title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Thread Programming in C++/CLR
|
<p>I am really struggling with Thread programming in Visual C++/CLR. I have searched a lot and found lots of material on the internet including the official resources however i am still confused. There are very few resources for C++/CLR. Most of them are for C# or old style C++. I try to run this simple code. I choose a new project of type clr console applicatioN and place the following code there but i am getting errors which i am not understading. </p>
<pre><code>// thread_clr.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System;
using namespace System::Threading;
class MessagePrinter;
// class ThreadTester demonstrates basic threading concepts
class ThreadTester
{
static int Main()
{
// Create and name each thread. Use MessagePrinter's
// Print method as argument to ThreadStart delegate.
MessagePrinter printer1 = gcnew MessagePrinter();
Thread thread1 = gcnew Thread ( gcnew ThreadStart( printer1.Print ) );
thread1.Name = "thread1";
MessagePrinter printer2 = gcnew MessagePrinter();
Thread thread2 = gcnew Thread ( gcnew ThreadStart( printer2.Print ) );
thread2.Name = "thread2";
MessagePrinter printer3 = gcnew MessagePrinter();
Thread thread3 = gcnew Thread ( gcnew ThreadStart( printer3.Print ) );
thread3.Name = "thread3";
Console.WriteLine( "Starting threads" );
// call each thread's Start method to place each
// thread in Started state
thread1.Start();
thread2.Start();
thread3.Start();
Console.WriteLine( "Threads started\n" );
} // end method Main
}; // end class ThreadTester
class MessagePrinter
{
private int sleepTime;
private static Random random = gcnew Random();
// constructor to initialize a MessagePrinter object
public MessagePrinter()
{
// pick random sleep time between 0 and 5 seconds
sleepTime = random.Next( 5001 );
}
//controls Thread that prints message
public void Print()
{
// obtain reference to currently executing thread
Thread current = Thread.CurrentThread;
// put thread to sleep for sleepTime amount of time
Console.WriteLine(current.Name + " going to sleep for " + sleepTime );
Thread.Sleep ( sleepTime );
// print thread name
Console.WriteLine( current.Name + " done sleeping" );
} // end method Print
} // end class MessagePrinter
</code></pre>
<p>Please help. Or better still please guide me to some tutorials or something to that affect. I understand SO is not a tutorial site and i am not asking one but i would appreciate if some one could atleast point out the resources for C++/CLR thread. C++/CLR Winform Threads. Would really appreciate it</p>
<p>Regards</p>
<p>Some errors are:</p>
<blockquote>
<p>'printer1' uses undefined class 'MessagePrinter' 'Print' : is not a
member of 'System::Int32' 'System::Threading::ThreadStart' : a
delegate constructor expects 2 argument(s)
'System::Threading::Thread::Thread' : no appropriate default
constructor available 'System::Threading::Thread::Thread' : no
appropriate default constructor available 'syntax error : 'int' should
be preceded by ':' 'cannot declare a managed 'random' in an unmanaged
'MessagePrinter'may not declare a global or static variable, or a
member of a native type that refers to objects in the gc heap
'MessagePrinter::random' : you cannot embed an instance of a reference
type, 'System::Random', in a native type 'MessagePrinter::random' :
only static const integral data members can be initialized within a
class 'MessagePrinter' should be preceded by ':' 'void' should be
preceded by ':'</p>
</blockquote>
| 0 | 1,189 |
Java RMI cannot bind server
|
<p>I'm working on Java RMI application, and having problem binding a server to the registry. I'm working on eclipse using rmi plugin, and everything worked fine before I had to format my pc. Also, I'm sure the code is ok since it's the one given to me as a solution, so there must be something wrong with my configuration.
Here's the code:</p>
<pre><code>public static void main (String[] args){
try{
RMIChatServer myObject = new RMIChatServerImpl();
System.setSecurityManager(new RMISecurityManager());
Naming.rebind("Hello", myObject);
System.out.println("Remote object bound to registry");
}
catch( Exception e){
System.out.println("Failed to register object " + e);
e.printStackTrace();
System.exit(1);
}
}
</code></pre>
<p>Exceptions it gives:</p>
<pre><code>Failed to register object java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: access to class loader denied
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: access to class loader denied
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:419)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
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:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
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:377)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at java.rmi.Naming.rebind(Naming.java:177)
at RMIChatServerImpl.main(RMIChatServerImpl.java:175)
Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: access to class loader denied
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:409)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
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:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassNotFoundException: access to class loader denied
at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:447)
at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:184)
at java.rmi.server.RMIClassLoader$2.loadClass(RMIClassLoader.java:637)
at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:264)
at sun.rmi.server.MarshalInputStream.resolveClass(MarshalInputStream.java:216)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1593)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1750)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
... 13 more
Caused by: java.security.AccessControlException: access denied ("java.io.FilePermission" "\D:\uni\YEAR 3\Enterprise Programming\java\czat solution 2\bin\-" "read")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:366)
at java.security.AccessController.checkPermission(AccessController.java:555)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at sun.rmi.server.LoaderHandler$Loader.checkPermissions(LoaderHandler.java:1176)
at sun.rmi.server.LoaderHandler$Loader.access$000(LoaderHandler.java:1130)
at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:411)
... 22 more
</code></pre>
<p>I researched the problem and most say that it's because of codebase settings (I also use security policy), I have tried different settings, and currently using 'compute from classpath' option provided by rmi plugin, which worked before, but fails now :( Please advice!</p>
| 0 | 1,935 |
Why does my Android service get restarted when the process is killed, even though I used START_NOT_STICKY?
|
<p>My app uses a pattern where I start a service with <a href="http://developer.android.com/reference/android/content/Context.html#startService%28android.content.Intent%29" rel="noreferrer">Context#startService()</a> as well as bind to it with <a href="http://developer.android.com/reference/android/content/Context.html#bindService%28android.content.Intent,%20android.content.ServiceConnection,%20int%29" rel="noreferrer">Context#bindService()</a>. This is so that I can control the lifetime of the service independently from whether any clients are currently bound to it. However, I noticed recently that whenever my app is killed by the system, it soon restarts any services that were running. At this point the service will never be told to stop, and this is causing battery drain whenever it happens. Here's a minimal example:</p>
<p>I found someone with a similar issue <a href="https://groups.google.com/forum/?fromgroups=#!topic/android-developers/x4pYZcXeKsw" rel="noreferrer">here</a>, but it wasn't ever diagnosed or solved.</p>
<p>Service:</p>
<pre><code>@Override
public void onCreate() {
Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return new Binder();
}
</code></pre>
<p>Activity:</p>
<pre><code>@Override
protected void onStart() {
super.onStart();
Intent service = new Intent(this, BoundService.class);
startService(service);
bindService(service, mServiceConnection, 0);
}
@Override
protected void onStop() {
unbindService(mServiceConnection);
Toast.makeText(this, "unbindService", Toast.LENGTH_SHORT).show();
super.onStop();
}
</code></pre>
<p>To test it, I launched the app, which started the service and bound to it. Then I backed out of the app, which unbinds (but leaves the service running). Then I did</p>
<pre><code>$ adb shell am kill com.tavianator.servicerestart
</code></pre>
<p>and sure enough, 5 seconds later, the "onCreate" toast appears, indicating that the service started again. Logcat shows this:</p>
<pre><code>$ adb logcat | grep BoundService
W/ActivityManager( 306): Scheduling restart of crashed service com.tavianator.servicerestart/.BoundService in 5000ms
I/ActivityManager( 306): Start proc com.tavianator.servicerestart for service com.tavianator.servicerestart/.BoundService: pid=20900 uid=10096 gids={1028}
</code></pre>
<p>If I replace the startService() pattern with BIND_AUTO_CREATE, the problem doesn't occur (even if I crash the app while it's still bound to the service). It also works if I never bind to the service. But the combination of start, bind, and unbind seems to never let my service die.</p>
<p>Using dumpsys before killing the app shows this:</p>
<pre><code>$ adb shell dumpsys activity services com.tavianator.servicerestart
ACTIVITY MANAGER SERVICES (dumpsys activity services)
Active services:
* ServiceRecord{43099410 com.tavianator.servicerestart/.BoundService}
intent={cmp=com.tavianator.servicerestart/.BoundService}
packageName=com.tavianator.servicerestart
processName=com.tavianator.servicerestart
baseDir=/data/app/com.tavianator.servicerestart-2.apk
dataDir=/data/data/com.tavianator.servicerestart
app=ProcessRecord{424fb5c8 20473:com.tavianator.servicerestart/u0a96}
createTime=-20s825ms lastActivity=-20s825ms
executingStart=-5s0ms restartTime=-20s825ms
startRequested=true stopIfKilled=true callStart=true lastStartId=1
Bindings:
* IntentBindRecord{42e5e7c0}:
intent={cmp=com.tavianator.servicerestart/.BoundService}
binder=android.os.BinderProxy@42aee778
requested=true received=true hasBound=false doRebind=false
</code></pre>
| 0 | 1,260 |
how to make junit test run methods in order
|
<p>guys! I have a new question for you. I'm adding some data to cache using different cache managers and I'm facing the problem with it. I'm doing it using junit and spring. When I run the test, the test methods are executed randomly, but I need them to be executed in order. How to do it?? Here is some code and a proving console output:</p>
<p>Service class:</p>
<pre><code>@Service("HelloCache")
public class CacheServiceImpl implements CacheInterface {
@Autowired
@Qualifier("memcachedClient")
private MemcachedClient mBean;
public void Add(String key, Object object) {
mBean.set(key, 12, object);
}
public void Get(String key) {
mBean.get(key);
}
public void Delete(String key) {
mBean.delete(key);
}
}
</code></pre>
<p>Here is the test: </p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "file:src/main/java/spring.xml")
public class UsingMemcachedTest extends TestCase {
@Autowired
@Qualifier("HelloCache")
private CacheInterface emcached;
private byte[][] i = new byte[2500][3000];
private String key = "j";
@Test
public void testAddBulkObjects() {
System.out.println("");
System.out.println("This is async BULK adding test");
long time = System.currentTimeMillis();
for (int k=1; k<=1000; k++) {
emcached.Add(key+k, i);
}
long time2 = System.currentTimeMillis();
long timeE=time2-time;
System.out.println("Vremya add BULK objects: " + timeE);
System.out.println("");
}
@Test
public void testGetBulkObjects() {
System.out.println("");
System.out.println("This is getting BULK objects test");
long time = System.currentTimeMillis();
for (int k=1; k<=1000; k++) {
emcached.Get(key+k);
}
long time2 = System.currentTimeMillis();
long timeE=time2-time;
System.out.println("Vremya Get object: " + timeE);
System.out.println("");
}
@Test
public void testDeleteBulkObjects() {
System.out.println("");
System.out.println("This is deleting BULK objects test");
long time = System.currentTimeMillis();
for (int k=1; k<=1000; k++) {
emcached.Delete(key+k);
}
long time2 = System.currentTimeMillis();
long timeE=time2-time;
System.out.println("Vremya delete object: " + timeE);
System.out.println("");
}
</code></pre>
<p>And the output: </p>
<pre><code>This is deleting BULK objects test
Vremya delete object: 137
This is getting BULK objects test
Vremya Get object: 703
This is async BULK adding test
Vremya add BULK objects: 87681
</code></pre>
<p>Please, HELP!! =)</p>
| 0 | 1,159 |
Using Unity3D's IPointerDownHandler approach, but with "the whole screen"
|
<p>In Unity say you need to detect finger touch (finger drawing) on something in the scene.</p>
<p>The only way to do this <strong>in modern Unity, is very simple</strong>:</p>
<hr>
<p><strong>Step 1</strong>. Put a collider on that object. ("The ground" or whatever it may be.) <sup>1</sup></p>
<p><strong>Step 2.</strong> On your camera, Inspector panel, click to add a Physics Raycaster (2D or 3D as relevant).</p>
<p><strong>Step 3.</strong> Simply use code as in Example A below.</p>
<p><em>(Tip - don't forget to ensure there's an EventSystem ... sometimes Unity adds one automatically, sometimes not!)</em></p>
<hr>
<p>Fantastic, couldn't be easier. Unity finally handles un/propagation correctly through the UI layer. Works uniformly and flawlessly on desktop, devices, Editor, etc etc. Hooray Unity.</p>
<p>All good. But what if you want to draw just <strong>"on the screen"</strong>?</p>
<p>So you are wanting, quite simply, swipes/touches/drawing from the user "on the screen". (Example, simply for operating an orbit camera, say.) So just as in any ordinary 3D game where the camera runs around and moves.</p>
<p>You don't want the position of the finger on <strong>some object</strong> in world space, you simply want abstract "finger motions" (i.e. position on the glass).</p>
<p>What collider do you then use? Can you do it with no collider? It seems fatuous to add a collider just for that reason.</p>
<p><strong>What we do is this</strong>:</p>
<p>I just make a flat collider of some sort, and actually attach it <strong>under the camera</strong>. So it simply sits in the camera frustum and completely covers the screen.</p>
<p><a href="https://i.stack.imgur.com/wQOv4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wQOv4.png" alt="enter image description here"></a></p>
<p>(For the code, there is then no need to use ScreenToWorldPoint, so just use code as in Example B - extremely simple, works perfectly.)</p>
<p>My question, it seems a bit odd to have to use the "under-camera colldier" I describe, just to get touches on the glass.</p>
<p>What's the deal here?</p>
<p>(Note - please don't answer involving Unity's ancient "Touches" system, which is unusable today for real projects, you can't ignore .UI using the legacy approach.)</p>
<hr>
<p>Code sample A - drawing on a scene object. Use ScreenToWorldPoint.</p>
<pre><code> using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FingerMove:MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
public void OnPointerDown (PointerEventData data)
{
Debug.Log("FINGER DOWN");
prevPointWorldSpace =
theCam.ScreenToWorldPoint( data.position );
}
public void OnDrag (PointerEventData data)
{
thisPointWorldSpace =
theCam.ScreenToWorldPoint( data.position );
realWorldTravel =
thisPointWorldSpace - prevPointWorldSpace;
_processRealWorldtravel();
prevPointWorldSpace = thisPointWorldSpace;
}
public void OnPointerUp (PointerEventData data)
{
Debug.Log("clear finger...");
}
</code></pre>
<p>Code sample B ... you only care about what the user does on the glass screen of the device. Even easier here:</p>
<pre><code> using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FingerMove:MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
private Vector2 prevPoint;
private Vector2 newPoint;
private Vector2 screenTravel;
public void OnPointerDown (PointerEventData data)
{
Debug.Log("FINGER DOWN");
prevPoint = data.position;
}
public void OnDrag (PointerEventData data)
{
newPoint = data.position;
screenTravel = newPoint - prevPoint;
prevPoint = newPoint;
_processSwipe();
}
public void OnPointerUp (PointerEventData data)
{
Debug.Log("FINEGR UP...");
}
private void _processSwipe()
{
// your code here
Debug.Log("screenTravel left-right.. " + screenTravel.x.ToString("f2"));
}
}
</code></pre>
<hr>
<p><sup>1</sup> If you're just new to Unity: at that step very likely, make it a layer called say "Draw"; in physics settings make "Draw" interact with nothing; in step two with the Raycaster just set the layer to "Draw".</p>
| 0 | 1,557 |
How to use jasper-reports with spring MVC?
|
<p>I want to generate a report using jasper-reports and i can't figure what information should contain the controller, because when i a create the report i am using as data source the result set of a query. </p>
<p>reports.jsp</p>
<pre><code><%@ include file="/WEB-INF/template/taglibs.jsp"%>
<div class="container">
<%@ include file="menu.jsp"%>
<div class="budgetTable">
<div class="form-group ">
<a class="btn btn-warning buttons generate"
href="http://localhost:8080/Catering/index/reports/fullreport/pdf">Generate
full report </a>
</div>
<div class="form-group">
<a class="btn btn-warning buttons generate"
href="http://localhost:8080/Catering/index/reports/partialreport/pdf">Generate
partial report </a>
</div>
<div class="form-group">
<a class="btn btn-warning buttons generate"
href="http://localhost:8080/Catering/index/reports/anotherreport/pdf">Generate
another report </a>
</div>
</div>
</div>
</code></pre>
<p>ReportsController.java</p>
<pre><code>package catering.web.controller;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ReportsController {
protected static Logger logger = Logger.getLogger("controller");
@RequestMapping(value="reports", method = RequestMethod.GET)
public String reportsGet(Model model, Authentication authentication){
logger.debug("Received request to show reports page(GET)");
model.addAttribute("username", "You are logged in as " + authentication.getPrincipal());
return "reports";
}
@RequestMapping(value = "/reports/fullreport/pdf", method = RequestMethod.GET)
public ModelAndView fullReport(ModelAndView model){
logger.debug("Received request to download PDF report");
//List<UserModelSummary> users = UserSummaryDataAccess.getUsersSummary();
//JRDataSource ds = new JRBeanCollectionDataSource(users);
//Map<String, Object> parameterMap = new HashMap<String, Object>();
//parameterMap.put("datasource", ds);
//model = new ModelAndView("pdfReport",parameterMap);
return model;
}
}
</code></pre>
<p>jasper-views.xml</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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="pdfReport" class="org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView"
p:url="classpath:fullReport.jrxml"
p:reportDataKey="datasource">
</bean>
</beans>
</code></pre>
<p>fullReport.jrxml</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version last-->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="fullReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="2a2f56d0-72e3-4ccf-942d-bf77c76956aa">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="cateringTest"/>
<queryString>
<![CDATA[select u.iduser, u.firstname, u.lastname, u.username from user u]]>
</queryString>
<field name="iduser" class="java.lang.Integer">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="firstname" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="lastname" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="username" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="80" splitType="Stretch">
<staticText>
<reportElement x="0" y="60" width="80" height="20" uuid="62c1f51a-4917-456f-8c14-e8df054a02ea"/>
<text><![CDATA[Detailed Report]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="50" splitType="Stretch">
<staticText>
<reportElement x="0" y="29" width="80" height="20" uuid="5cbcc29e-c1fd-40e2-82b7-4faa4929cedb"/>
<text><![CDATA[ID]]></text>
</staticText>
<staticText>
<reportElement x="80" y="30" width="100" height="20" uuid="c6e2fa3b-a346-4a48-b0fd-5381ab527640"/>
<text><![CDATA[First name]]></text>
</staticText>
<staticText>
<reportElement x="180" y="29" width="100" height="20" uuid="2fe1f184-f577-4f47-bdf4-661b4d297738"/>
<text><![CDATA[Last name]]></text>
</staticText>
<staticText>
<reportElement x="280" y="29" width="100" height="20" uuid="e4187042-e081-4cba-bdd3-ffd54ef3594b"/>
<text><![CDATA[Username]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="25" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="100" height="20" uuid="24b51b0e-37f5-4636-910b-ce01fc427ce5"/>
<textFieldExpression><![CDATA[$F{iduser}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="80" y="0" width="100" height="20" uuid="d60cbff1-5d4e-45e3-bd0f-ccb833f7165d"/>
<textFieldExpression><![CDATA[$F{firstname}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="180" y="0" width="100" height="20" uuid="e6e56077-f6a1-4f23-923e-6eda1937d019"/>
<textFieldExpression><![CDATA[$F{lastname}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="280" y="0" width="100" height="20" uuid="697ab4a6-70a3-4eeb-b0fe-842d1b51f754"/>
<textFieldExpression><![CDATA[$F{username}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
</code></pre>
| 0 | 3,936 |
How do I show a label beyond a certain zoom level in Leaflet?
|
<p>I'm pretty new to the Leaflet library, and to JavaScript in general, and I'm stuck trying to figure out how to show/hide a leaflet Label based on the zoom level (and the markers are in a 'cluster' layer). </p>
<p>The markers are all loaded via AJAX callback and then I bind the popup and label using the <code>onEachFeature</code>, then I add the layer of geoJson markers to the map. </p>
<p>I'd like to only show the labels when zoomed in to some level, but I haven't had any luck. I also tried adding the <code>leaflet.zoomcss.js</code> but I guess I'm not using that correctly. </p>
<p><strong>Sample</strong></p>
<pre><code>var officesLayerGroup = L.markerClusterGroup();
var currentMakers;
function DiaplyLocalOffices(jqOffices) {
currentMakers = new L.geoJson(jqOffices, {
style: function (feature) {
var c = feature.properties.markercolor;
if (feature.properties.OfficeID == 0) {
c = 'yellow';
}
return { color: c };
},
pointToLayer: function (feature, latlng) {
return new L.CircleMarker(latlng, { radius: 7, fillOpacity: 0.5 });
},
onEachFeature: bindOfficePopup
});
officesLayerGroup.addLayer(currentMakers);
map.addLayer(officesLayerGroup);
}
function bindOfficePopup(feature, layer) {
// This function adds the popup based on the information in the 'layer' or marker
// Keep track of the layer(marker)
feature.layer = layer;
var props = feature.properties;
if (props) {
var desc = '<span id="feature-popup">';
//.. a bunch of other html added here!
var warn = props.Warning ? props.Warning : null;
if (warn !== null) {
desc += '<font size="4" color="red"><strong><em>' + warn + '</em></strong></font></br>';
}
desc += '</span>';
layer.bindPopup(desc);
layer.bindLabel('Hi Label!', { noHide: true, className: 'my-css-styled-labels'});
}
}
</code></pre>
<p>I've also tried adding it like this but that didn't work either:</p>
<pre><code> layer.on({
zoomend: showLabel(e)
});
</code></pre>
<p>and then a quickie function:</p>
<pre><code>function showLabel(e) {
z = map.getZoom();
if (z > 6) {
layer.bindLabel("HIYA", { noHide: true, className: 'my-css-styled-labels' });
}
}
</code></pre>
<p>But no luck, even when adding the library and CSS styles for <code>leaflet.zoomcss.js</code></p>
<p>Sorry for being lengthy, but any help would be really appreciated! </p>
| 0 | 1,073 |
Spring MVC @RequestMapping not working
|
<p>I have a strange scenario in which my controller is not invoked unless I map the dispatcher servlet to /* in web.xml. I have defined a controller with a RequestMapping:</p>
<pre><code>@Controller
public class UserController {
@RequestMapping(value = "/rest/users", method = RequestMethod.GET)
public ModelAndView getUsers(HttpServletRequest request) throws RestException {
...
}
}
</code></pre>
<p>And an application context:</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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.test.rest.controller" />
</code></pre>
<p>Finally this is mapped in web.xml:</p>
<pre><code><servlet>
<servlet-name>rest-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/restContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</code></pre>
<p>This works as expected i.e. I can make requests to /rest/users. However if I change the web.xml mapping to:</p>
<pre><code><servlet-mapping>
<servlet-name>rest-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</code></pre>
<p>I get an MVC error:</p>
<blockquote>
<p>WARN servlet.PageNotFound: No mapping found for HTTP request with URI
[/rest/users] in DispatcherServlet with name 'rest-servlet'.</p>
</blockquote>
<p>It seems really strange because the error indicates that the request is being mapped to the dispatcher-servlet, yet the only thing that has changed is the servlet mapping. </p>
<p>Has anyone else encountered this?</p>
| 0 | 1,114 |
MVC 3 client side validation, model binding decimal value and culture (different decimal separator)
|
<p>I am trying to have my client side validation (model binding) to support different cultures, and I found an interesting blog on the subject on which I am trying to implement.</p>
<p><a href="http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx" rel="noreferrer">http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx</a></p>
<p>Poco</p>
<pre><code> public class Jogador
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}
</code></pre>
<p>I've got my custom DecimalModelBinder class</p>
<pre><code> public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState {Value = valueResult};
object actualValue = null;
try
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
</code></pre>
<p>My web.config:</p>
<p>
</p>
<p>
</p>
<p>
</p>
<pre><code><compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</code></pre>
<p></p>
<p>
</p>
<p>
</p>
<p>Global.asax are altered to use my custom ModelBinder on decimal and decimal? values</p>
<pre><code>protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
</code></pre>
<p>Still the client-side validation fails on decimal entered in my view with a "," as a decimal separator. It does not handle both "," and ".". The js validation does not seem to take my custom binding in consideration</p>
<p>Reading the blog article over and over again, I just can't seem to figure out what I am missing.</p>
<p>Here is the view:</p>
<pre><code>@model MVC_Empty.Web.Models.Jogador
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Jogador</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Salary)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Salary)
@Html.ValidationMessageFor(model => model.Salary)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</code></pre>
<p>Server side validation seems fine, but how to handle the client-side validation in order to send a POST when clicking the submit button.</p>
<p>The javascript validation does not handle the comma.<img src="https://i.stack.imgur.com/wVpyh.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/sA07n.png" alt="enter image description here"></p>
| 0 | 2,149 |
C free() invalid next size (normal)
|
<p>I'm fairly new to C and I can't seem to figure out what seems to be a pretty simple pointer problem. My program adds line numbers to a file. It reads in the file line by line and then adds a line number to the beginning of each line. It works fine on each file individually as you can see below:</p>
<pre><code>soccer@soccer-Dell-DV051:~/code C$ ./a.out test.c
soccer@soccer-Dell-DV051:~/code C$ ./a.out miscellaneousHeader.h
soccer@soccer-Dell-DV051:~/code C$ ./a.out test.c miscellaneousHeader.h
*** Error in `./a.out': free(): invalid next size (normal): 0x08648170 ***
Segmentation fault (core dumped)
soccer@soccer-Dell-DV051:~/code C$
</code></pre>
<p>but when I run them together I get the above error. The following code is my program.</p>
<p>Compiler.c:</p>
<pre><code>#include <stdio.h>
#include "lineNumAdderHeader.h"
#include "miscellaneousHeader.h"
int main(int argc, char *argv[]){
if (argc < 2)
fatal("in main(). Invalid number of arguments");
int i = 1;
while (i < argc){
lineNumAdder(argv[i]);
i++;
}
}
</code></pre>
<p>I have narrowed the problem to the <code>lineNumPtr</code>. The error occurs when <code>lineNumPtr</code> is freed after the second file. If <code>lineNumPtr</code> is not freed, which I know is bad programming, the program works just fine.</p>
<p>lineNumAdder.c:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "miscellaneousHeader.h"
#include "lineNumAdderHeader.h"
int lineSizeChecker(FILE*, int);
int lineNumChecker(char*);
int fileSizeChecker(FILE*);
void lineNumAdder(char* filename){
int lineSpace, position, lineNumCheckerBoolean, numOfDigits, fileSpace;
int lineNum = 1;
char *lineNumPtr = NULL;
char *numberedFile = NULL;
char *nonNumberedLine = NULL;
char *originalLine = NULL;
FILE *file = errorCheckedFopen(filename, "r+w");
while(1){
position = ftell(file);
if (position == 0){
fileSpace = fileSizeChecker(file);
numberedFile = errorCheckedMalloc(fileSpace);
}
lineSpace = lineSizeChecker(file, position);
if (position == 0)
originalLine = errorCheckedMalloc(lineSpace);
else
originalLine = realloc(originalLine, lineSpace);
if (fgets(originalLine, lineSpace, file) == NULL)
break;
lineNumCheckerBoolean = lineNumChecker(originalLine);
if (lineNumCheckerBoolean == 0){
if (position == 0)
nonNumberedLine = errorCheckedMalloc(lineSpace - 9);
else
nonNumberedLine = realloc(nonNumberedLine, lineSpace - 9);
strcpy(nonNumberedLine, &originalLine[9]);
}
else{
if (position == 0)
nonNumberedLine = errorCheckedMalloc(lineSpace);
else
nonNumberedLine = realloc(nonNumberedLine, lineSpace);
strcpy(nonNumberedLine, originalLine);
fileSpace += 8;
numberedFile = realloc(numberedFile, fileSpace);
}
numOfDigits = intDigitFinder(lineNum);
if (position == 0)
lineNumPtr = errorCheckedMalloc(numOfDigits);
else
lineNumPtr = realloc(lineNumPtr, numOfDigits);
sprintf(lineNumPtr, "%d", lineNum);
strcat(numberedFile, "/*");
strcat(numberedFile, lineNumPtr);
strcat(numberedFile, "*/");
if (lineNum < 10)
strcat(numberedFile, " ");
else if (lineNum >= 10 && lineNum < 100)
strcat(numberedFile, " ");
else if (lineNum >= 100 && lineNum < 1000)
strcat(numberedFile, " ");
else if (lineNum >= 1000 && lineNum < 10000)
strcat(numberedFile, " ");
strcat(numberedFile, nonNumberedLine);
lineNum++;
}
fclose(file);
free(originalLine);
free(nonNumberedLine);
free(lineNumPtr);
free(numberedFile);
}
int lineNumChecker(char *comment){
if (sizeOf(comment) < 8)
return 1;
if (comment[7] == '/' || comment[6] == '/' || comment[5] == '/' || comment[4] == '/')
return 0;
else
return 1;
}
int lineSizeChecker(FILE *file, int position){
int i = 2;
int ch;
while ((ch = fgetc(file)) != '\n' && ch != EOF)
i++;
fseek(file, position, SEEK_SET);
return i;
}
int fileSizeChecker(FILE *file){
int i = 2;
while (fgetc(file) != EOF)
i++;
fseek(file, 0, SEEK_SET);
return i;
}
</code></pre>
<p>miscellaneous.c:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "miscellaneousHeader.h"
void fatal(char*);
int sizeOf(char *data){
int i = 1;
while(data[i-1] != '\n')
i++;
return i;
}
void *errorCheckedMalloc(size_t size){
void *ptr = malloc(size);
if (ptr == NULL)
fatal("in errorCheckedMalloc(). Memory Allocation Failure\n");
else
return ptr;
}
FILE *errorCheckedFopen(char *filename, char *mode){
FILE *file = fopen(filename, mode);
if (file == NULL)
fatal("in errorCheckedFopen(). File Opening Failure\n");
else
return file;
}
void fatal(char *errorMessage){
char* completedErrorMessage = errorCheckedMalloc(sizeOf(errorMessage)+17);
strcpy(completedErrorMessage, "[!!] Fatal Error ");
strcat(completedErrorMessage, errorMessage);
perror(completedErrorMessage);
free(completedErrorMessage);
exit(-1);
}
int intDigitFinder(int num){
int digits = 0;
do {
num /= 10;
digits++;
} while (num != 0);
return digits;
}
void *reMalloc(void *ptr, size_t size){
char buf[strlen(ptr) + 1];
strcpy(buf, ptr);
free(ptr);
ptr = errorCheckedMalloc(size);
if(size >= strlen(buf))
strcpy(ptr, buf);
return ptr;
}
</code></pre>
<p>I apologize for the length. This is my first post and I wanted to make sure that I provided enough information for you guys to give me the best answers possible. Thank you for any and all answers. They are much appriciated.</p>
| 0 | 2,672 |
Visual Studio Code [eslint] Delete 'CR' [prettier/prettier] on windows
|
<p><a href="https://i.stack.imgur.com/OeH4N.png" rel="noreferrer">Eslint error in vscode terminal</a></p>
<p>Getting ESLint error of CR - even if I have the git pull code with windows line endings.</p>
<p>This occurs on Visual Studio Code with EsLint plugin (1.7.0)
This did not occur until I recently update my git to the latest version(2.20.0).windows.1</p>
<p>My eslintrc file</p>
<pre><code> {
"plugins": [
"jsx-a11y",
"react",
"prettier"
],
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"prettier"
],
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true,
"generators": true,
"experimentalObjectRestSpread": true
}
},
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"node": true,
"jquery": true
},
"globals": {
"define": true
},
"rules": {
"array-callback-return": 1,
"camelcase": 2,
"complexity": 1,
"consistent-this": [
1,
"self"
],
"curly": 2,
"dot-notation": 1,
"eqeqeq": 2,
"func-names": [
1,
"never"
],
"func-style": [
2,
"expression"
],
"linebreak-style": ["error", "windows"],
"max-depth": [1, 10],
"max-len": [
1,
{
"code": 120,
"ignoreUrls": true
}
],
"max-nested-callbacks": [
1,
3
],
"max-params": [
1,
3
],
"max-statements-per-line": [
1,
{
"max": 1
}
],
"new-cap": 2,
"newline-after-var": 1,
"newline-before-return": 1,
"no-alert": 2,
"no-array-constructor": 2,
"no-bitwise": 2,
"no-caller": 2,
"no-catch-shadow": 2,
"no-cond-assign": [
2,
"except-parens"
],
"no-console": 2,
"no-continue": 2,
"no-duplicate-imports": 2,
"no-else-return": 1,
"no-eq-null": 2,
"no-eval": 2,
"no-extend-native": 2,
"no-extra-bind": 2,
"no-floating-decimal": 1,
"no-global-assign": 2,
"no-implicit-coercion": 1,
"no-implicit-globals": 2,
"no-implied-eval": 2,
"no-iterator": 2,
"no-labels": 2,
"no-lone-blocks": 1,
"no-lonely-if": 2,
"no-loop-func": 2,
"no-magic-numbers": 0,
"no-mixed-operators": 0,
"no-multi-str": 1,
"no-native-reassign": 2,
"no-negated-condition": 1,
"no-nested-ternary": 2,
"no-new-func": 2,
"no-new-object": 2,
"no-new-wrappers": 2,
"no-octal-escape": 2,
"no-param-reassign": 2,
"no-undef": 2,
"no-proto": 2,
"no-return-assign": 2,
"no-return-await": 1,
"no-script-url": 2,
"no-self-compare": 2,
"no-sequences": 2,
"no-shadow": 2,
"no-shadow-restricted-names": 2,
"no-tabs": 1,
"no-template-curly-in-string": 1,
"no-throw-literal": 1,
"no-undef-init": 1,
"no-undefined": 1,
"no-underscore-dangle": 1,
"no-unmodified-loop-condition": 2,
"no-unneeded-ternary": 1,
"no-unsafe-negation": 1,
"no-unused-expressions": 2,
"no-unused-vars": 2,
"no-use-before-define": 2,
"no-useless-call": 2,
"no-useless-computed-key": 1,
"no-useless-constructor": 1,
"no-useless-concat": 1,
"no-useless-escape": 1,
"no-useless-rename": 1,
"no-useless-return": 1,
"no-var": 2,
"no-void": 2,
"no-warning-comments": 1,
"no-with": 2,
"object-shorthand": 1,
"one-var": [
2,
"never"
],
"prefer-arrow-callback": 1,
"prefer-const": 1,
"prefer-rest-params": 1,
"prefer-spread": 1,
"prefer-template": 1,
"prettier/prettier": ["error", {
"printWidth": 120,
"singleQuote": true
}],
"quotes": [
2,
"single"
],
"radix": [
1,
"as-needed"
],
"require-await": 1,
"spaced-comment": [
1,
"always"
],
"strict": [
2,
"safe"
],
"yoda": [
1,
"never"
],
"react/jsx-equals-spacing": ["warn", "never"],
"react/jsx-no-duplicate-props": ["warn", { "ignoreCase": true }],
"react/jsx-no-undef": "warn",
"react/jsx-pascal-case": ["warn", { "allowAllCaps": true, "ignore": [] }],
"react/jsx-space-before-closing": "warn",
"react/jsx-uses-react": "warn",
"react/jsx-uses-vars": "warn",
"react/no-danger-with-children": "warn",
"react/no-deprecated": "warn",
"react/no-direct-mutation-state": "warn",
"react/no-is-mounted": "warn",
"react/react-in-jsx-scope": "error",
"react/require-render-return": "warn",
"react/style-prop-object": "warn",
"jsx-a11y/anchor-has-content": "warn",
"jsx-a11y/aria-props": "warn",
"jsx-a11y/aria-proptypes": "warn",
"jsx-a11y/aria-role": "warn",
"jsx-a11y/aria-unsupported-elements": "warn",
"jsx-a11y/click-events-have-key-events": "warn",
"jsx-a11y/heading-has-content": "warn",
"jsx-a11y/href-no-hash": "warn",
"jsx-a11y/html-has-lang": "warn",
"jsx-a11y/img-has-alt": "warn",
"jsx-a11y/img-redundant-alt": "warn",
"jsx-a11y/label-has-for": "warn",
"jsx-a11y/lang": "warn",
"jsx-a11y/mouse-events-have-key-events": "warn",
"jsx-a11y/no-access-key": "warn",
"jsx-a11y/no-marquee": "warn",
"jsx-a11y/no-onchange": "warn",
"jsx-a11y/no-static-element-interactions": "warn",
"jsx-a11y/onclick-has-focus": "warn",
"jsx-a11y/onclick-has-role": "warn",
"jsx-a11y/role-has-required-aria-props": "warn",
"jsx-a11y/role-supports-aria-props": "warn",
"jsx-a11y/scope": "warn",
"jsx-a11y/tabindex-no-positive": "warn"
}
}
</code></pre>
<p>I have been trying to fix this issue by trying to get rid of this by line ends using the linebreak-style: "all combinations i.e. 0, 1, ["error","windows"], off, warn"</p>
| 0 | 2,968 |
How to do validation with mat-checkbox?
|
<p>I would like to know how to check if the checkbox was selected, if it was not selected, an error message will appear for the user.
I managed to put the error message but not to able to use it along with the rest of the form.
can you help me?
Here's what I have to do.</p>
<pre><code><mat-checkbox class="hcs-full-width" [formControl]="termsFormControl"> Aceite os termos de uso
</mat-checkbox>
<mat-error *ngIf="termsFormControl.hasError('required')">
Termo é
<strong>requirido</strong>
</mat-error>
</code></pre>
<p>.ts</p>
<pre><code>export class AppComponent implements OnInit {
private subscription: Subscription;
uri: string;
ssid: string;
sessiondId: string;
ip: string;
mac: string;
ufi: string;
mgmtBaseUrl: string;
clientRedirectUrl: string;
req: string;
userName: string;
hmac: string;
name: string;
email: string;
constructor(@Inject(DOCUMENT) private document: any, private route: ActivatedRoute) {
}
ngOnInit() {
this.route.queryParams
.filter(params => params.mac)
.subscribe(params => {
console.log(params);
this.ssid = params.ssid;
this.sessiondId = params.sessionId;
this.ip = params.ip;
this.mac = params.mac;
this.ufi = params.ufi;
this.mgmtBaseUrl = params.mgmtBaseUrl;
this.clientRedirectUrl = params.clientRedirectUrl;
this.req = params.req;
this.hmac = params.hmac;
});
console.log("LOGAR: " + this.nameFormControl.valid);
console.log("LOGAR: " + this.termsFormControl.valid);
}
Logar() {
if (this.nameFormControl.valid && this.emailFormControl.valid && this.termsFormControl.valid) {
this.userName = this.name + ";" + this.email;
this.uri = "#" + this.ssid + "&sessionId=" + this.sessiondId + "&ip=" + this.ip + "&mac=" + this.mac + "&ufi=" + this.ufi + "&mgmtBaseUrl=" + this.mgmtBaseUrl + "&clientRedirectUrl=" + this.clientRedirectUrl + "&req=" + this.req + "&username=" + this.userName + "&hmac=" + this.hmac;
// console.log("LOGAR: " + this.nameFormControl.valid);
this.document.location.href = this.uri;
}
console.log("LOGAR: " + this.nameFormControl.valid);
console.log("LOGAR: " + this.termsFormControl.valid);
};
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
nameFormControl = new FormControl('', [
Validators.required,
]);
termsFormControl = new FormControl('', [
Validators.required,
]);
}
</code></pre>
| 0 | 1,036 |
Yii2 Form in Modal Window
|
<p>I would like to understand the basics of how to work with form from Modal window in Yii2? This is my current understanding and I will be grateful if someone can explain me what I missed.
So, I have a ListView with records. Each record contains a button. The button opens a Modal with a Form inside:</p>
<pre><code>echo Html::a('<span class="glyphicon glyphicon-bell" aria-hidden="true"></span>', ['#'],[
'id' => $model->id,
'class' => 'linkbutton',
'data-toggle'=>'modal',
'data-tooltip'=>'true',
'data-target'=>'#submit_vote'.$model->id,
'title'=> 'Assign'
]);
Modal::begin([
'size' => 'modal-lg',
'options' => [
'id' => 'submit_vote'.$model->id,
],
'header' => '<h2>Create Vote</h2>',
'footer' => 'Footer'
]);
ActiveForm::begin([
'action' => 'vote/vote',
'method' => 'post',
'id' => 'form'.$model->id
]);
echo Html::input(
'type: text',
'search',
'',
[
'placeholder' => 'Search...',
'class' => 'form-control'
]
);
echo Html::submitButton(
'<span class="glyphicon glyphicon-search"></span>',
[
'class' => 'btn btn-success',
]
);
ActiveForm::End();
Modal::end();
</code></pre>
<p>In Form 'action' I wrote vote/vote and method post. So I expect post data inside actionVote function of my VoteController.</p>
<pre><code>public function actionVote()
{
if (Yii::$app->request->post()) {
$id = Yii::$app->request->post('search');
Yii::$app->session->setFlash('error', $id);
return true;
}
}
</code></pre>
<p>For submitting I use an ajax:</p>
<pre><code>$('form').on('submit', function () {
alert($(this).attr('id')+$(this).attr('action')+$(this).serialize()); //just to see what data is coming to js
if($(this).attr('id') !== 'searchForm') { //some check
$.ajax({
url: $(this).attr('action'),
type: 'post',
data: $(this).serialize(),
success: function(){
$("#submit_vote15").modal('hide'); //hide popup
},
});
return false;
}
</code></pre>
<p>But after click on Submit form I see two alerts. Modal also not hidden. Flash message also is not showed.
What I am doing wrong? Can anyone clearly explain a step by step procedure of data flow? For now my understanding is:</p>
<ol>
<li>Open Modal;</li>
<li>Click Form Submit inside Modal;</li>
<li>Load data via ajax to controller action;</li>
<li>catch data from post and execute controller action code;
What I missed?</li>
</ol>
| 0 | 1,830 |
How to set timeout on event onChange
|
<p>I have a gallery that show images, and i have a search textbox
Im Trying to use Timeout on Input event to prevent the api call on every letter im typing :
I try to handle the event with doSearch function onChange: but now I cant write anything on the textbox and it cause many errors
Attached to this session the app and gallery components</p>
<p>Thanks in advance</p>
<pre><code>class App extends React.Component {
static propTypes = {
};
constructor() {
super();
this.timeout = 0;
this.state = {
tag: 'art'
};
}
doSearch(event){
var searchText = event.target.value; // this is the search text
if(this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(function(){this.setState({tag: event.target.value})} , 500);
}
render() {
return (
<div className="app-root">
<div className="app-header">
<h2>Gallery</h2>
<input className="input" onChange={event => this.doSearch(event)} value={this.state.tag}/>
</div>
<Gallery tag={this.state.tag}/>
</div>
);
}
}
export default App;
</code></pre>
<p>This is the Gallery class:</p>
<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import Image from '../Image';
import './Gallery.scss';
class Gallery extends React.Component {
static propTypes = {
tag: PropTypes.string
};
constructor(props) {
super(props);
this.state = {
images: [],
galleryWidth: this.getGalleryWidth()
};
}
getGalleryWidth(){
try {
return document.body.clientWidth;
} catch (e) {
return 1000;
}
}
getImages(tag) {
const getImagesUrl = `services/rest/?method=flickr.photos.search&api_key=522c1f9009ca3609bcbaf08545f067ad&tags=${tag}&tag_mode=any&per_page=100&format=json&safe_search=1&nojsoncallback=1`;
const baseUrl = 'https://api.flickr.com/';
axios({
url: getImagesUrl,
baseURL: baseUrl,
method: 'GET'
})
.then(res => res.data)
.then(res => {
if (
res &&
res.photos &&
res.photos.photo &&
res.photos.photo.length > 0
) {
this.setState({images: res.photos.photo});
}
});
}
componentDidMount() {
this.getImages(this.props.tag);
this.setState({
galleryWidth: document.body.clientWidth
});
}
componentWillReceiveProps(props) {
this.getImages(props.tag);
}
render() {
return (
<div className="gallery-root">
{this.state.images.map((dto , i) => {
return <Image key={'image-' + dto.id+ i.toString()} dto={dto} galleryWidth={this.state.galleryWidth}/>;
})}
</div>
);
}
}
</code></pre>
| 0 | 1,237 |
error "remote error: tls: bad certificate", ServerName ""
|
<p>I am start etcd(3.3.13) member using this command:</p>
<pre><code>/usr/local/bin/etcd \
--name infra2 \
--cert-file=/etc/kubernetes/ssl/kubernetes.pem \
--key-file=/etc/kubernetes/ssl/kubernetes-key.pem \
--peer-cert-file=/etc/kubernetes/ssl/kubernetes.pem \
--peer-key-file=/etc/kubernetes/ssl/kubernetes-key.pem \
--trusted-ca-file=/etc/kubernetes/ssl/ca.pem \
--peer-trusted-ca-file=/etc/kubernetes/ssl/ca.pem \
--initial-advertise-peer-urls https://172.19.104.230:2380 \
--listen-peer-urls https://172.19.104.230:2380 \
--listen-client-urls http://127.0.0.1:2379 \
--advertise-client-urls https://172.19.104.230:2379 \
--initial-cluster-token etcd-cluster \
--initial-cluster infra1=https://172.19.104.231:2380,infra2=https://172.19.104.230:2380,infra3=https://172.19.150.82:2380 \
--initial-cluster-state new \
--data-dir=/var/lib/etcd
</code></pre>
<p>but the log shows this error:</p>
<pre><code>2019-08-24 13:12:07.981345 I | embed: rejected connection from "172.19.104.231:60474" (error "remote error: tls: bad certificate", ServerName "")
2019-08-24 13:12:08.003918 I | embed: rejected connection from "172.19.104.231:60478" (error "remote error: tls: bad certificate", ServerName "")
2019-08-24 13:12:08.004242 I | embed: rejected connection from "172.19.104.231:60480" (error "remote error: tls: bad certificate", ServerName "")
2019-08-24 13:12:08.045940 E | rafthttp: request cluster ID mismatch (got 52162d7b86a0617a want b125c249de626e35)
2019-08-24 13:12:08.046455 E | rafthttp: request cluster ID mismatch (got 52162d7b86a0617a want b125c249de626e35)
2019-08-24 13:12:08.081290 I | embed: rejected connection from "172.19.104.231:60484" (error "remote error: tls: bad certificate", ServerName "")
2019-08-24 13:12:08.101692 I | embed: rejected connection from "172.19.104.231:60489" (error "remote error: tls: bad certificate", ServerName "")
2019-08-24 13:12:08.102002 I | embed: rejected connection from "172.19.104.231:60488" (error "remote error: tls: bad certificate", ServerName "")
2019-08-24 13:12:08.144928 E | rafthttp: request cluster ID mismatch (got 52162d7b86a0617a want b125c249de626e35)
2019-08-24 13:12:08.145151 E | rafthttp: request cluster ID mismatch (got 52162d7b86a0617a want b125c249de626e35)
2019-08-24 13:12:08.181299 I | embed: rejected connection from "172.19.104.231:60494" (error "remote error: tls: bad certificate", ServerName "")
2019-08-24 13:12:08.201722 I | embed: rejected connection from "172.19.104.231:60500" (error "remote error: tls: bad certificate", ServerName "")
2019-08-24 13:12:08.202096 I | embed: rejected connection from "172.19.104.231:60498" (error "remote error: tls: bad certificate", ServerName "")
</code></pre>
<p>I search from internet and find the reason is: should give all etcd node ip in hosts config when generate CA cert,but I config all my etcd node ip in csr.json,this is my csr.json config:</p>
<pre><code>{
"CN": "kubernetes",
"hosts": [
"127.0.0.1",
"172.19.104.230",
"172.19.150.82",
"172.19.104.231"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}
</code></pre>
<p>what should I do to fix the error?</p>
| 0 | 1,422 |
Zeppelin throws java.lang.OutOfMemoryError: Java heap space
|
<p>I am trying to use Zeppelin with the following code:</p>
<pre class="lang-scala prettyprint-override"><code>val dataText = sc.parallelize(IOUtils.toString(new URL("http://XXX.XX.XXX.121:8090/my_data.txt"),Charset.forName("utf8")).split("\n"))
case class Data(id: string, time: long, value1: Double, value2: int, mode: int)
val dat = dataText .map(s => s.split("\t")).filter(s => s(0) != "Header:").map(
s => Data(s(0),
s(1).toLong,
s(2).toDouble,
s(3).toInt,
s(4).toInt
)
).toDF()
dat.registerTempTable("mydatatable")
</code></pre>
<p>this keeps throwing me following error :</p>
<pre><code>java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2367)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:535)
at java.lang.StringBuilder.append(StringBuilder.java:204)
at org.apache.commons.io.output.StringBuilderWriter.write(StringBuilderWriter.java:138)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2002)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1980)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1957)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1907)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:778)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:896)
at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:38)
at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:43)
at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:45)
at $iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:47)
at $iwC$$iwC$$iwC$$iwC.<init>(<console>:49)
at $iwC$$iwC$$iwC.<init>(<console>:51)
at $iwC$$iwC.<init>(<console>:53)
at $iwC.<init>(<console>:55)
at <init>(<console>:57)
at .<init>(<console>:61)
at .<clinit>(<console>)
at .<init>(<console>:7)
at .<clinit>(<console>)
at $print(<console>)
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 org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)
at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1338)
</code></pre>
<p>I have already set the following in the <code>zeppelin-env.sh</code></p>
<p><code>export ZEPPELIN_JAVA_OPTS="-Dhdp.version=2.3.0.0-2557 -Dspark.executor.memory=4g"</code></p>
<p>any idea what I may be missing. File I am parsing <code>my_data.txt</code> is about 200MB</p>
<p>BTW I am using the Hortonworks Sandbox if that matters</p>
<p><strong>EDIT 1</strong>
Here is my <code>zeppelin-env.sh</code></p>
<pre><code>export HADOOP_CONF_DIR=/etc/hadoop/conf
export ZEPPELIN_PORT=9995
export ZEPPELIN_JAVA_OPTS="-Dhdp.version=2.3.0.0-2557 -Dspark.executor.memory=4g"
export SPARK_SUBMIT_OPTIONS="--driver-java-options -Xmx4g"
export ZEPPELIN_INT_MEM="-Xmx4g"
export SPARK_HOME=/usr/hdp/2.3.0.0-2557/spark
</code></pre>
<p>Regards
Kiran </p>
| 0 | 1,605 |
Expansion File (Android): "Download failed because the resources could not be found"
|
<p>I am facing a problem with an expansion file process, I do not know what the problem is. I hope if someone could help.</p>
<p>I have followed the steps by Google; yet I cannot assure I have done it correctly 100%.</p>
<pre><code>/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
import com.android.vending.expansion.zipfile.ZipResourceFile;
import com.android.vending.expansion.zipfile.ZipResourceFile.ZipEntryRO;
import com.google.android.vending.expansion.downloader.Constants;
import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
import com.google.android.vending.expansion.downloader.DownloaderServiceMarshaller;
import com.google.android.vending.expansion.downloader.Helpers;
import com.google.android.vending.expansion.downloader.IDownloaderClient;
import com.google.android.vending.expansion.downloader.IDownloaderService;
import com.google.android.vending.expansion.downloader.IStub;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Messenger;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.zip.CRC32;
/**
* This is sample code for a project built against the downloader library. It
* implements the IDownloaderClient that the client marshaler will talk to as
* messages are delivered from the DownloaderService.
*/
public class ExpansionFileDownloaderActivity extends Activity implements IDownloaderClient {
private static final String LOG_TAG = "LVLDownloader";
private ProgressBar mPB;
private TextView mStatusText;
private TextView mProgressFraction;
private TextView mProgressPercent;
private TextView mAverageSpeed;
private TextView mTimeRemaining;
private View mDashboard;
private View mCellMessage;
private Button mPauseButton;
private Button mWiFiSettingsButton;
private boolean mStatePaused;
private int mState;
private IDownloaderService mRemoteService;
private IStub mDownloaderClientStub;
private void setState(int newState) {
if (mState != newState) {
mState = newState;
mStatusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState));
}
}
private void setButtonPausedState(boolean paused) {
mStatePaused = paused;
int stringResourceID = paused ? R.string.text_button_resume :
R.string.text_button_pause;
mPauseButton.setText(stringResourceID);
}
/**
* This is a little helper class that demonstrates simple testing of an
* Expansion APK file delivered by Market. You may not wish to hard-code
* things such as file lengths into your executable... and you may wish to
* turn this code off during application development.
*/
private static class XAPKFile {
public final boolean mIsMain;
public final int mFileVersion;
public final long mFileSize;
XAPKFile(boolean isMain, int fileVersion, long fileSize) {
mIsMain = isMain;
mFileVersion = fileVersion;
mFileSize = fileSize;
}
}
/**
* Here is where you place the data that the validator will use to determine
* if the file was delivered correctly. This is encoded in the source code
* so the application can easily determine whether the file has been
* properly delivered without having to talk to the server. If the
* application is using LVL for licensing, it may make sense to eliminate
* these checks and to just rely on the server.
*/
private static final XAPKFile[] xAPKS = {
new XAPKFile(
true, // true signifies a main file
1, // the version of the APK that the file was uploaded
// against
102459993L // the length of the file in bytes
)
};
/**
* Go through each of the APK Expansion files defined in the structure above
* and determine if the files are present and match the required size. Free
* applications should definitely consider doing this, as this allows the
* application to be launched for the first time without having a network
* connection present. Paid applications that use LVL should probably do at
* least one LVL check that requires the network to be present, so this is
* not as necessary.
*
* @return true if they are present.
*/
boolean expansionFilesDelivered() {
for (XAPKFile xf : xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsMain, xf.mFileVersion);
if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false))
return false;
}
return true;
}
public static boolean expansionFilesDelivered(Context ctx) {
for (XAPKFile xf : xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(ctx, xf.mIsMain, xf.mFileVersion);
if (!Helpers.doesFileExist(ctx, fileName, xf.mFileSize, false))
return false;
}
return true;
}
/**
* Calculating a moving average for the validation speed so we don't get
* jumpy calculations for time etc.
*/
static private final float SMOOTHING_FACTOR = 0.005f;
/**
* Used by the async task
*/
private boolean mCancelValidation;
/**
* Go through each of the Expansion APK files and open each as a zip file.
* Calculate the CRC for each file and return false if any fail to match.
*
* @return true if XAPKZipFile is successful
*/
void validateXAPKZipFiles() {
AsyncTask<Object, DownloadProgressInfo, Boolean> validationTask = new AsyncTask<Object, DownloadProgressInfo, Boolean>() {
@Override
protected void onPreExecute() {
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_verifying_download);
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCancelValidation = true;
}
});
mPauseButton.setText(R.string.text_button_cancel_verify);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Object... params) {
for (XAPKFile xf : xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(
ExpansionFileDownloaderActivity.this,
xf.mIsMain, xf.mFileVersion);
if (!Helpers.doesFileExist(ExpansionFileDownloaderActivity.this, fileName,
xf.mFileSize, false))
return false;
fileName = Helpers
.generateSaveFileName(ExpansionFileDownloaderActivity.this, fileName);
ZipResourceFile zrf;
byte[] buf = new byte[1024 * 256];
try {
zrf = new ZipResourceFile(fileName);
ZipEntryRO[] entries = zrf.getAllEntries();
/**
* First calculate the total compressed length
*/
long totalCompressedLength = 0;
for (ZipEntryRO entry : entries) {
totalCompressedLength += entry.mCompressedLength;
}
float averageVerifySpeed = 0;
long totalBytesRemaining = totalCompressedLength;
long timeRemaining;
/**
* Then calculate a CRC for every file in the Zip file,
* comparing it to what is stored in the Zip directory.
* Note that for compressed Zip files we must extract
* the contents to do this comparison.
*/
for (ZipEntryRO entry : entries) {
if (-1 != entry.mCRC32) {
long length = entry.mUncompressedLength;
CRC32 crc = new CRC32();
DataInputStream dis = null;
try {
dis = new DataInputStream(
zrf.getInputStream(entry.mFileName));
long startTime = SystemClock.uptimeMillis();
while (length > 0) {
int seek = (int) (length > buf.length ? buf.length
: length);
dis.readFully(buf, 0, seek);
crc.update(buf, 0, seek);
length -= seek;
long currentTime = SystemClock.uptimeMillis();
long timePassed = currentTime - startTime;
if (timePassed > 0) {
float currentSpeedSample = (float) seek
/ (float) timePassed;
if (0 != averageVerifySpeed) {
averageVerifySpeed = SMOOTHING_FACTOR
* currentSpeedSample
+ (1 - SMOOTHING_FACTOR)
* averageVerifySpeed;
} else {
averageVerifySpeed = currentSpeedSample;
}
totalBytesRemaining -= seek;
timeRemaining = (long) (totalBytesRemaining / averageVerifySpeed);
this.publishProgress(
new DownloadProgressInfo(
totalCompressedLength,
totalCompressedLength
- totalBytesRemaining,
timeRemaining,
averageVerifySpeed
)
);
}
startTime = currentTime;
if (mCancelValidation)
return true;
}
if (crc.getValue() != entry.mCRC32) {
Log.e(Constants.TAG,
"CRC does not match for entry: "
+ entry.mFileName
);
Log.e(Constants.TAG,
"In file: " + entry.getZipFileName());
return false;
}
} finally {
if (null != dis) {
dis.close();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
@Override
protected void onProgressUpdate(DownloadProgressInfo... values) {
onDownloadProgress(values[0]);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_validation_complete);
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mPauseButton.setText(android.R.string.ok);
} else {
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_validation_failed);
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mPauseButton.setText(android.R.string.cancel);
}
super.onPostExecute(result);
}
};
validationTask.execute(new Object());
}
/**
* If the download isn't present, we initialize the download UI. This ties
* all of the controls into the remote service calls.
*/
private void initializeDownloadUI() {
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub
(this, SampleDownloaderService.class);
setContentView(R.layout.downloader_ui);
mPB = (ProgressBar) findViewById(R.id.progressBar);
mStatusText = (TextView) findViewById(R.id.statusText);
mProgressFraction = (TextView) findViewById(R.id.progressAsFraction);
mProgressPercent = (TextView) findViewById(R.id.progressAsPercentage);
mAverageSpeed = (TextView) findViewById(R.id.progressAverageSpeed);
mTimeRemaining = (TextView) findViewById(R.id.progressTimeRemaining);
mDashboard = findViewById(R.id.downloaderDashboard);
mCellMessage = findViewById(R.id.approveCellular);
mPauseButton = (Button) findViewById(R.id.pauseButton);
mWiFiSettingsButton = (Button) findViewById(R.id.wifiSettingsButton);
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mStatePaused) {
mRemoteService.requestContinueDownload();
} else {
mRemoteService.requestPauseDownload();
}
setButtonPausedState(!mStatePaused);
}
});
mWiFiSettingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
Button resumeOnCell = (Button) findViewById(R.id.resumeOverCellular);
resumeOnCell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR);
mRemoteService.requestContinueDownload();
mCellMessage.setVisibility(View.GONE);
}
});
}
/**
* Called when the activity is first create; we wouldn't create a layout in
* the case where we have the file and are moving to another activity
* without downloading.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Both downloading and validation make use of the "download" UI
*/
initializeDownloadUI();
/**
* Before we do anything, are the files we expect already here and
* delivered (presumably by Market) For free titles, this is probably
* worth doing. (so no Market request is necessary)
*/
if (!expansionFilesDelivered()) {
try {
Intent launchIntent = ExpansionFileDownloaderActivity.this
.getIntent();
Intent intentToLaunchThisActivityFromNotification = new Intent(
ExpansionFileDownloaderActivity
.this, ((Object) this).getClass() //..... this.getClass()
);
intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());
if (launchIntent.getCategories() != null) {
for (String category : launchIntent.getCategories()) {
intentToLaunchThisActivityFromNotification.addCategory(category);
}
}
// Build PendingIntent used to open this activity from
// Notification
PendingIntent pendingIntent = PendingIntent.getActivity(
ExpansionFileDownloaderActivity.this,
0, intentToLaunchThisActivityFromNotification,
PendingIntent.FLAG_UPDATE_CURRENT);
// Request to start the download
int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
pendingIntent, SampleDownloaderService.class);
if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
// The DownloaderService has started downloading the files,
// show progress
initializeDownloadUI();
return;
} // otherwise, download not needed so we fall through to
// starting the movie
} catch (NameNotFoundException e) {
Log.e(LOG_TAG, "Cannot find own package! MAYDAY!");
e.printStackTrace();
}
} else {
validateXAPKZipFiles();
}
}
/**
* Connect the stub to our service on start.
*/
@Override
protected void onStart() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(this);
}
super.onStart();
}
/**
* Disconnect the stub from our service on stop
*/
@Override
protected void onStop() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.disconnect(this);
}
super.onStop();
}
/**
* Critical implementation detail. In onServiceConnected we create the
* remote service and marshaler. This is how we pass the client information
* back to the service so the client can be properly notified of changes. We
* must do this every time we reconnect to the service.
*/
@Override
public void onServiceConnected(Messenger m) {
mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
}
/**
* The download state should trigger changes in the UI --- it may be useful
* to show the state as being indeterminate at times. This sample can be
* considered a guideline.
*/
@Override
public void onDownloadStateChanged(int newState) {
setState(newState);
boolean showDashboard = true;
boolean showCellMessage = false;
boolean paused;
boolean indeterminate;
switch (newState) {
case IDownloaderClient.STATE_IDLE:
// STATE_IDLE means the service is listening, so it's
// safe to start making calls via mRemoteService.
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_CONNECTING:
case IDownloaderClient.STATE_FETCHING_URL:
showDashboard = true;
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_DOWNLOADING:
paused = false;
showDashboard = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
paused = true;
showDashboard = false;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
showDashboard = false;
paused = true;
indeterminate = false;
showCellMessage = true;
break;
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_ROAMING:
case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_COMPLETED:
showDashboard = false;
paused = false;
indeterminate = false;
validateXAPKZipFiles();
return;
default:
paused = true;
indeterminate = true;
showDashboard = true;
}
int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE;
if (mDashboard.getVisibility() != newDashboardVisibility) {
mDashboard.setVisibility(newDashboardVisibility);
}
int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE;
if (mCellMessage.getVisibility() != cellMessageVisibility) {
mCellMessage.setVisibility(cellMessageVisibility);
}
mPB.setIndeterminate(indeterminate);
setButtonPausedState(paused);
}
/**
* Sets the state of the various controls based on the progressinfo object
* sent from the downloader service.
*/
@Override
public void onDownloadProgress(DownloadProgressInfo progress) {
mAverageSpeed.setText(getString(R.string.kilobytes_per_second,
Helpers.getSpeedString(progress.mCurrentSpeed)));
mTimeRemaining.setText(getString(R.string.time_remaining,
Helpers.getTimeRemaining(progress.mTimeRemaining)));
progress.mOverallTotal = progress.mOverallTotal;
mPB.setMax((int) (progress.mOverallTotal >> 8));
mPB.setProgress((int) (progress.mOverallProgress >> 8));
mProgressPercent.setText(Long.toString(progress.mOverallProgress
* 100 /
progress.mOverallTotal) + "%");
mProgressFraction.setText(Helpers.getDownloadProgressString
(progress.mOverallProgress,
progress.mOverallTotal));
}
@Override
protected void onDestroy() {
this.mCancelValidation = true;
super.onDestroy();
}
}
</code></pre>
<p>this is the SampleDownloaderService class, </p>
<pre><code>import com.google.android.vending.expansion.downloader.impl.DownloaderService;
/**
* Created by Abdulkarim Kanaan on 22-Mar-14.
*/
public class SampleDownloaderService extends DownloaderService {
// You must use the public key belonging to your publisher account
public static final String BASE64_PUBLIC_KEY = "<Place Key provided by Google Play Publisher>";
// You should also modify this salt
public static final byte[] SALT = new byte[] { 1, 42, -12, -1, 54, 98,
-100, -12, 43, 2, -8, -4, 9, 5, -106, -107, -33, 45, -1, 84
};
@Override
public String getPublicKey() {
return BASE64_PUBLIC_KEY;
}
@Override
public byte[] getSALT() {
return SALT;
}
@Override
public String getAlarmReceiverClassName() {
return SampleAlarmReceiver.class.getName();
}
}
</code></pre>
<p>Finally, this is the Main Activity creation method, where the check is carried out to see whether the expansion file exists or not.</p>
<pre><code>public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String.valueOf(ExpansionFileDownloaderActivity.expansionFilesDelivered(this)));
if (!ExpansionFileDownloaderActivity.expansionFilesDelivered(this)){
startActivity(new Intent(this, ExpansionFileDownloaderActivity.class));
}
//startApp(); // Expansion files are available, start the app
}
</code></pre>
<p>the problem is that after uploading the expansion file to Google Play, when the program starts, it shows that downloading process is going to be carried out. After a short period, it stops saying that "Download failed because the resources could not be found". When I place the file (obb file) in the SD Card, the application works as expected. However, I am trying now to download the file from Google Play.</p>
<p>What is the problem?</p>
<p>Thank you in advance,</p>
| 0 | 13,026 |
TableLayoutPanel rows & columns at runtime
|
<p>im trying to build a usercontrol which contains a tablelayoutpanel. in this panel i need to dynamically add 3 columns with each having different a width and 5 rows which all shell have the same height (20% of the tablelayoutpanel's height).</p>
<p>column1 should have an absolute width of 20,
column2 depending a width on its content (a textbox with .dock = fill)
column3 a width of 30.</p>
<p>my code:</p>
<pre><code>Private Sub BuildGUI()
If Rows > 0 Then
tlp.Controls.Clear()
tlp.ColumnStyles.Clear()
tlp.RowStyles.Clear()
If Style = Styles.Adding Then
tlp.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 30))
tlp.ColumnStyles.Add(New ColumnStyle(SizeType.Autosize))
tlp.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 20))
tlp.ColumnCount = 3
tlp.RowStyles.Add(New RowStyle(SizeType.AutoSize, 20%))
tlp.RowStyles.Add(New RowStyle(SizeType.AutoSize, 20%))
tlp.RowStyles.Add(New RowStyle(SizeType.AutoSize, 20%))
tlp.RowStyles.Add(New RowStyle(SizeType.AutoSize, 20%))
tlp.RowStyles.Add(New RowStyle(SizeType.AutoSize, 20%))
tlp.RowCount = Rows
For i = 0 To Rows - 1
Dim L As New Label
Dim T As New TextBox
Dim C As New CheckBox
With L
.BackColor = Color.Aqua
'.Dock = DockStyle.Fill
.Visible = True
.BorderStyle = Windows.Forms.BorderStyle.FixedSingle
.Font = New Font("Microsoft Sans Serif", 11, FontStyle.Bold)
End With
tlp.Controls.Add(L, 0, i)
With T
.BackColor = Color.Beige
.Visible = True
.Multiline = True
.ScrollBars = ScrollBars.Vertical
.Dock = DockStyle.Fill
End With
tlp.Controls.Add(T, 1, i)
With C
.Visible = True
.BackColor = Color.Brown
End With
tlp.Controls.Add(C, 2, i)
Next
Else
End If
End If
</code></pre>
<p>End Sub</p>
<p>Styles & Rows are properties of the Usercontrol.</p>
<p>but the result is never as i want it to be. any ideas?</p>
| 0 | 1,246 |
PHP 'Years' array
|
<p>I am trying to create an array for years which i will use in the DOB year piece of a form I am building. Currently, I know there are two ways to handle the issue but I don't really care for either:</p>
<h2>1) Range:</h2>
<p>I know I can create a year array using the following</p>
<pre><code><?php
$year = range(1910,date("Y"));
$_SESSION['years_arr'] = $year;
?>
</code></pre>
<p>the problem with Point 1 is two fold: a) my function call shows the first year as 'selected' instead of "Year" as I have as option="0", and b) I want the years reversed so 2010 is the first in the least and shown decreasing.</p>
<p>My function call is:</p>
<p><strong>PHP</strong></p>
<pre><code><?php
function showOptionsDrop($array, $active, $echo=true){
$string = '';
foreach($array as $k => $v){
$s = ($active == $k)? ' selected="selected"' : '';
$string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";
}
if($echo) echo $string;
else return $string;
}
?>
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><table>
<tr>
<td>State:</td>
<td><select name="F1State"><option value="0">Choose a year</option><?php showOptionsDrop($_SESSION['years_arr'], null, true); ?></select>
</td>
</tr>
</table>
</code></pre>
<hr>
<h1>2) Long Array</h1>
<p>I know i can physically create an array with years listed out but this takes up a lot of space and time if I ever want to go back and modify.</p>
<p>ex: <strong>PHP</strong></p>
<pre><code>$years = array('1900'=>"1900", '1901'=>"1901", '1902'=>"1902", '1903'=>"1903", '1904'=>"1904", '1905'=>"1905", '1906'=>"1906", '1907'=>"1907", '1908'=>"1908", '1909'=>"1909", '1910'=>"1910", '1911'=>"1911", '1912'=>"1912", '1913'=>"1913", '1914'=>"1914", '1915'=>"1915", '1916'=>"1916", '1917'=>"1917", '1918'=>"1918", '1919'=>"1919", '1920'=>"1920", '1921'=>"1921", '1922'=>"1922", '1923'=>"1923", '1924'=>"1924", '1925'=>"1925", '1926'=>"1926", '1927'=>"1927", '1928'=>"1928", '1929'=>"1929", '1930'=>"1930", '1931'=>"1931", '1932'=>"1932", '1933'=>"1933", '1934'=>"1934", '1935'=>"1935", '1936'=>"1936", '1937'=>"1937", '1938'=>"1938", '1939'=>"1939", '1940'=>"1940", '1941'=>"1941", '1942'=>"1942", '1943'=>"1943", '1944'=>"1944", '1945'=>"1945", '1946'=>"1946", '1947'=>"1947", '1948'=>"1948", '1949'=>"1949", '1950'=>"1950", '1951'=>"1951", '1952'=>"1952", '1953'=>"1953", '1954'=>"1954", '1955'=>"1955", '1956'=>"1956", '1957'=>"1957", '1958'=>"1958", '1959'=>"1959", '1960'=>"1960", '1961'=>"1961", '1962'=>"1962", '1963'=>"1963", '1964'=>"1964", '1965'=>"1965", '1966'=>"1966", '1967'=>"1967", '1968'=>"1968", '1969'=>"1969", '1970'=>"1970", '1971'=>"1971", '1972'=>"1972", '1973'=>"1973", '1974'=>"1974", '1975'=>"1975", '1976'=>"1976", '1977'=>"1977", '1978'=>"1978", '1979'=>"1979", '1980'=>"1980", '1981'=>"1981", '1982'=>"1982", '1983'=>"1983", '1984'=>"1984", '1985'=>"1985", '1986'=>"1986", '1987'=>"1987", '1988'=>"1988", '1989'=>"1989", '1990'=>"1990", '1991'=>"1991", '1992'=>"1992", '1993'=>"1993", '1994'=>"1994", '1995'=>"1995", '1996'=>"1996", '1997'=>"1997", '1998'=>"1998", '1999'=>"1999", '2000'=>"2000", '2001'=>"2001", '2002'=>"2002", '2003'=>"2003", '2004'=>"2004", '2005'=>"2005", '2006'=>"2006", '2007'=>"2007", '2008'=>"2008", '2009'=>"2009", '2010'=>"2010");
$_SESSION['years_arr'] = $years_arr;
</code></pre>
<p>Does anybody have a recommended idea how to work - or just how to simply modify my existing code?</p>
<p>Thank you!</p>
| 0 | 1,932 |
What happens when there's insufficient memory to throw an OutOfMemoryError?
|
<p>I am aware that every object requires heap memory and every primitive/reference on the stack requires stack memory.</p>
<p>When I attempt to create an object on the heap and there's insufficient memory to do so, the JVM creates an <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html">java.lang.OutOfMemoryError</a> on the heap and throws it to me.</p>
<p>So implicitly, this means that there is some memory reserved by the JVM on startup.</p>
<p>What happens when this reserved memory is used up (it would definitely be used up, read discussion below) and the JVM does not have enough memory on the heap to create an instance of <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html">java.lang.OutOfMemoryError</a>?</p>
<p>Does it just hang? Or would he throw me a <code>null</code> since there's no memory to <code>new</code> an instance of OOM ?</p>
<pre><code>try {
Object o = new Object();
// and operations which require memory (well.. that's like everything)
} catch (java.lang.OutOfMemoryError e) {
// JVM had insufficient memory to create an instance of java.lang.OutOfMemoryError to throw to us
// what next? hangs here, stuck forever?
// or would the machine decide to throw us a "null" ? (since it doesn't have memory to throw us anything more useful than a null)
e.printStackTrace(); // e.printStackTrace() requires memory too.. =X
}
</code></pre>
<p>==</p>
<p><strong>Why couldn't the JVM reserve sufficient memory?</strong></p>
<p>No matter how much memory is reserved, it is still possible for that memory to be used up if the JVM does not have a way to "reclaim" that memory:</p>
<pre><code>try {
Object o = new Object();
} catch (java.lang.OutOfMemoryError e) {
// JVM had 100 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e2) {
// JVM had 99 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e3) {
// JVM had 98 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e4) {
// JVM had 97 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e5) {
// JVM had 96 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e6) {
// JVM had 95 units of "spare memory". 1 is used to create this OOM.
e.printStackTrace();
//........the JVM can't have infinite reserved memory, he's going to run out in the end
}
}
}
}
}
}
</code></pre>
<p>Or more concisely:</p>
<pre><code>private void OnOOM(java.lang.OutOfMemoryError e) {
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e2) {
OnOOM(e2);
}
}
</code></pre>
| 0 | 1,342 |
How to show JRBeanCollectionDataSource data with help of Table component?
|
<p>I need to show JRBeanCollectionDataSource data in Table component (JasperReports). </p>
<p>Here is my template, ShowPerson.jrxml file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ShowPerson" pageWidth="612" pageHeight="792" whenNoDataType="NoDataSection" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="304c4c4e-c99a-4399-8081-748d3b7c0b8c">
<style name="table">
<box>
<pen lineWidth="1.0" lineColor="#000000"/>
</box>
</style>
<style name="table_TH" mode="Opaque" backcolor="#F0F8FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="table_CH" mode="Opaque" backcolor="#BFE1FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="table_TD" mode="Opaque" backcolor="#FFFFFF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<subDataset name="Table Dataset 1" whenResourceMissingType="Empty" uuid="63b01547-bce2-47c9-ba15-666f94d11387">
<queryString language="SQL">
<![CDATA[]]>
</queryString>
<field name="name" class="java.lang.String"/>
<field name="age" class="java.lang.Integer"/>
</subDataset>
<parameter name="INFO" class="java.lang.String"/>
<title>
<band height="40" splitType="Stretch">
<staticText>
<reportElement uuid="e96450a8-8358-4cae-a094-3add06d57de2" x="0" y="20" width="56" height="20"/>
<textElement/>
<text><![CDATA[Info]]></text>
</staticText>
<textField>
<reportElement uuid="e21e9932-ebfe-4bb5-904d-ea99e141866b" x="56" y="20" width="100" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$P{INFO}]]></textFieldExpression>
</textField>
</band>
</title>
<detail>
<band height="40" splitType="Stretch">
<componentElement>
<reportElement uuid="dea5d821-81b6-434b-ae27-4f3a0268e805" key="table 1" x="0" y="0" width="572" height="40"/>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="Table Dataset 1" uuid="39f8f0bf-8a2b-44f4-9a4c-0c873da79fba">
<datasetParameter name="REPORT_DATA_SOURCE">
<datasetParameterExpression><![CDATA[]]></datasetParameterExpression>
</datasetParameter>
<dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression>
</datasetRun>
<jr:column width="169" uuid="aae649c4-6a69-485f-8a0d-87022df793ee">
<jr:tableHeader height="20" rowSpan="1">
<staticText>
<reportElement uuid="795dac43-0ff0-482c-89a0-7dac3b27d513" x="0" y="0" width="169" height="20"/>
<textElement/>
<text><![CDATA[Name]]></text>
</staticText>
</jr:tableHeader>
<jr:detailCell height="20" rowSpan="1">
<textField>
<reportElement uuid="4f1ab13a-d776-4cd5-a2a7-a5cf23360816" x="0" y="0" width="169" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="173" uuid="a6997eea-131e-4555-80e6-a20d4decb18f">
<jr:tableHeader height="20" rowSpan="1">
<staticText>
<reportElement uuid="5f6e2413-8025-47ca-9638-9609ea13f93f" x="0" y="0" width="173" height="20"/>
<textElement/>
<text><![CDATA[Age]]></text>
</staticText>
</jr:tableHeader>
<jr:detailCell height="20" rowSpan="1">
<textField>
<reportElement uuid="195d51a0-9e45-4201-ad67-d3026ce2e72c" x="0" y="0" width="173" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{age}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
</band>
</detail>
</jasperReport>
</code></pre>
<p>My POJO:</p>
<pre><code>public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
</code></pre>
<p>Main class for building report:</p>
<pre><code>public class OpenReport {
public static void main(String[] args) throws JRException {
Map<String, Object> peopleMap = new HashMap<>();
peopleMap.put("Sisco", 17);
peopleMap.put("Eve", 19);
peopleMap.put("John", 20);
peopleMap.put("George", 21);
peopleMap.put("Steve", 18);
ArrayList<Person> dataList = new ArrayList<Person>();
for(Map.Entry<String, Object> personMap : peopleMap.entrySet()) {
Person person = new Person();
person.setName(personMap.getKey());
person.setAge(Integer.valueOf(personMap.getValue().toString()));
dataList.add(person);
}
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
Map parameters = new HashMap();
parameters.put("INFO", "Hello");
JasperReport report = (JasperReport) JRLoader.loadObject("src/test/ireport/ShowPerson.jasper");
JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, beanColDataSource);
JFrame frame = new JFrame("Report");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JRViewer(jasperPrint));
frame.pack();
frame.setVisible(true);
}
}
</code></pre>
| 0 | 4,246 |
Django ERROR: Invalid HTTP_HOST header: u'/run/myprojectname/gunicorn.sock:'
|
<p><em>I know that there are a lot of questions like this on SO, but none of them appear to answer my particular issue.</em></p>
<p>I understand that Django's <code>ALLOWED_HOSTS</code> value is blocking any requests to port <code>80</code> at my IP that do not come with the appropriate <code>Host:</code> value, and that when a request comes in that doesn't have the right value, Django is dropping me an email. I also know about the <a href="https://stackoverflow.com/a/17477436/231670">slick Nginx hack</a> to make this problem go away, but I'm trying to understand the nature of one such request and determine whether this is a security issue I need to worry about.</p>
<p>Requests like these make sense:</p>
<pre><code>[Django] ERROR: Invalid HTTP_HOST header: '203.0.113.1'. You may need to add u'203.0.113.1' to ALLOWED_HOSTS.
</code></pre>
<p>But this one kind of freaks me out:</p>
<pre><code>[Django] ERROR: Invalid HTTP_HOST header: u'/run/my_project_name/gunicorn.sock:'.
</code></pre>
<p>Doesn't this mean that the requestor sent <code>Host: /run/my_project_name/gunicorn.sock</code> to the server? If so, how do they have the path name for my <code>.sock</code> file? Is my server somehow leaking this information?</p>
<p>Additionally, as I'm running Django 1.6.5, I don't understand why I'm receiving these emails at all, as <a href="https://code.djangoproject.com/ticket/19866" rel="noreferrer">this ticket</a> has been marked fixed for some time now.</p>
<p>Can someone shed some light on what I'm missing?</p>
<p>This is my <code>settings.LOGGING</code> variable:</p>
<pre><code>{
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}
},
'formatters': {
'simple': {'format': '%(levelname)s %(message)s'},
'verbose': {'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'verbose',
'level': 'DEBUG'
},
'mail_admins': {
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['require_debug_false'],
'level': 'ERROR'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True
},
'my_project_name': {
'handlers': ['console'],
'level': 'DEBUG'
}
},
'version': 1
}
</code></pre>
<p>And here's my nginx config:</p>
<pre><code>worker_processes 1;
pid /run/nginx.pid;
error_log /var/log/myprojectname/nginx.error.log debug;
events {
}
http {
include mime.types;
default_type application/octet-stream;
access_log /var/log/myprojectname/nginx.access.log combined;
sendfile on;
gzip on;
gzip_http_version 1.0;
gzip_proxied any;
gzip_min_length 500;
gzip_disable "MSIE [1-6]\.";
gzip_types text/plain text/html text/xml text/css
text/comma-separated-values
text/javascript application/x-javascript
application/atom+xml;
upstream app_server {
server unix:/run/myprojectname/gunicorn.sock fail_timeout=0;
}
server {
listen 80 default;
listen [::]:80 default;
client_max_body_size 4G;
server_name myprojectname.mydomain.tld;
keepalive_timeout 5;
root /var/www/myprojectname;
location / {
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
proxy_pass http://app_server;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /tmp;
}
}
}
</code></pre>
<p>Lastly, I found this in my nginx access log. It corresponds to the emails coming through that complain about /run/myprojectname/gunicorn.sock being an invalid HTTP_HOST header.*</p>
<p>This was all on one line of course:</p>
<pre><code>2014/09/05 20:38:56 [info] 12501#0: *513 epoll_wait() reported that client
prematurely closed connection, so upstream connection is closed too while sending
request to upstream, client: 54.84.192.68, server: myproject.mydomain.tld, request:
"HEAD / HTTP/1.0", upstream: "http://unix:/run/myprojectname/gunicorn.sock:/"
</code></pre>
<p>Obviously I still don't know what this means though :-(</p>
<ul>
<li><strong><em>Update #1</strong>: Added my <code>settings.LOGGING</code></em></li>
<li><strong><em>Update #2</strong>: Added my nginx config</em></li>
<li><strong><em>Update #3</strong>: Added an interesting line from my nginx log</em></li>
<li><strong><em>Update #4</strong>: Updated my nginx config</em></li>
</ul>
| 0 | 1,932 |
Change Images on Custom CheckBox in WPF
|
<p>All I have created the following custom <code>CheckBox</code> which uses images instead of a <code>CheckBox</code>. This works well however, I want to be able to change the images as required. Ideally I would like to use application resources <code>Properties.Resources.SomeImage16</code> (a .png file). The XAML is </p>
<pre><code><Style x:Key="styleCustomCheckBox"
TargetType="{x:Type CheckBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<StackPanel Orientation="Horizontal">
<Image x:Name="imageCheckBox"
Width="16"
Height="16"
Source="F:\Camus\ResourceStudio\Graphics\Images\UnPinned16.png"/>
<ContentPresenter VerticalAlignment="Center"/>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="False">
<Setter TargetName="imageCheckBox"
Property="Source"
Value="F:\Camus\ResourceStudio\Graphics\Images\Pinned16.png"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="imageCheckBox"
Property="Source"
Value="F:\Camus\ResourceStudio\Graphics\Images\UnPinned16.png"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>With implementation </p>
<pre><code><ListBox SelectionMode="Single" >
<StackPanel Orientation="Horizontal">
<CheckBox Style="{StaticResource styleCustomCheckBox}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="4,0,4,0"/>
<TextBlock VerticalAlignment="Top"
Text="SomeRecentDocument.resx"/>
</StackPanel>
</ListBox>
</code></pre>
<p><strong>How can I change the images used for the custom <code>CheckBox</code> (i.e. change the pinned/un-pinned to tick/cross etc.) without having to create a new style/template?</strong></p>
<p>Thanks for your time.</p>
| 0 | 1,261 |
fixed page, content scrolling behind header
|
<p>I am working on a website. I have most of the page fixed, except I want the table in the middle to scroll with the main scrollbar. Then I have an image in the background that I want to partially show through. I have it mostly working. The only part I cannot figure out is how to get the table content to go behind or even stop when it gets to the header. I will include a fiddle so you can see what I am talking about.
HTML:</p>
<pre><code><body>
<div id="background"></div>
<div id="tableBackground"></div>
<div id="fixedHeader">
<h1>fixed header</h1>
<h2>Subheading</h2>
</div>
<div id="tableContainer">
<table class="stocks compact display cell-border">
<tr><td>row 1 cell 1</td><td>row 1 cell 2</td></tr>
<tr><td>row 2 cell 1</td><td>row 2 cell 2</td></tr>
<tr><td>row 3 cell 1</td><td>row 3 cell 2</td></tr>
<tr><td>row 4 cell 1</td><td>row 4 cell 2</td></tr>
<tr><td>row 5 cell 1</td><td>row 5 cell 2</td></tr>
<tr><td>row 6 cell 1</td><td>row 6 cell 2</td></tr>
<tr><td>row 7 cell 1</td><td>row 7 cell 2</td></tr>
<tr><td>row 8 cell 1</td><td>row 8 cell 2</td></tr>
<tr><td>row 9 cell 1</td><td>row 9 cell 2</td></tr>
<tr><td>row 10 cell 1</td><td>row 10 cell 2</td></tr>
<tr><td>row 11 cell 1</td><td>row 11 cell 2</td></tr>
<tr><td>row 12 cell 1</td><td>row 12 cell 2</td></tr>
<tr><td>row 13 cell 1</td><td>row 13 cell 2</td></tr>
<tr><td>row 14 cell 1</td><td>row 14 cell 2</td></tr>
<tr><td>row 15 cell 1</td><td>row 15 cell 2</td></tr>
<tr><td>row 16 cell 1</td><td>row 16 cell 2</td></tr>
<tr><td>row 17 cell 1</td><td>row 17 cell 2</td></tr>
<tr><td>row 18 cell 1</td><td>row 18 cell 2</td></tr>
<tr><td>row 19 cell 1</td><td>row 19 cell 2</td></tr>
<tr><td>row 20 cell 1</td><td>row 20 cell 2</td></tr>
<tr><td>row 21 cell 1</td><td>row 21 cell 2</td></tr>
<tr><td>row 22 cell 1</td><td>row 22 cell 2</td></tr>
<tr><td>row 23 cell 1</td><td>row 23 cell 2</td></tr>
<tr><td>row 24 cell 1</td><td>row 24 cell 2</td></tr>
<tr><td>row 25 cell 1</td><td>row 25 cell 2</td></tr>
<tr><td>row 26 cell 1</td><td>row 26 cell 2</td></tr>
<tr><td>row 27 cell 1</td><td>row 27 cell 2</td></tr>
<tr><td>row 28 cell 1</td><td>row 28 cell 2</td></tr>
<tr><td>row 29 cell 1</td><td>row 29 cell 2</td></tr>
<tr><td>row 30 cell 1</td><td>row 30 cell 2</td></tr>
<tr><td>row 31 cell 1</td><td>row 31 cell 2</td></tr>
<tr><td>row 32 cell 1</td><td>row 32 cell 2</td></tr>
<tr><td>row 33 cell 1</td><td>row 33 cell 2</td></tr>
<tr><td>row 34 cell 1</td><td>row 34 cell 2</td></tr>
<tr><td>row 35 cell 1</td><td>row 35 cell 2</td></tr>
<tr><td>row 36 cell 1</td><td>row 36 cell 2</td></tr>
<tr><td>row 37 cell 1</td><td>row 37 cell 2</td></tr>
<tr><td>row 38 cell 1</td><td>row 38 cell 2</td></tr>
<tr><td>row 39 cell 1</td><td>row 39 cell 2</td></tr>
<tr><td>row 40 cell 1</td><td>row 40 cell 2</td></tr>
<tr><td>row 41 cell 1</td><td>row 41 cell 2</td></tr>
<tr><td>row 42 cell 1</td><td>row 42 cell 2</td></tr>
<tr><td>row 43 cell 1</td><td>row 43 cell 2</td></tr>
<tr><td>row 44 cell 1</td><td>row 44 cell 2</td></tr>
<tr><td>row 45 cell 1</td><td>row 45 cell 2</td></tr>
<tr><td>row 46 cell 1</td><td>row 46 cell 2</td></tr>
</table>
</div>
</body>
</code></pre>
<p>CSS:</p>
<pre><code> html {
background: url(http://oi65.tinypic.com/29dhf6g.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
html,body{
margin: 0;
padding: 0;
}
#background {
position: fixed;
top: 0;
left: 0;
z-index: -10;
width: 100%;
height: 100%;
}
#tableBackground {
position: fixed;
width: 90%;
height: 100%;
max-width: 1200px;
margin: 0 auto;
background: rgba(255, 255, 255, 0.8);
left: 0;
right: 0;
z-index: 0;
}
#fixedHeader {
position: fixed;
left: 50%;
top: 0;
margin-left:-600px;
width: 1200px;
height: 80px;
z-index: 10;
}
#tableContainer {
position: relative;
top: 80px;
width: 1200px;
margin: 0 auto;
}
.stocks {
margin: 20px auto;
}
h1 {
font-size: 1.4em;
text-align: center;
}
h2 {
font-size: 1.2em;
text-align: center;
}
</code></pre>
<p>And here is my <a href="http://jsfiddle.net/Lmwuz4gf/" rel="noreferrer">fiddle</a> so you can see what exactly I am describing. You can see the table content shows behind the header when it scrolls up. I want it to hide when it gets to the header.</p>
| 0 | 3,886 |
Undefined method `instance' for Capistrano::Configuration:Class
|
<p>I am trying to get Capistrano up and running for the first time in a rails app. I have a linux server running Ubuntu 12.04, nginx, unicorn and rails, however, I seem to be running into a few issues. I am also using Capistrano 3.0.0, rails 3.2.14, bundler 1.4.0 & ruby 1.9.3p448 using RVM. </p>
<p>I only have a production stage set up and at this point in time and I'm only concerned with Capistrano communicating with my server and pushing my code from github ( No migrations and bundling etc just yet).</p>
<p>When I try the command <code>cap production deploy:check</code> or <code>cap production deploy:setup</code> ( which seems to be deprecated?) with the setup below, I get the following error msg:</p>
<p>I'm not really sure where to start on this error, and google doesn't suggest much. I have tried adding the <code>rvm-capistrano</code> gem but to no avail. How can I amend my code to address this error?</p>
<pre><code> cap aborted!
undefined method `instance' for Capistrano::Configuration:Class
/Users/andrew/.rvm/gems/ruby-1.9.3-p448/gems/bundler-1.4.0.rc.1/lib/bundler/capistrano.rb:11:in `<top (required)>'
config/deploy.rb:1:in `<top (required)>'
/Users/andrew/.rvm/gems/ruby-1.9.3-p448/gems/capistrano-3.0.0/lib/capistrano/setup.rb:12:in `load'
/Users/andrew/.rvm/gems/ruby-1.9.3-p448/gems/capistrano-3.0.0/lib/capistrano/setup.rb:12:in `block (2 levels) in <top (required)>'
/Users/andrew/.rvm/gems/ruby-1.9.3-p448/gems/capistrano-3.0.0/lib/capistrano/application.rb:12:in `run'
/Users/andrew/.rvm/gems/ruby-1.9.3-p448/gems/capistrano-3.0.0/bin/cap:3:in `<top (required)>'
/Users/andrew/.rvm/gems/ruby-1.9.3-p448/bin/cap:23:in `load'
/Users/andrew/.rvm/gems/ruby-1.9.3-p448/bin/cap:23:in `<main>'
Tasks: TOP => production
(See full trace by running task with --trace)
</code></pre>
<p>deploy.rb</p>
<pre><code>require "bundler/capistrano"
set :stages, %w(staging production)
set :default_stage, "production"
set :application, "my_app"
set :user, "andrew"
set :scm, "git"
set :repository, "https://github.com/my_repo/#{application}"
set :branch, "master"
set :deploy_to, "/home/rails/#{application}"
set :deploy_via, :remote_cache
set :use_sudo, false
default_run_options[:pty] = true
ssh_options[:forward_agent] = true
after "deploy", "deploy:cleanup" # keep only the last 5 releases
namespace :deploy do
task :restart, roles: :app do
run "touch #{current_path}tmp/restart.txt"
end
end
after :finishing, 'deploy:cleanup'
</code></pre>
<p>deploy/production.rb</p>
<pre><code>#Real IP ommitted
server "10.2.32.68", :web, :app, :db, primary: true
</code></pre>
<p>Capfile</p>
<pre><code># Load DSL and Setup Up Stages
require 'capistrano/setup'
# Includes default deployment tasks
require 'capistrano/deploy'
# require 'capistrano/rvm'
# require 'capistrano/rbenv'
# require 'capistrano/chruby'
# require 'capistrano/bundler'
# require 'capistrano/rails/assets'
# require 'capistrano/rails/migrations'
# Loads custom tasks from `lib/capistrano/tasks' if you have any defined.
Dir.glob('lib/capistrano/tasks/*.cap').each { |r| import r }
</code></pre>
<p><strong>EDIT</strong> After looking at the offending line in capistrano.rb within bundler it mentions to add require 'bundler/deployment' to deploy.rb, which has seemed to get rid of the capistrano instance error.</p>
<p><strong>NOTE</strong> Downgraded to capistrano 2.15.5 which got rid of the errors.</p>
| 0 | 1,330 |
pg_upgrade on Windows cannot write to log file pg_upgrade_internal.log
|
<p>I'm trying to run pg_upgrade on Windows 2008R2, but I'm getting the error:</p>
<blockquote>
<p>cannot write to log file pg_upgrade_internal.log Failure, exiting</p>
</blockquote>
<p>I saw a similar question for Linux at <a href="https://stackoverflow.com/questions/23216734/cannot-write-to-log-file-pg-upgrade-internal-log-when-upgrading-from-postgresq">23216734</a> which explains that the issue is with permissions, but it doesn't help with Windows as I do not have a user named <code>postgres</code></p>
<p>Same goes for the <a href="http://www.postgresql.org/docs/current/static/pgupgrade.html" rel="noreferrer">pg_upgrade docs</a>, which mention a <code>postgres</code> user:</p>
<blockquote>
<p>RUNAS /USER:postgres "CMD.EXE"</p>
</blockquote>
<p>But again, I do not have such a user, and am trying to run this command as Administrator so I don't understand why I would have no permission. I even tried to do </p>
<pre><code>RUNAS /USER:Administrator "CMD.EXE"
</code></pre>
<p>And run pg_upgrade in the new command prompt, but am getting the same error.</p>
<p>Also, I am not sure which directory needs permissions? Where is the process trying to write <code>pg_upgrade_internal.log</code> to?</p>
<hr>
<p>More details:</p>
<p>The command I'm running is:</p>
<pre class="lang-none prettyprint-override"><code>C:\Apps\postgresql\pgsql-9.5.0\bin>pg_upgrade.exe --old-datadir=E:\PGSQL_data --new-datadir=E:\PGSQLData\pgsql-9.5 --old-bindir=C:\Apps\postgresql\pgsql-9.4.5.3\bin --new-bindir=C:\Apps\postgresql\pgsql-9.5.0\bin
</code></pre>
<p>From the same command prompt that gives the error I ran the following commands and they all worked, creating an empty file in the respective directories, so write permissions to the directories that are passed to pg_upgrade are allowed:</p>
<pre><code>C:\Apps\postgresql\pgsql-9.5.0\bin>type nul > E:\PGSQL_data\_test_write_permission.txt
C:\Apps\postgresql\pgsql-9.5.0\bin>type nul > E:\PGSQLData\pgsql-9.5\_test_write_permission.txt
C:\Apps\postgresql\pgsql-9.5.0\bin>type nul > C:\Apps\postgresql\pgsql-9.4.5.3\bin\_test_write_permission.txt
C:\Apps\postgresql\pgsql-9.5.0\bin>type nul > C:\Apps\postgresql\pgsql-9.5.0\bin\_test_write_permission.txt
</code></pre>
<p>So now I'm even more puzzled than before...</p>
<hr>
<p>Even more details:</p>
<p>I see that the command to create the internal log file is at <a href="https://github.com/postgres/postgres/blob/master/src/bin/pg_upgrade/option.c#L101" rel="noreferrer">/src/bin/pg_upgrade/option.c#L101</a></p>
<p>Which calls <code>fopen_priv(INTERNAL_LOG_FILE, "a")</code> defined at
<a href="https://github.com/postgres/postgres/blob/master/src/bin/pg_upgrade/file.c#L243" rel="noreferrer">/src/bin/pg_upgrade/file.c#L243</a></p>
<p>But I'm not sure to which directory it is trying to write. If I would know that then I can check the permissions on that directory. </p>
<p>Any ideas?</p>
| 0 | 1,133 |
Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given
|
<p>I'm learning Symfony 2 and I got the following error when I submit a form: </p>
<blockquote>
<p>Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in C:\xampp\htdocs\ppe2\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php on line 555 and defined</p>
</blockquote>
<p>Here is my code : </p>
<p>Controller : </p>
<pre><code> public function ajouterAction(Request $request){
$sponsor = new Sponsor();
$formulaire = $this->createForm(new SponsorType(), $sponsor)->add('Ajouter', 'submit');
if ($formulaire->handleRequest($request)->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($sponsor);
$em->flush();
$request->getSession()->getFlashBag()->add('notice', 'Le sponsor a bien été modfié !');
return $this->redirect($this->generateUrl('ffe_sponsor_voir', array('id' => $sponsor->getId())));
}
return $this->render('FFESponsorBundle:Sponsor:ajouter.html.twig', array(
'formulaire' => $formulaire->createView(),
));
}
</code></pre>
<p>My form type SponsorType : </p>
<pre><code>public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom', 'text')
->add('rue', 'text')
->add('codePostal', 'text')
->add('ville', 'text')
->add('telephone', 'text')
->add('mail', 'text')
->add('nomRepresentant', 'text')
->add('typeSponsor', 'entity', array(
'class' => 'FFESponsorBundle:TypeSponsor',
'property' => 'nom',
'multiple' => true
))
;
}
</code></pre>
<p>My typeSponsor and Sponsor entities are linked by a ManyToMany relation.</p>
<p>Any idea what's wrong?</p>
<p>UPDATE : </p>
<p>This is my entity : </p>
<pre><code><?php
namespace FFE\SponsorBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Sponsor
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="FFE\SponsorBundle\Entity\SponsorRepository")
*/
class Sponsor
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* @var string
*
* @ORM\Column(name="rue", type="string", length=255)
*/
private $rue;
/**
* @var string
*
* @ORM\Column(name="codePostal", type="string", length=5)
*/
private $codePostal;
/**
* @var string
*
* @ORM\Column(name="ville", type="string", length=45)
*/
private $ville;
/**
* @var string
*
* @ORM\Column(name="telephone", type="string", length=10)
*/
private $telephone;
/**
* @var string
*
* @ORM\Column(name="mail", type="string", length=255)
*/
private $mail;
/**
* @var string
*
* @ORM\Column(name="nomRepresentant", type="string", length=45)
*/
private $nomRepresentant;
/**
* @ORM\ManyToMany(targetEntity="FFE\SponsorBundle\Entity\TypeSponsor", cascade={"persist"})
*/
private $typeSponsor;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* @param string $nom
* @return Sponsor
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set rue
*
* @param string $rue
* @return Sponsor
*/
public function setRue($rue)
{
$this->rue = $rue;
return $this;
}
/**
* Get rue
*
* @return string
*/
public function getRue()
{
return $this->rue;
}
/**
* Set codePostal
*
* @param string $codePostal
* @return Sponsor
*/
public function setCodePostal($codePostal)
{
$this->codePostal = $codePostal;
return $this;
}
/**
* Get codePostal
*
* @return string
*/
public function getCodePostal()
{
return $this->codePostal;
}
/**
* Set ville
*
* @param string $ville
* @return Sponsor
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* @return string
*/
public function getVille()
{
return $this->ville;
}
/**
* Set telephone
*
* @param string $telephone
* @return Sponsor
*/
public function setTelephone($telephone)
{
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* @return string
*/
public function getTelephone()
{
return $this->telephone;
}
/**
* Set mail
*
* @param string $mail
* @return Sponsor
*/
public function setMail($mail)
{
$this->mail = $mail;
return $this;
}
/**
* Get mail
*
* @return string
*/
public function getMail()
{
return $this->mail;
}
/**
* Set nomRepresentant
*
* @param string $nomRepresentant
* @return Sponsor
*/
public function setNomRepresentant($nomRepresentant)
{
$this->nomRepresentant = $nomRepresentant;
return $this;
}
/**
* Get nomRepresentant
*
* @return string
*/
public function getNomRepresentant()
{
return $this->nomRepresentant;
}
/**
* Set typeSponsor
*
* @param \FFE\SponsorBundle\Entity\TypeSponsor $typeSponsor
* @return Sponsor
*/
public function setTypeSponsor(\FFE\SponsorBundle\Entity\TypeSponsor $typeSponsor = null)
{
$this->typeSponsor = $typeSponsor;
return $this;
}
/**
* Get typeSponsor
*
* @return \FFE\SponsorBundle\Entity\TypeSponsor
*/
public function getTypeSponsor()
{
return $this->typeSponsor;
}
}
</code></pre>
| 0 | 3,144 |
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]
|
<p>Am deploying an application repair-service on Apache Tomcat server using Eclipse, but the issue seems that the application is not getting copied in the webapps folder i.e its not getting published.</p>
<p>HTTPConnectionManager class is already present in the jar in build path.</p>
<pre><code>Sep 09, 2013 1:24:46 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/repair-service] has started
Sep 09, 2013 1:25:01 PM org.apache.catalina.core.StandardContext reload
SEVERE: Exception starting Context with name [/repair-service]
org.apache.catalina.LifecycleException: Failed to start component
[StandardEngine[Catalina].StandardHost[localhost].StandardContext[/repair-service]]
`enter code here`at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3926)
at org.apache.catalina.startup.HostConfig.checkResources(HostConfig.java:1271)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1440)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:301)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1374)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/httpclient/HttpConnectionManager
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Unknown Source)
at java.lang.Class.getDeclaredFields(Unknown Source)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:261)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:140)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:67)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:405)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:881)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.httpclient.HttpConnectionManager
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
... 25 more
Sep 09, 2013 1:25:01 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/repair-service] is completed
</code></pre>
| 0 | 1,327 |
How to replace a part of a string in an xml file?
|
<p>I have an xml file with something like this:</p>
<pre><code><Verbiage>
The whiskers plots are based on the responses of incarcerated
<Choice>
<Juvenile> juveniles who have committed sexual offenses. </Juvenile>
<Adult> adult sexual offenders. </Adult>
</Choice>
If the respondent is a
<Choice>
<Adult>convicted sexual offender, </Adult>
<Juvenile>juvenile who has sexually offended, </Juvenile>
</Choice>
#his/her_lc# percentile score, which defines #his/her_lc# position
relative to other such offenders, should be taken into account as well as #his/her_lc# T score. Percentile
scores in the top decile (> 90 %ile) of such offenders suggest that the respondent
may be defensive and #his/her_lc# report should be interpreted with this in mind.
</Verbiage>
</code></pre>
<p>I am trying to find a way to parse the xml file (I've been using DOM), search for #his/her_lc# and replace that with "her". I've tried using FileReader,BufferedReader, string.replaceAll, FileWriter, but those didn't work.</p>
<p>Is there a way I could do this using XPath?</p>
<p>Ultimately I want to search this xml file for this string and replace it with another string.</p>
<p>do I have to add a tag around the string I want it parse it that way?</p>
<p>Code I tried:</p>
<pre><code>protected void parse() throws ElementNotValidException {
try {
//Parse xml File
File inputXML = new File("template.xml");
DocumentBuilderFactory parser = DocumentBuilderFactory.newInstance(); // new instance of doc builder
DocumentBuilder dParser = parser.newDocumentBuilder(); // calls it
Document doc = dParser.parse(inputXML); // parses file
FileReader reader = new FileReader(inputXML);
String search = "#his/her_lc#";
String newString;
BufferedReader br = new BufferedReader(reader);
while ((newString = br.readLine()) != null){
newString.replaceAll(search, "her");
}
FileWriter writer = new FileWriter(inputXML);
writer.write(newString);
writer.close();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
</code></pre>
<p>Code I was given to fix:</p>
<pre><code>try {
File inputXML = new File("template.xml"); // creates new input file
DocumentBuilderFactory parser = DocumentBuilderFactory.newInstance(); // new instance of doc builder
DocumentBuilder dParser = parser.newDocumentBuilder(); // calls it
Document doc = dParser.parse(inputXML); // parses file
doc.getDocumentElement().normalize();
NodeList pList = doc.getElementsByTagName("Verbiage"); // gets element by tag name and places into list to begin parsing
int gender = 1; // gender has to be taken from the response file, it is hard coded for testing purposes
System.out.println("----------------------------"); // new line
// loops through the list of Verbiage tags
for (int temp = 0; temp < pList.getLength(); temp++) {
Node pNode = pList.item(0); // sets node to temp
if (pNode.getNodeType() == Node.ELEMENT_NODE) { // if the node type = the element node
Element eElement = (Element) pNode;
NodeList pronounList = doc.getElementsByTagName("pronoun"); // gets a list of pronoun element tags
if (gender == 0) { // if the gender is male
int count1 = 0;
while (count1 < pronounList.getLength()) {
if ("#he/she_lc#".equals(pronounList.item(count1).getTextContent())) {
pronounList.item(count1).setTextContent("he");
}
if ("#he/she_caps#".equals(pronounList.item(count1).getTextContent())) {
pronounList.item(count1).setTextContent("He");
}
if ("#his/her_lc#".equals(pronounList.item(count1).getTextContent())) {
pronounList.item(count1).setTextContent("his");
}
if ("#his/her_caps#".equals(pronounList.item(count1).getTextContent())) {
pronounList.item(count1).setTextContent("His");
}
if ("#him/her_lc#".equals(pronounList.item(count1).getTextContent())) {
pronounList.item(count1).setTextContent("him");
}
count1++;
}
pNode.getNextSibling();
} else if (gender == 1) { // female
int count = 0;
while (count < pronounList.getLength()) {
if ("#he/she_lc#".equals(pronounList.item(count).getTextContent())) {
pronounList.item(count).setTextContent("she");
}
if ("#he/she_caps3".equals(pronounList.item(count).getTextContent())) {
pronounList.item(count).setTextContent("She");
}
if ("#his/her_lc#".equals(pronounList.item(count).getTextContent())) {
pronounList.item(count).setTextContent("her");
}
if ("#his/her_caps#".equals(pronounList.item(count).getTextContent())) {
pronounList.item(count).setTextContent("Her");
}
if ("#him/her_lc#".equals(pronounList.item(count).getTextContent())) {
pronounList.item(count).setTextContent("her");
}
count++;
}
pNode.getNextSibling();
}
}
}
// write the content to file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
System.out.println("-----------Modified File-----------");
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, new StreamResult(new FileOutputStream("template.xml"))); // writes changes to file
} catch (Exception e) {
e.printStackTrace();
}
</code></pre>
<p>}</p>
<p>This code I think would work if I could figure out how to associate the tag Pronoun with the pronounParser that this code is in.</p>
| 0 | 3,148 |
SQLite error code = 1
|
<p>I'm trying to insert some data into my SQLite database. But I keeo receiving an error code 1 saying that my column does not exist. Can someone help me please, Below is my code:</p>
<pre><code>08-17 13:12:46.473: I/Database(13328): sqlite returned: error code = 1, msg = table login has no column named uid
08-17 13:12:46.503: E/Database(13328): Error inserting uid=502e7b90657ab1.86949026 created_at=2012-08-17 12:12:48 email=epaas name=hwheuu
08-17 13:12:46.503: E/Database(13328): android.database.sqlite.SQLiteException: table login has no column named uid: , while compiling: INSERT INTO login(uid, created_at, email, name) VALUES(?, ?, ?, ?);
08-17 13:12:46.503: E/Database(13328): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
08-17 13:12:46.503: E/Database(13328): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
08-17 13:12:46.503: E/Database(13328): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
08-17 13:12:46.503: E/Database(13328): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
08-17 13:12:46.503: E/Database(13328): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:41)
08-17 13:12:46.503: E/Database(13328): at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1231)
08-17 13:12:46.503: E/Database(13328): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1658)
08-17 13:12:46.503: E/Database(13328): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1515)
08-17 13:12:46.503: E/Database(13328): at library.DatabaseHandler.addUser(DatabaseHandler.java:69)
08-17 13:12:46.503: E/Database(13328): at com.thryfting.www.RegisterActivity$register.doInBackground(RegisterActivity.java:135)
08-17 13:12:46.503: E/Database(13328): at com.thryfting.www.RegisterActivity$register.doInBackground(RegisterActivity.java:1)
08-17 13:12:46.503: E/Database(13328): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-17 13:12:46.503: E/Database(13328): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-17 13:12:46.503: E/Database(13328): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-17 13:12:46.503: E/Database(13328): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-17 13:12:46.503: E/Database(13328): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-17 13:12:46.503: E/Database(13328): at java.lang.Thread.run(Thread.java:1027)
</code></pre>
<p>Below is my database code:</p>
<pre><code>package library;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "thryfting_api";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " INTEGER,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
}
</code></pre>
| 0 | 2,529 |
$(...).tabs is not a function jQuery UI 1.10.4
|
<p>Getting this error $(..).tabs not a function.</p>
<p>here are my imports</p>
<p><code><link rel="stylesheet" href="css/jquery-ui-1.10.4.css" type="text/css"></link>
<script type="text/javascript" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.js"></script><br>
<script type="text/javascript" src="js/home.js"></script></code></p>
<p>Can you help debugging that.</p>
<p>JSP FILE</p>
<pre><code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login to Web Service Details Tool</title>
<script type="text/javascript" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.custom.js"></script>
<script type="text/javascript" src="js/home.js"></script>
<link rel="stylesheet" href="css/jquery-ui-1.9.2.custom.css" type="text/css"></link>
</head>
<body>
<div id="tabs">
<ul>
<li><a href="#tabs1">Overview</a></li>
<li><a href="#tabs2">Web Service Dashboard</a></li>
<li><a href="#tabs3">Console</a></li>
</ul>
<div id="tabs1">
<jsp:include page="overview.jsp" />
</div>
<div id="tabs2">
<jsp:include page="dashboard.jsp"/>
</div>
<div id="tabs3">
<jsp:include page="menu.jsp" />
</div>
</div>
<br><br>
</code></pre>
<p>
</p>
<p>This was working until today, i don't know why it stopped working & console is throwing me error <code>tabs</code> is not defined function</p>
| 0 | 1,118 |
maven-surefire-report-plugin 2.8 error: org.apache.maven.doxia.siterenderer.sink.SiteRendererSink.unknown
|
<p>My project started to fail during the execution of <code>mvn site:site</code> since I updated the maven-surefire-report-plugin to version 2.8, which was just <a href="http://www.mail-archive.com/users@maven.apache.org/msg117227.html" rel="nofollow noreferrer">released a week or so ago</a>.</p>
<p>Here is the exception:</p>
<pre><code>[INFO] ------------------------------------------------------------------------
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] org.apache.maven.doxia.siterenderer.sink.SiteRendererSink.unknown(Ljava/lang/String;[Ljava/lang/Object;Lorg/apache/maven/doxia/sink/SinkEventAttributes;)V
[INFO] ------------------------------------------------------------------------
[INFO] Trace
java.lang.AbstractMethodError: org.apache.maven.doxia.siterenderer.sink.SiteRendererSink.unknown(Ljava/lang/String;[Ljava/lang/Object;Lorg/apache/maven/doxia/sink/SinkEventAttributes;)V
at org.apache.maven.plugins.surefire.report.SurefireReportGenerator.doGenerateReport(SurefireReportGenerator.java:76)
at org.apache.maven.plugins.surefire.report.SurefireReportMojo.executeReport(SurefireReportMojo.java:200)
at org.apache.maven.reporting.AbstractMavenReport.generate(AbstractMavenReport.java:190)
at org.apache.maven.reporting.AbstractMavenReport.generate(AbstractMavenReport.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at hudson.maven.agent.ComponentInterceptor.invoke(ComponentInterceptor.java:47)
at hudson.maven.agent.PluginManagerInterceptor$3.invoke(PluginManagerInterceptor.java:229)
at $Proxy7.generate(Unknown Source)
at org.apache.maven.plugins.site.ReportDocumentRenderer.renderDocument(ReportDocumentRenderer.java:139)
at org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.renderModule(DefaultSiteRenderer.java:269)
at org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.render(DefaultSiteRenderer.java:101)
at org.apache.maven.plugins.site.SiteMojo.renderLocale(SiteMojo.java:133)
at org.apache.maven.plugins.site.SiteMojo.execute(SiteMojo.java:100)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490)
at hudson.maven.agent.PluginManagerInterceptor.executeMojo(PluginManagerInterceptor.java:182)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:569)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:539)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
at org.apache.maven.lifecycle.LifecycleExecutorInterceptor.execute(LifecycleExecutorInterceptor.java:65)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at hudson.maven.agent.Main.launch(Main.java:165)
at hudson.maven.MavenBuilder.call(MavenBuilder.java:165)
at hudson.maven.MavenModuleSetBuild$Builder.call(MavenModuleSetBuild.java:744)
at hudson.maven.MavenModuleSetBuild$Builder.call(MavenModuleSetBuild.java:688)
at hudson.remoting.UserRequest.perform(UserRequest.java:114)
at hudson.remoting.UserRequest.perform(UserRequest.java:48)
at hudson.remoting.Request$2.run(Request.java:270)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
</code></pre>
<p>Here is the relevant section of my pom file:</p>
<pre><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.8/version>
<configuration>
<argLine>-Xmx512m</argLine>
</configuration>
</plugin>
</code></pre>
<p>Switching back to version 2.7.2 results in no error. Anyone knows more about this? Thanks.</p>
| 0 | 1,945 |
aplay / alsaplayer - sound not working for normal user
|
<p>I cannot use alsa as a normal user (resulting in me not having sound in chromium).</p>
<p>I am guessing it has something to do with permissions. Adding myself to group audio didn't help.</p>
<pre><code>[zarac@towelie ~]$ grep audio /etc/group
audio:x:92:mpd,zarac
</code></pre>
<p>Testing sound as normal user:</p>
<pre><code>[zarac@towelie ~]$ aplay /usr/share/sounds/alsa/Noise.wav
ALSA lib confmisc.c:768:(parse_card) cannot find card '0'
ALSA lib conf.c:4154:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4154:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1251:(snd_func_refer) error evaluating name
ALSA lib conf.c:4154:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:4633:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2211:(snd_pcm_open_noupdate) Unknown PCM default
aplay: main:654: audio open error: No such file or directory
[zarac@towelie ~]$
</code></pre>
<p>and as root...</p>
<pre><code>[root@towelie zarac]# aplay /usr/share/sounds/alsa/Noise.wav
Playing WAVE '/usr/share/sounds/alsa/Noise.wav' : Signed 16 bit Little Endian, Rate 48000 Hz, Mono
[root@towelie zarac]#
</code></pre>
<p>Running the command 'aplay -l' as normal user:</p>
<pre><code>[zarac@towelie ~]$ aplay -l
aplay: device_list:235: no soundcards found...
</code></pre>
<p>and as root...</p>
<pre><code>[root@towelie zarac]# aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: XFi [Creative X-Fi], device 0: ctxfi [Front/WaveIn]
Subdevices: 6/8
Subdevice #0: subdevice #0
Subdevice #1: subdevice #1
Subdevice #2: subdevice #2
Subdevice #3: subdevice #3
Subdevice #4: subdevice #4
Subdevice #5: subdevice #5
Subdevice #6: subdevice #6
Subdevice #7: subdevice #7
card 0: XFi [Creative X-Fi], device 1: ctxfi [Surround]
Subdevices: 8/8
Subdevice #0: subdevice #0
Subdevice #1: subdevice #1
Subdevice #2: subdevice #2
Subdevice #3: subdevice #3
Subdevice #4: subdevice #4
Subdevice #5: subdevice #5
Subdevice #6: subdevice #6
Subdevice #7: subdevice #7
card 0: XFi [Creative X-Fi], device 2: ctxfi [Center/LFE]
Subdevices: 8/8
Subdevice #0: subdevice #0
Subdevice #1: subdevice #1
Subdevice #2: subdevice #2
Subdevice #3: subdevice #3
Subdevice #4: subdevice #4
Subdevice #5: subdevice #5
Subdevice #6: subdevice #6
Subdevice #7: subdevice #7
card 0: XFi [Creative X-Fi], device 3: ctxfi [Side]
Subdevices: 8/8
Subdevice #0: subdevice #0
Subdevice #1: subdevice #1
Subdevice #2: subdevice #2
Subdevice #3: subdevice #3
Subdevice #4: subdevice #4
Subdevice #5: subdevice #5
Subdevice #6: subdevice #6
Subdevice #7: subdevice #7
card 0: XFi [Creative X-Fi], device 4: ctxfi [IEC958 Non-audio]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 1: Intel [HDA Intel], device 0: ALC889A Analog [ALC889A Analog]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 1: Intel [HDA Intel], device 1: ALC889A Digital [ALC889A Digital]
Subdevices: 1/1
Subdevice #0: subdevice #0
</code></pre>
<p>Any clues to what might be causing this is appreciated. Perhaps something needs to be chmodded somwhere?</p>
| 0 | 1,273 |
Multilevel (up to 3 level) Vertical Menu with bootstrap/Jquery
|
<p>I am trying to create a navigation menu which is vertical and up to 3-level navigation and last level is toggable menu (when u click on last level menu,a set of submenu appears below that).A sample structure of the menu structure is similar to this</p>
<p><img src="https://i.stack.imgur.com/HWUrk.png" alt="enter image description here"></p>
<p>I tried below code but doesn't getting desired output</p>
<pre><code> <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap </title>
<!-- Bootstrap -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link href="StyleSheet1.css" rel="stylesheet" />
<!-- Optional theme
<link rel="stylesheet" href="">
-->
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.dropdown-submenu {
position: relative;
border-bottom: 1px solid #ccc;
}
.dropdown-submenu > .dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
-webkit-border-radius: 0 6px 6px 6px;
-moz-border-radius: 0 6px 6px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover > .dropdown-menu {
display: block;
}
.dropdown-submenu > a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #ccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover > a:after {
border-left-color: #fff;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left > .dropdown-menu {
left: -100%;
margin-left: 10px;
-webkit-border-radius: 6px 0 6px 6px;
-moz-border-radius: 6px 0 6px 6px;
border-radius: 6px 0 6px 6px;
}
ul {
list-style: none;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-3 column margintop20">
<ul class="nav nav-pills nav-stacked">
<li class="dropdown-submenu active">
<a tabindex="-1" href="#">Client Advice</a>
<ul class="dropdown-menu">
<li class="dropdown-submenu"><a tabindex="-1" href="#">Pre-advice</a></li>
<li class="dropdown-submenu"><a href="#">Strategy & Technical</a></li>
<li class="dropdown-submenu"><a href="#">Research</a></li>
<li class="dropdown-submenu active">
<a href="#">APL & Products</a>
<ul class="dropdown-menu parent">
<li style=" border-bottom: 1px solid #ccc;">
<a href="#">
Approved Product List
<span aria-hidden="true" class="glyphicon glyphicon-plus"></span>
<span aria-hidden="true" class="glyphicon glyphicon-minus" style="display:none;"></span>
</a>
<ul class="child">
<li style="padding:10px 15px;">Platforms</li>
<li style="padding: 10px 15px;">Managed Funds</li>
<li style="padding: 10px 15px;">Wealth Protection</li>
<li style="padding: 10px 15px;">Listed Securities</li>
<li style="padding: 10px 15px;">Wealth Protection</li>
<li style="padding: 10px 15px;">Listed Securities</li>
<li style="padding: 10px 15px;">Listed Securities</li>
</ul>
</li>
<li style=" border-bottom: 1px solid #ccc;"><a href="#">Model Portfolios</a></li>
<li style=" border-bottom: 1px solid #ccc;"><a href="#">Non-approved Products</a></li>
</ul>
</li>
<li class="dropdown-submenu"><a href="#">Implementation</a></li>
<li class="dropdown-submenu"><a href="#">Review</a></li>
<li class="dropdown-submenu"><a href="#">Execution Only</a></li>
</ul>
</li>
<li class="dropdown-submenu"><a href="#">Personal Development</a></li>
<li class="dropdown-submenu"><a href="#">Practice</a></li>
<li class="dropdown-submenu"><a href="#">News</a></li>
</ul>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
$('.child').hide(); //Hide children by default
$('.parent').children().click(function () {
event.preventDefault();
$(this).children('.child').slideToggle('slow');
$(this).find('span').toggle();
});
</script>
</body>
</html>
</code></pre>
<p>Is there any way to create a vertical multilevel menu structure using bootstrap,jquery I haven't got any multilevel menus with vertical orientation .Facing css issues with this code,not able to create similar navigation menu.</p>
| 0 | 4,221 |
How to catch all errors for ExoPlayer?
|
<p>I implemented ExoPlayer as player for my application. But I can´t find out how to catch all ExoPlayer errors to avoid app crash. I added following listener, but it doesn´t catch all errors.</p>
<p>I have to use DRM and it sometimes crash on some problem with it, but I can´t set listener before, because player is NULL.</p>
<pre class="lang-java prettyprint-override"><code>player = ExoPlayerFactory.newSimpleInstance(context, trackSelector, loadControl, drmSessionManager);
player.addListener(new ExoPlayer.EventListener() {
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
}
@Override
public void onPlayerError(ExoPlaybackException error) {
//Catch here, but app still crash on some errors!
}
@Override
public void onPositionDiscontinuity() {
}
});
</code></pre>
<p>Error example:</p>
<pre><code>03-22 16:38:31.401 17960-25624/com.mypackage.name E/ExoPlayerImplInternal: Renderer error.
com.google.android.exoplayer2.ExoPlaybackException
at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.shouldWaitForKeys(MediaCodecRenderer.java:709)
at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.feedInputBuffer(MediaCodecRenderer.java:650)
at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:490)
at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:464)
at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:300)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
at com.google.android.exoplayer2.util.PriorityHandlerThread.run(PriorityHandlerThread.java:40)
Caused by: com.google.android.exoplayer2.drm.DrmSession$DrmSessionException: com.google.android.exoplayer2.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to https://widevine-dash.ezdrm.com/proxy?pX=blablablabla
at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.onError(DefaultDrmSessionManager.java:594)
at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.onKeysError(DefaultDrmSessionManager.java:589)
at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.onKeyResponse(DefaultDrmSessionManager.java:549)
at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.access$900(DefaultDrmSessionManager.java:49)
at com.google.android.exoplayer2.drm.DefaultDrmSessionManager$PostResponseHandler.handleMessage(DefaultDrmSessionManager.java:669)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
at com.google.android.exoplayer2.util.PriorityHandlerThread.run(PriorityHandlerThread.java:40)
Caused by: com.google.android.exoplayer2.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to https://widevine-dash.ezdrm.com/proxy?pX=blablablabla
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:204)
at com.google.android.exoplayer2.upstream.DataSourceInputStream.checkOpened(DataSourceInputStream.java:101)
at com.google.android.exoplayer2.upstream.DataSourceInputStream.read(DataSourceInputStream.java:81)
at com.google.android.exoplayer2.upstream.DataSourceInputStream.read(DataSourceInputStream.java:75)
at com.google.android.exoplayer2.util.Util.toByteArray(Util.java:118)
at com.google.android.exoplayer2.drm.HttpMediaDrmCallback.executePost(HttpMediaDrmCallback.java:106)
at com.google.android.exoplayer2.drm.HttpMediaDrmCallback.executeKeyRequest(HttpMediaDrmCallback.java:91)
at com.google.android.exoplayer2.drm.DefaultDrmSessionManager$PostRequestHandler.handleMessage(DefaultDrmSessionManager.java:692)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
Caused by: java.net.SocketTimeoutException: timeout
at com.android.okhttp.okio.Okio$3.newTimeoutException(Okio.java:212)
at com.android.okhttp.okio.AsyncTimeout.exit(AsyncTimeout.java:250)
at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:217)
at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:306)
at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:300)
at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196)
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:906)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:782)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:463)
03-22 16:38:31.401 17960-25624/com.mypackage.name E/ExoPlayerImplInternal: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:521)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java)
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:201)
... 10 more
03-22 16:38:31.402 17960-17960/com.mypackage.name E/PlayerActivity: onPlayerError: com.google.android.exoplayer2.drm.DrmSession$DrmSessionException: com.google.android.exoplayer2.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to https://widevine-dash.ezdrm.com/proxy?pX=blablablabla
03-22 16:38:31.404 17960-17960/com.mypackage.name D/AndroidRuntime: Shutting down VM
03-22 16:38:31.407 17960-17960/com.mypackage.name E/UncaughtException: java.lang.IllegalStateException
at com.google.android.exoplayer2.util.Assertions.checkState(Assertions.java:79)
at com.google.android.exoplayer2.ExoPlaybackException.getSourceException(ExoPlaybackException.java:111)
at com.mypackage.name.ui.activities.PlayerActivity$1.onPlayerError(PlayerActivity.java:260)
at com.google.android.exoplayer2.ExoPlayerImpl.handleEvent(ExoPlayerImpl.java:382)
at com.google.android.exoplayer2.ExoPlayerImpl$1.handleMessage(ExoPlayerImpl.java:93)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
03-22 16:38:31.417 17960-25623/com.mypackage.name D/FA: Logging event (FE): _ae, Bundle[{_o=crash, _sc=PlayerActivity_, _si=-5050973009208192093, timestamp=1490197111407, fatal=1}]
03-22 16:38:31.437 17960-25684/com.mypackage.name D/SurfaceUtils: set up nativeWindow 0x791072a810 for 1x1, color 0x2, rotation 0, usage 0x930
03-22 16:38:31.454 17960-25623/com.mypackage.name V/FA: Using measurement service
03-22 16:38:31.455 17960-25623/com.mypackage.name V/FA: Connecting to remote service
03-22 16:38:31.707 17960-17960/com.mypackage.name E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mypackage.name, PID: 17960
java.lang.IllegalStateException
at com.google.android.exoplayer2.util.Assertions.checkState(Assertions.java:79)
at com.google.android.exoplayer2.ExoPlaybackException.getSourceException(ExoPlaybackException.java:111)
at com.mypackage.name.ui.activities.PlayerActivity$1.onPlayerError(PlayerActivity.java:260)
at com.google.android.exoplayer2.ExoPlayerImpl.handleEvent(ExoPlayerImpl.java:382)
at com.google.android.exoplayer2.ExoPlayerImpl$1.handleMessage(ExoPlayerImpl.java:93)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code></pre>
| 0 | 3,391 |
How to get WPF ContentControl content to stretch?
|
<p>I'm using a <code>ContentControl</code> to render various <code>UserControl</code> derivations dynamically. I can't for the life of me figure out how to get the content to stretch when I resize the parent <code>Window</code>. I've found many references like <a href="https://stackoverflow.com/questions/6767613/wpf-usercontrol-is-not-filling-parent-container-when-bound-at-runtime">this</a>, but it's still not working for me. Here is a simple example:</p>
<p>This is the <code>Window</code> XAML:</p>
<pre><code><Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary Source="Dictionary1.xaml"/>
</Window.Resources>
<Grid>
<ContentControl VerticalAlignment="Top"
HorizontalAlignment="Left"
VerticalContentAlignment="Stretch"
HorizontalContentAlignment="Stretch"
Content="{Binding Path=ChildView}"
Margin="10"/>
</Grid>
</Window>
</code></pre>
<p>This uses the resource file <code>Dictionary1.XAML</code>:</p>
<pre><code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModels ="clr-namespace:WpfApplication3"
xmlns:views ="clr-namespace:WpfApplication3">
<DataTemplate DataType="{x:Type viewModels:UserControlViewModel}">
<views:UserControl1/>
</DataTemplate>
</ResourceDictionary>
</code></pre>
<p>Here is the code behind for the main <code>Window</code> as well as the view model classes:</p>
<pre><code>public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
public class MainViewModel
{
public UserControlViewModel ChildView { get; set; }
public MainViewModel()
{
ChildView = new UserControlViewModel();
}
}
public class UserControlViewModel
{
}
</code></pre>
<p>and finally the user control:</p>
<pre><code><UserControl x:Class="WpfApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
Background="Blue"
Height="141" Width="278"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch">
<Grid>
</Grid>
</UserControl>
</code></pre>
<p>Here's what it looks like at run time:</p>
<p><img src="https://i.stack.imgur.com/4s0LK.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/KVa1i.png" alt="enter image description here"></p>
<p>What am I missing here? How can I get the child content to behave such that it remains anchored to the top/left of the parent and the bottom/right stretches as the parent is resized?</p>
| 0 | 1,469 |
What does the `Target Platform Version` mean for a VS C++ project?
|
<h2>BACKGROUND</h2>
<p>As I understand it, in a C++ project:</p>
<ul>
<li>Project Properties => Configuration Properties => General => <em>Platform Toolset</em>
<ul>
<li>Tells the compiler which SDK to physically compile against.</li>
<li>For example: v140 will tell Visual Studio 2015 to use the latest and greatest v8.1 Windows SDK</li>
</ul>
</li>
<li><code>_WIN32_WINNT</code>, <code>WINVER</code>, and <code>NTDDI_VERSION</code> macros
<ul>
<li>Depending on the underlying operating system, an SDK function can have a different function signature from OS-to-OS.</li>
<li>SDKs are suppose to be backward compatible. <a href="http://www.kndr.org/windows-sdk-brokenness" rel="noreferrer" title="Windows SDK Brokenness">1</a></li>
<li>The before mentioned macros enable you to specify which version of a function you wish to compile against.</li>
</ul>
</li>
</ul>
<h2>MY QUESTION</h2>
<p>If I compile my application with the following setup:</p>
<ul>
<li>project properties => configuration properties => General => <em>Platform Toolset</em>
<ul>
<li>set to: <code>v140_xp</code> (Visual Studio 2015 - Windows XP)</li>
<li>Setting tells compiler to use the 7.1 SDK, which makes sense.</li>
</ul>
</li>
<li>content of: <code>StdAfh.h</code>
<ul>
<li><code>#include <WinSDKVer.h></code></li>
<li><code>#define _WIN32_WINNT 0x0501</code></li>
<li><code>#define WINVER 0x0501</code></li>
<li><code>#define NTDDI_VERSION 0x05010000</code></li>
<li><code>#include <SDKDDKVer.h></code></li>
<li>Macros tell compiler which function signatures to use, which makes sense.</li>
</ul>
</li>
</ul>
<p>From what I can tell, it looks like <em>Target Platform Version</em> is an suposed to be an alternative to the <code>_WIN32_WINNT</code>, <code>WINVER</code>, and <code>NTDDI_VERSION</code> macros. The weird thing is, with the above configuration you can set the <em>Target Platform Version</em> to <code>1</code> or <code>99</code>... and the compiler doesn't generate any errors or warnings.</p>
<p>This this leaves me wondering: <strong>What is the <em>Target Platform Version</em> for?</strong></p>
<h2>ADDITIONAL CONTEXT</h2>
<ul>
<li>Compiler: Visual Studio 2015</li>
</ul>
<h2>REFERENCES</h2>
<ul>
<li><a href="http://www.kndr.org/windows-sdk-brokenness" rel="noreferrer" title="Windows SDK Brokenness">Windows SDK Brokenness</a></li>
<li><a href="https://social.msdn.microsoft.com/Forums/SqlServer/en-US/cd712d51-0b3a-4403-b448-e23922b190d2/target-platform-version-general-project-property-on-vs2015?forum=vcgeneral" rel="noreferrer">Target Platform Version general project property on VS2015</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa383745(v=vs.85).aspx" rel="noreferrer" title="Using the Windows Headers">Using the Windows Headers</a></li>
<li><a href="https://stackoverflow.com/questions/1439752/what-is-winver">What is WINVER?</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/6sehtctf.aspx" rel="noreferrer" title="Modifying WINVER and _WIN32_WINNT">Modifying WINVER and _WIN32_WINNT</a></li>
<li><a href="https://stackoverflow.com/questions/37668692/visual-studio-setting-winver-win32-winnt-to-windows-8-on-windows-7">Visual Studio setting WINVER/_WIN32_WINNT to Windows 8 on Windows 7?</a></li>
</ul>
<h2>EDIT HISTORY</h2>
<ul>
<li>2016/09/21: As per Hans' comment, macros have been updated to reference Windows XP.</li>
</ul>
| 0 | 1,233 |
Installing NumPy with pip fails on Ubuntu
|
<p>When I try:</p>
<pre><code>$ sudo pip install numpy
</code></pre>
<p>on my Ubuntu 12.04 server, I get:</p>
<pre><code>------------------------------------------------------------
/usr/local/bin/pip run on Tue Dec 10 18:25:54 2013
Downloading/unpacking numpy
Getting page https://pypi.python.org/simple/numpy/
URLs to search for versions for numpy:
* https://pypi.python.org/simple/numpy/
Analyzing links from page https://pypi.python.org/simple/numpy/
Skipping link https://pypi.python.org/packages/2.4/n/numpy/numpy-1.0.1.dev3460.win32-py2.4.exe#md5=a55b13b1f141de2aa965d5c5554c4ad8 (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Skipping link https://pypi.python.org/packages/2.5/n/numpy/numpy-1.3.0.win32-py2.5.exe#md5=28ee6681b04beb5bfc4bc056417ff087 (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Skipping link https://pypi.python.org/packages/2.5/n/numpy/numpy-1.5.1.win32-py2.5-nosse.exe#md5=bfcb66706ebdece6a9680f79f2b643ca (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Skipping link https://pypi.python.org/packages/2.5/n/numpy/numpy-1.6.0.win32-py2.5.exe#md5=539782c7311d4a3379f66a964159ef11 (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
[ ...SNIP...]
Skipping link https://pypi.python.org/packages/3.2/n/numpy/numpy-1.6.1.win32-py3.2.exe#md5=a6b66602e72436db37e6edbbce269fdf (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Skipping link https://pypi.python.org/packages/3.2/n/numpy/numpy-1.6.2.win32-py3.2.exe#md5=b98cc04b20347127e297a99b6114b514 (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Skipping link https://pypi.python.org/packages/3.2/n/numpy/numpy-1.7.0.win32-py3.2.exe#md5=1b12834a53d3ba543d41399c40b5b791 (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Skipping link https://pypi.python.org/packages/3.2/n/numpy/numpy-1.7.1.win32-py3.2.exe#md5=651465cacf107d254ddcefcebb47064d (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Skipping link https://pypi.python.org/packages/3.3/n/numpy/numpy-1.7.0.win32-py3.3.exe#md5=4f20740e7e9d31a9d4c1636a931bc3f9 (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Skipping link https://pypi.python.org/packages/3.3/n/numpy/numpy-1.7.1.win32-py3.3.exe#md5=6519c7bb198d0caf2913469883a63be9 (from https://pypi.python.org/simple/numpy/); unknown archive format: .exe
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.3.0.tar.gz#md5=3f7773ff0971a5ebb8591536d8ec7bd6 (from https://pypi.python.org/simple/numpy/), version: 1.3.0
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.4.1.tar.gz#md5=89b8a56e018b634f7d05c56f17bc4943 (from https://pypi.python.org/simple/numpy/), version: 1.4.1
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.5.0.tar.gz#md5=3a8bfdc434df782d647161c48943ee09 (from https://pypi.python.org/simple/numpy/), version: 1.5.0
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.5.1.tar.gz#md5=376ef150df41b5353944ab742145352d (from https://pypi.python.org/simple/numpy/), version: 1.5.1
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.6.0.tar.gz#md5=e0993c74cb8e83292e560eac1a9be8e9 (from https://pypi.python.org/simple/numpy/), version: 1.6.0
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.6.0.zip#md5=f0ce7ea1a12b3b3480571980af243e48 (from https://pypi.python.org/simple/numpy/), version: 1.6.0
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.6.1.tar.gz#md5=2bce18c08fc4fce461656f0f4dd9103e (from https://pypi.python.org/simple/numpy/), version: 1.6.1
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.6.1.zip#md5=462c22b8eb221c78ddd51de98fbb5979 (from https://pypi.python.org/simple/numpy/), version: 1.6.1
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.6.2.tar.gz#md5=95ed6c9dcc94af1fc1642ea2a33c1bba (from https://pypi.python.org/simple/numpy/), version: 1.6.2
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.6.2.zip#md5=7e13c931985f90efcfa0408f845d6fee (from https://pypi.python.org/simple/numpy/), version: 1.6.2
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.7.0.tar.gz#md5=4fa54e40b6a243416f0248123b6ec332 (from https://pypi.python.org/simple/numpy/), version: 1.7.0
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.7.0.zip#md5=ca27913c59393940e880fab420f985b4 (from https://pypi.python.org/simple/numpy/), version: 1.7.0
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.7.1.tar.gz#md5=0ab72b3b83528a7ae79c6df9042d61c6 (from https://pypi.python.org/simple/numpy/), version: 1.7.1
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.7.1.zip#md5=9a72db3cad7a6286c0d22ee43ad9bc6c (from https://pypi.python.org/simple/numpy/), version: 1.7.1
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.8.0.tar.gz#md5=2a4b0423a758706d592abb6721ec8dcd (from https://pypi.python.org/simple/numpy/), version: 1.8.0
Found link https://pypi.python.org/packages/source/n/numpy/numpy-1.8.0.zip#md5=6c918bb91c0cfa055b16b13850cfcd6e (from https://pypi.python.org/simple/numpy/), version: 1.8.0
Using version 1.8.0 (newest of versions: 1.8.0, 1.8.0, 1.7.1, 1.7.1, 1.7.0, 1.7.0, 1.6.2, 1.6.2, 1.6.1, 1.6.1, 1.6.0, 1.6.0, 1.5.1, 1.5.0, 1.4.1, 1.3.0)
Downloading from URL https://pypi.python.org/packages/source/n/numpy/numpy-1.8.0.tar.gz#md5=2a4b0423a758706d592abb6721ec8dcd (from https://pypi.python.org/simple/numpy/)
Running setup.py egg_info for package numpy
Running from numpy source directory.
/bin/sh: 1: svnversion: not found
non-existing path in 'numpy/distutils': 'site.cfg'
F2PY Version 2
blas_opt_info:
blas_mkl_info:
libraries mkl,vml,guide not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
openblas_info:
libraries openblas not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
atlas_blas_threads_info:
Setting PTATLAS=ATLAS
libraries ptf77blas,ptcblas,atlas not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
atlas_blas_info:
libraries f77blas,cblas,atlas not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1522: UserWarning:
Atlas (http://math-atlas.sourceforge.net/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [atlas]) or by setting
the ATLAS environment variable.
warnings.warn(AtlasNotFoundError.__doc__)
blas_info:
libraries blas not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1531: UserWarning:
Blas (http://www.netlib.org/blas/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [blas]) or by setting
the BLAS environment variable.
warnings.warn(BlasNotFoundError.__doc__)
blas_src_info:
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1534: UserWarning:
Blas (http://www.netlib.org/blas/) sources not found.
Directories to search for the sources can be specified in the
numpy/distutils/site.cfg file (section [blas_src]) or by setting
the BLAS_SRC environment variable.
warnings.warn(BlasSrcNotFoundError.__doc__)
NOT AVAILABLE
/bin/sh: 1: svnversion: not found
non-existing path in 'numpy/lib': 'benchmarks'
lapack_opt_info:
lapack_mkl_info:
mkl_info:
libraries mkl,vml,guide not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
NOT AVAILABLE
atlas_threads_info:
Setting PTATLAS=ATLAS
libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib
libraries lapack_atlas not found in /usr/local/lib
libraries ptf77blas,ptcblas,atlas not found in /usr/lib
libraries lapack_atlas not found in /usr/lib
numpy.distutils.system_info.atlas_threads_info
NOT AVAILABLE
atlas_info:
libraries f77blas,cblas,atlas not found in /usr/local/lib
libraries lapack_atlas not found in /usr/local/lib
libraries f77blas,cblas,atlas not found in /usr/lib
libraries lapack_atlas not found in /usr/lib
numpy.distutils.system_info.atlas_info
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1428: UserWarning:
Atlas (http://math-atlas.sourceforge.net/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [atlas]) or by setting
the ATLAS environment variable.
warnings.warn(AtlasNotFoundError.__doc__)
lapack_info:
libraries lapack not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1439: UserWarning:
Lapack (http://www.netlib.org/lapack/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [lapack]) or by setting
the LAPACK environment variable.
warnings.warn(LapackNotFoundError.__doc__)
lapack_src_info:
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1442: UserWarning:
Lapack (http://www.netlib.org/lapack/) sources not found.
Directories to search for the sources can be specified in the
numpy/distutils/site.cfg file (section [lapack_src]) or by setting
the LAPACK_SRC environment variable.
warnings.warn(LapackSrcNotFoundError.__doc__)
NOT AVAILABLE
/usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'define_macros'
warnings.warn(msg)
running egg_info
running build_src
build_src
building py_modules sources
creating build
creating build/src.linux-x86_64-2.7
creating build/src.linux-x86_64-2.7/numpy
creating build/src.linux-x86_64-2.7/numpy/distutils
building library "npymath" sources
customize Gnu95FCompiler
Could not locate executable gfortran
Could not locate executable f95
customize IntelFCompiler
Could not locate executable ifort
Could not locate executable ifc
customize LaheyFCompiler
Could not locate executable lf95
customize PGroupFCompiler
Could not locate executable pgfortran
customize AbsoftFCompiler
Could not locate executable f90
Could not locate executable f77
customize NAGFCompiler
customize VastFCompiler
customize CompaqFCompiler
Could not locate executable fort
customize IntelItaniumFCompiler
Could not locate executable efort
Could not locate executable efc
customize IntelEM64TFCompiler
customize GnuFCompiler
Could not locate executable g77
customize G95FCompiler
Could not locate executable g95
customize PathScaleFCompiler
Could not locate executable pathf95
don't know how to compile Fortran code on platform 'posix'
C compiler: gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC
compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/usr/include/python2.7 -c'
gcc: _configtest.c
sh: 1: gcc: not found
sh: 1: gcc: not found
failure.
removing: _configtest.c _configtest.o
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/tmp/pip_build_root/numpy/setup.py", line 192, in <module>
setup_package()
File "/tmp/pip_build_root/numpy/setup.py", line 185, in setup_package
configuration=configuration )
File "/tmp/pip_build_root/numpy/numpy/distutils/core.py", line 169, in setup
return old_setup(**new_attr)
File "/usr/lib/python2.7/distutils/core.py", line 152, in setup
dist.run_commands()
File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "/tmp/pip_build_root/numpy/numpy/distutils/command/egg_info.py", line 10, in run
self.run_command("build_src")
File "/usr/lib/python2.7/distutils/cmd.py", line 326, in run_command
self.distribution.run_command(command)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "/tmp/pip_build_root/numpy/numpy/distutils/command/build_src.py", line 153, in run
self.build_sources()
File "/tmp/pip_build_root/numpy/numpy/distutils/command/build_src.py", line 164, in build_sources
self.build_library_sources(*libname_info)
File "/tmp/pip_build_root/numpy/numpy/distutils/command/build_src.py", line 299, in build_library_sources
sources = self.generate_sources(sources, (lib_name, build_info))
File "/tmp/pip_build_root/numpy/numpy/distutils/command/build_src.py", line 386, in generate_sources
source = func(extension, build_dir)
File "numpy/core/setup.py", line 674, in get_mathlib_info
raise RuntimeError("Broken toolchain: cannot link a simple C program")
RuntimeError: Broken toolchain: cannot link a simple C program
Complete output from command python setup.py egg_info:
Running from numpy source directory.
/bin/sh: 1: svnversion: not found
non-existing path in 'numpy/distutils': 'site.cfg'
F2PY Version 2
blas_opt_info:
blas_mkl_info:
libraries mkl,vml,guide not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
openblas_info:
libraries openblas not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
atlas_blas_threads_info:
Setting PTATLAS=ATLAS
libraries ptf77blas,ptcblas,atlas not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
atlas_blas_info:
libraries f77blas,cblas,atlas not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1522: UserWarning:
Atlas (http://math-atlas.sourceforge.net/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [atlas]) or by setting
the ATLAS environment variable.
warnings.warn(AtlasNotFoundError.__doc__)
blas_info:
libraries blas not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1531: UserWarning:
Blas (http://www.netlib.org/blas/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [blas]) or by setting
the BLAS environment variable.
warnings.warn(BlasNotFoundError.__doc__)
blas_src_info:
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1534: UserWarning:
Blas (http://www.netlib.org/blas/) sources not found.
Directories to search for the sources can be specified in the
numpy/distutils/site.cfg file (section [blas_src]) or by setting
the BLAS_SRC environment variable.
warnings.warn(BlasSrcNotFoundError.__doc__)
NOT AVAILABLE
/bin/sh: 1: svnversion: not found
non-existing path in 'numpy/lib': 'benchmarks'
lapack_opt_info:
lapack_mkl_info:
mkl_info:
libraries mkl,vml,guide not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
NOT AVAILABLE
atlas_threads_info:
Setting PTATLAS=ATLAS
libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib
libraries lapack_atlas not found in /usr/local/lib
libraries ptf77blas,ptcblas,atlas not found in /usr/lib
libraries lapack_atlas not found in /usr/lib
numpy.distutils.system_info.atlas_threads_info
NOT AVAILABLE
atlas_info:
libraries f77blas,cblas,atlas not found in /usr/local/lib
libraries lapack_atlas not found in /usr/local/lib
libraries f77blas,cblas,atlas not found in /usr/lib
libraries lapack_atlas not found in /usr/lib
numpy.distutils.system_info.atlas_info
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1428: UserWarning:
Atlas (http://math-atlas.sourceforge.net/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [atlas]) or by setting
the ATLAS environment variable.
warnings.warn(AtlasNotFoundError.__doc__)
lapack_info:
libraries lapack not found in ['/usr/local/lib', '/usr/lib']
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1439: UserWarning:
Lapack (http://www.netlib.org/lapack/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [lapack]) or by setting
the LAPACK environment variable.
warnings.warn(LapackNotFoundError.__doc__)
lapack_src_info:
NOT AVAILABLE
/tmp/pip_build_root/numpy/numpy/distutils/system_info.py:1442: UserWarning:
Lapack (http://www.netlib.org/lapack/) sources not found.
Directories to search for the sources can be specified in the
numpy/distutils/site.cfg file (section [lapack_src]) or by setting
the LAPACK_SRC environment variable.
warnings.warn(LapackSrcNotFoundError.__doc__)
NOT AVAILABLE
/usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'define_macros'
warnings.warn(msg)
running egg_info
running build_src
build_src
building py_modules sources
creating build
creating build/src.linux-x86_64-2.7
creating build/src.linux-x86_64-2.7/numpy
creating build/src.linux-x86_64-2.7/numpy/distutils
building library "npymath" sources
customize Gnu95FCompiler
Could not locate executable gfortran
Could not locate executable f95
customize IntelFCompiler
Could not locate executable ifort
Could not locate executable ifc
customize LaheyFCompiler
Could not locate executable lf95
customize PGroupFCompiler
Could not locate executable pgfortran
customize AbsoftFCompiler
Could not locate executable f90
Could not locate executable f77
customize NAGFCompiler
customize VastFCompiler
customize CompaqFCompiler
Could not locate executable fort
customize IntelItaniumFCompiler
Could not locate executable efort
Could not locate executable efc
customize IntelEM64TFCompiler
customize GnuFCompiler
Could not locate executable g77
customize G95FCompiler
Could not locate executable g95
customize PathScaleFCompiler
Could not locate executable pathf95
don't know how to compile Fortran code on platform 'posix'
C compiler: gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC
compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/usr/include/python2.7 -c'
gcc: _configtest.c
sh: 1: gcc: not found
sh: 1: gcc: not found
failure.
removing: _configtest.c _configtest.o
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/tmp/pip_build_root/numpy/setup.py", line 192, in <module>
setup_package()
File "/tmp/pip_build_root/numpy/setup.py", line 185, in setup_package
configuration=configuration )
File "/tmp/pip_build_root/numpy/numpy/distutils/core.py", line 169, in setup
return old_setup(**new_attr)
File "/usr/lib/python2.7/distutils/core.py", line 152, in setup
dist.run_commands()
File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "/tmp/pip_build_root/numpy/numpy/distutils/command/egg_info.py", line 10, in run
self.run_command("build_src")
File "/usr/lib/python2.7/distutils/cmd.py", line 326, in run_command
self.distribution.run_command(command)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "/tmp/pip_build_root/numpy/numpy/distutils/command/build_src.py", line 153, in run
self.build_sources()
File "/tmp/pip_build_root/numpy/numpy/distutils/command/build_src.py", line 164, in build_sources
self.build_library_sources(*libname_info)
File "/tmp/pip_build_root/numpy/numpy/distutils/command/build_src.py", line 299, in build_library_sources
sources = self.generate_sources(sources, (lib_name, build_info))
File "/tmp/pip_build_root/numpy/numpy/distutils/command/build_src.py", line 386, in generate_sources
source = func(extension, build_dir)
File "numpy/core/setup.py", line 674, in get_mathlib_info
raise RuntimeError("Broken toolchain: cannot link a simple C program")
RuntimeError: Broken toolchain: cannot link a simple C program
----------------------------------------
Cleaning up...
Removing temporary dir /tmp/pip_build_root...
Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_root/numpy
Exception information:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 134, in main
status = self.run(options, args)
File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 236, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/local/lib/python2.7/dist-packages/pip/req.py", line 1134, in prepare_files
req_to_install.run_egg_info()
File "/usr/local/lib/python2.7/dist-packages/pip/req.py", line 259, in run_egg_info
command_desc='python setup.py egg_info')
File "/usr/local/lib/python2.7/dist-packages/pip/util.py", line 670, in call_subprocess
% (command_desc, proc.returncode, cwd))
InstallationError: Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_root/numpy
</code></pre>
<p>I have no idea what I need to do to fix this. Eventually I would be able to put all dependencies that I need in a <code>requirements.txt</code> file, so that I can install devendencies in a <code>virtualenv</code>. With that in mind, I would prefer a solution that uses <code>pip</code> as opposed to <code>apt-get</code> or installing from source.</p>
| 0 | 9,076 |
Cannot get on http://localhost:3000/
|
<p>I am using gulp.The tasks are getting run creating required folders. But I get Cannot GET/ error when run in browser.I have attached the image of my project structure and also the output in command line<a href="https://i.stack.imgur.com/T91GY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T91GY.png" alt="command line output"></a>.<a href="https://i.stack.imgur.com/2kTle.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2kTle.png" alt="Project Structure"></a> .My index.html contains the following </p>
<pre><code><!DOCTYPE html>
<html lang="en" ng-app="helloWorldApp">
<head>
<title>Angular hello world app</title>
<link href="css/main.css" rel="stylesheet">
</head>
<body>
<ng-view class="view"></ng-view>
</body>
<script src="js/scripts.js"></script>
</html>
</code></pre>
<p>I want to know why it cannot get or not routed properly and what should be done. So the problem is when the server is running on localhost and I hit localhost:3000/ in browser it says cannot get with a white background.Following is my gulpfile.js</p>
<pre><code>const gulp = require('gulp');
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();
const scripts = require('./scripts');
const styles = require('./styles');
var devMode = false;
gulp.task('css',function(){
gulp.src(styles)
.pipe(concat('main.css'))
.pipe(gulp.dest('./dist/css'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('js',function(){
gulp.src(scripts)
.pipe(concat('scripts.js'))
.pipe(gulp.dest('./dist/js'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('html',function(){
gulp.src('./templates/**/*.html')
.pipe(gulp.dest('./dist/html'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('build',function(){
gulp.start(['css','js','html']);
console.log("finshed build");
});
gulp.task('browser-sync',function(){
browserSync.init(null,{
open : false,
server : {
baseDir : 'dist'
}
});
console.log("finshed browser ");
});
gulp.task('start',function(){
devMode = true;
gulp.start(['build','browser-sync']);
gulp.watch(['./css/**/*.css'],['css']);
gulp.watch(['./js/**/*.js'],['js']);
gulp.watch(['./templates/**/*.html'],['html']);
});
</code></pre>
| 0 | 1,088 |
Couldn't expand RemoteViews
|
<p>I try to create a custom notification but getting the following exception:</p>
<pre><code>FATAL EXCEPTION: main
android.app.RemoteServiceException: Bad notification posted from package com.my.app: Couldn't expand RemoteViews for: StatusBarNotification(pkg=com.my.app user=UserHandle{0} id=1 tag=null score=0: Notification(pri=0 contentView=com.my.app/0x7f03001b vibrate=null sound=null defaults=0x0 flags=0x2 kind=[null]))
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1423)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>My code looks like this:</p>
<pre><code>Intent intent = new Intent(this, MyFragmentActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent launchIntent = PendingIntent.getActivity(this, 0, intent, 0);
RemoteViews notificationView = new RemoteViews(this.getPackageName(), R.layout.notification_layout);
notificationView.setImageViewBitmap(R.id.notification_icon, icon);
notificationView.setTextViewText(R.id.present_text, "Text Test");
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder
.setContentTitle("Titel Test")
.setSmallIcon(R.drawable.ic_launcher_icon)
.setContentIntent(launchIntent)
.setOngoing(true)
.setWhen(0)
.setTicker("ticker Test")
.setContent(notificationView);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.getNotification());
</code></pre>
<p>The layout looks as follows:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/notification_icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true" />
<EditText
android:id="@+id/present_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/notification_icon"
android:gravity="center_vertical" />
</RelativeLayout>
</code></pre>
<p>I'm running android 4.3. I've tried before with NotificationCompat and get the same error.</p>
<p>Does someone has an idea?</p>
| 0 | 1,055 |
React useRef hook causing "Cannot read property '0' of undefined" error
|
<p>I'm trying to create a reference using the <code>useRef</code> hook for each items within an array of `data by doing the following:</p>
<pre><code>const markerRef = useRef(data.posts.map(React.createRef))
</code></pre>
<p>Now, <code>data</code> is fetched externally through GraphQL and it takes time to arrive, therefore, during the mounting phase, <code>data</code> is <code>undefined</code>. This causes the following error:</p>
<blockquote>
<p>TypeError: Cannot read property '0' of undefined</p>
</blockquote>
<p>I've tried the following with no success:</p>
<pre><code>const markerRef = useRef(data && data.posts.map(React.createRef))
</code></pre>
<p>How do I set up so that I can map through the <code>data</code> without causing the error?</p>
<pre><code> useEffect(() => {
handleSubmit(navigation.getParam('searchTerm', 'default value'))
}, [])
const [loadItems, { called, loading, error, data }] = useLazyQuery(GET_ITEMS)
const markerRef = useRef(data && data.posts.map(React.createRef))
const onRegionChangeComplete = newRegion => {
setRegion(newRegion)
}
const handleSubmit = () => {
loadItems({
variables: {
query: search
}
})
}
const handleShowCallout = index => {
//handle logic
}
if (called && loading) {
return (
<View style={[styles.container, styles.horizontal]}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
)
}
if (error) return <Text>Error...</Text>
return (
<View style={styles.container}>
<MapView
style={{ flex: 1 }}
region={region}
onRegionChangeComplete={onRegionChangeComplete}
>
{data && data.posts.map((marker, index) => (
<Marker
ref={markerRef.current[index]}
key={marker.id}
coordinate={{latitude: marker.latitude, longitude: marker.longitude }}
// title={marker.title}
// description={JSON.stringify(marker.price)}
>
<Callout onPress={() => handleShowCallout(index)}>
<Text>{marker.title}</Text>
<Text>{JSON.stringify(marker.price)}</Text>
</Callout>
</Marker>
))}
</MapView>
</View>
)
</code></pre>
<p>I'm using the <code>useLazyQuery</code> because I need to trigger it at different times.</p>
<p>Update:</p>
<p>I have modified the <code>useRef</code> to the following on the advise of @azundo:</p>
<pre><code>const dataRef = useRef(data);
const markerRef = useRef([]);
if (data && data !== dataRef.current) {
markerRef.current = data.posts.map(React.createRef);
dataRef.current = data
}
</code></pre>
<p>When I console.log <code>markerRef.current</code>, I get the following result:
<a href="https://i.stack.imgur.com/I1SE6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I1SE6.png" alt="enter image description here"></a></p>
<p>which is perfectly fine. However, when I attempt to map each <code>current</code> and invoke <code>showCallout()</code> to open all the callouts for each marker by doing the following:</p>
<pre><code>markerRef.current.map(ref => ref.current && ref.current.showCallout())
</code></pre>
<p>nothing gets executed.</p>
<pre><code>console.log(markerRef.current.map(ref => ref.current && ref.current.showCallout()))
</code></pre>
<p>This shows null for each array.</p>
| 0 | 1,824 |
Dynamically render view in a partial with Rails and jQuery
|
<p>In my app, I have a user profile page that has three tabs and a blank div below it. There is a default tab that is white and two other tabs that are darker and "unselected".</p>
<p>I want to make it so that the content in the div below renders a partial based on which tab is selected.</p>
<p>I already have it working to the point where jQuery allows me to click on the different tabs and it changes the colors of the tabs without a page refresh.</p>
<p>However, I am stuck on how to get the partial to render correctly. Any thoughts on this? I am stuck on how to dynamically call a partial based on which tab is selected in the jQuery and actually am not sure if I need another file to interact with this to make it work. I am relatively new to jQuery in a rails app so I am not sure if I've done everything I need to.</p>
<p>User profile page: app > views > show.html.erb</p>
<pre><code> <ul class="profile-tabs">
<%= link_to "<li class=\"tab selected\">Tab 1</li>".html_safe, userprofile_users_path, remote: true %>
<%= link_to "<li class=\"tab\">Tab 2</li>".html_safe, userprofile_users_path, remote: true %>
<%= link_to "<li class=\"tab\">Tab 3</li>".html_safe, userprofile_users_path, remote: true %>
</ul>
<div id="profile-content">
<!--content goes here -->
</div>
</code></pre>
<p>jQuery: app > assets > javascripts > userprofile.js</p>
<pre><code>$(function() {
$("li.tab").click(function(e) {
e.preventDefault();
$("li.tab").removeClass("selected");
$(this).addClass("selected");
$("#profile-content").html("<%= escape_javascript(render partial:
"How can I make this partial name be generated based on the value of the selected li?")%>");
});
});
</code></pre>
<p>Users Controller: app > controllers > users_controller.rb</p>
<pre><code>class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def userprofile
respond_to do |format|
format.js
end
end
end
</code></pre>
<p>There are three partials corresponding to the three tabs, and I need the jQuery to somehow dynamically change the partial being called based on the selected tab.</p>
<p>I'd really appreciate some help with this, or if there is another resource that can answer my question. I have not been able to find anything that directly answers what I am trying to do.</p>
<p>Update ------</p>
<p>I used the solution provided rails_has_elegance but nothing is appearing in the div I am targeting. However, I am seeing this in the rails server output, which seems like it is doing what I want:</p>
<pre><code>Started GET "/users/currentoffers" for 127.0.0.1 at 2013-03-28 21:20:01 -0500
Processing by UsersController#currentoffers as JS
Rendered users/_offers.html.erb (0.1ms)
Rendered users/currentoffers.js.erb (0.8ms)
Completed 200 OK in 4ms (Views: 3.7ms | ActiveRecord: 0.0ms)
[2013-03-28 21:20:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
</code></pre>
| 0 | 1,091 |
Problem with NTFRS - Missing Sysvol and Netlogon on a 2003 Server
|
<p>This is a problem that is affecting me. Although this description wasn´t written by me (seen at www.experts-exchange.com (1), one of the kind of sites stackoverflow was created because of) it applies 95% to the problem I´m having. Next time I won´t follow MS advice, The domain was working until I tried the suggested solution on the event log ("Enable Journal Wrap Automatic Restore"). What a mistake it was!!!.</p>
<p>Description (as seen in (1)) follows:</p>
<p>(1)
<a href="http://www.experts-exchange.com/OS/Microsoft%5fOperating%5fSystems/Server/Windows%5f2003%5fActive%5fDirectory/Q%5f22871376.html" rel="nofollow noreferrer">http://www.experts-exchange.com/OS/Microsoft%5fOperating%5fSystems/Server/Windows%5f2003%5fActive%5fDirectory/Q%5f22871376.html</a></p>
<p>---------- Cut starts here ---------- </p>
<p>I am having some apparently serious problems with a 2003 SBS server.</p>
<p>We have just started the process of putting in a second Domain Controller into this network for a project.</p>
<p>I performed the same task in a lab environment before I started on the live environment, and had no problems.</p>
<p>Firstly, we upgraded the SBS (tisserver) to 2003 R2. After that, I did the adprep to update the schema to R2.</p>
<p>I built up the 2003 R2 server (tisdr), installed DNS, joined it to the domain and did a DCPROMO.</p>
<p>This all worked fine, but I discovered errors in the File Replicaction Service event log on the new server:</p>
<hr>
<p>Event ID 13508 - Source NtFRS</p>
<hr>
<p>The File Replication Service is having trouble enabling replication from tisserver.TIS.local to TISDR for c:\windows\sysvol\domain using the DNS name tisserver.TIS.local. FRS will keep retrying.
Following are some of the reasons you would see this warning.</p>
<p>[1] FRS can not correctly resolve the DNS name tisserver.TIS.local from this computer.
[2] FRS is not running on tisserver.TIS.local.
[3] The topology information in the Active Directory for this replica has not yet replicated to all the Domain Controllers.</p>
<p>This event log message will appear once per connection, After the problem is fixed you will see another event log message indicating that the connection has been established.</p>
<p>For more information, see Help and Support Center at <a href="http://go.microsoft.com/fwlink/events.asp" rel="nofollow noreferrer">http://go.microsoft.com/fwlink/events.asp</a>.</p>
<hr>
<p>When I went and checked the SBS, I found the following error had been occurring:</p>
<hr>
<p>Eventid ID 13568 - Source NtFrs</p>
<hr>
<p>The File Replication Service has detected that the replica set "DOMAIN SYSTEM VOLUME (SYSVOL SHARE)" is in JRNL_WRAP_ERROR.</p>
<p>Replica set name is : "DOMAIN SYSTEM VOLUME (SYSVOL SHARE)"
Replica root path is : "c:\windows\sysvol\domain"
Replica root volume is : "\.\C:"
A Replica set hits JRNL_WRAP_ERROR when the record that it is trying to read from the NTFS USN journal is not found. This can occur because of one of the following reasons.</p>
<p>[1] Volume "\.\C:" has been formatted.
[2] The NTFS USN journal on volume "\.\C:" has been deleted.
[3] The NTFS USN journal on volume "\.\C:" has been truncated. Chkdsk can truncate the journal if it finds corrupt entries at the end of the journal.
[4] File Replication Service was not running on this computer for a long time.
[5] File Replication Service could not keep up with the rate of Disk IO activity on "\.\C:".
Setting the "Enable Journal Wrap Automatic Restore" registry parameter to 1 will cause the following recovery steps to be taken to automatically recover from this error state.
[1] At the first poll, which will occur in 5 minutes, this computer will be deleted from the replica set. If you do not want to wait 5 minutes, then run "net stop ntfrs" followed by "net start ntfrs" to restart the File Replication Service.
[2] At the poll following the deletion this computer will be re-added to the replica set. The re-addition will trigger a full tree sync for the replica set.</p>
<p>WARNING: During the recovery process data in the replica tree may be unavailable. You should reset the registry parameter described above to 0 to prevent automatic recovery from making the data unexpectedly unavailable if this error condition occurs again.</p>
<p>To change this registry parameter, run regedit.</p>
<p>Click on Start, Run and type regedit.</p>
<p>Expand HKEY_LOCAL_MACHINE.
Click down the key path:
"System\CurrentControlSet\Services\NtFrs\Parameters"
Double click on the value name
"Enable Journal Wrap Automatic Restore"
and update the value.</p>
<p>If the value name is not present you may add it with the New->DWORD Value function under the Edit Menu item. Type the value name exactly as shown above.</p>
<p>For more information, see Help and Support Center at <a href="http://go.microsoft.com/fwlink/events.asp" rel="nofollow noreferrer">http://go.microsoft.com/fwlink/events.asp</a>.</p>
<hr>
<p>After doing a bit of reading, it seemed like the right thing to do was a non-authoritative resotre, so I went through and created the registry key, then stopped and started the NTFRS service.</p>
<p>As expected, I got:</p>
<hr>
<p>EventID 13560 - Source NtFRS</p>
<hr>
<p>The File Replication Service is deleting this computer from the replica set "DOMAIN SYSTEM VOLUME (SYSVOL SHARE)" as an attempt to recover from the error state,
Error status = FrsErrorSuccess
At the next poll, which will occur in 5 minutes, this computer will be re-added to the replica set. The re-addition will trigger a full tree sync for the replica set.</p>
<p>For more information, see Help and Support Center at <a href="http://go.microsoft.com/fwlink/events.asp" rel="nofollow noreferrer">http://go.microsoft.com/fwlink/events.asp</a>.</p>
<hr>
<p>Exactly five minutes later, I got:</p>
<hr>
<p>EventID 13520 - Source NtFRS</p>
<hr>
<p>The File Replication Service moved the preexisting files in c:\windows\sysvol\domain to c:\windows\sysvol\domain\NtFrs_PreExisting___See_EventLog.</p>
<p>The File Replication Service may delete the files in c:\windows\sysvol\domain\NtFrs_PreExisting___See_EventLog at any time. Files can be saved from deletion by copying them out of c:\windows\sysvol\domain\NtFrs_PreExisting___See_EventLog. Copying the files into c:\windows\sysvol\domain may lead to name conflicts if the files already exist on some other replicating partner.</p>
<p>In some cases, the File Replication Service may copy a file from c:\windows\sysvol\domain\NtFrs_PreExisting___See_EventLog into c:\windows\sysvol\domain instead of replicating the file from some other replicating partner.</p>
<p>Space can be recovered at any time by deleting the files in c:\windows\sysvol\domain\NtFrs_PreExisting___See_EventLog.</p>
<p>For more information, see Help and Support Center at</p>
<hr>
<p>&</p>
<hr>
<p>EventID 13553 - Source NtFRS</p>
<hr>
<p>The File Replication Service successfully added this computer to the following replica set:
"DOMAIN SYSTEM VOLUME (SYSVOL SHARE)"</p>
<p>Information related to this event is shown below:
Computer DNS name is "tisserver.TIS.local"
Replica set member name is "TISSERVER"
Replica set root path is "c:\windows\sysvol\domain"
Replica staging directory path is "c:\windows\sysvol\staging\domain"
Replica working directory path is "c:\windows\ntfrs\jet"</p>
<p>For more information, see Help and Support Center at</p>
<hr>
<p>---------- Cut ends here ---------- </p>
<p>From this point on the responses I got start to drift from the original poster:</p>
<hr>
<p>EventID 13566 - Source NtFRS</p>
<hr>
<p>File Replication Service is scanning the data in the system volume. Computer DOMSERVER cannot become a domain controller until this process is complete. The system volume will then be shared as SYSVOL. </p>
<p>To check for the SYSVOL share, at the command prompt, type:
net share </p>
<p>When File Replication Service completes the scanning process, the SYSVOL share will appear. </p>
<p>The initialization of the system volume can take some time. The time is dependent on the amount of data in the system volume.</p>
<p>For more information, see Help and Support Center at <a href="http://go.microsoft.com/fwlink/events.asp" rel="nofollow noreferrer">http://go.microsoft.com/fwlink/events.asp</a>.</p>
<hr>
<p>I have left it for about an hour and a half now, and am not seeing any sign of a sysvol or netlogon share yet. The users are unable to log on. I don´t know where to go to from here. I´m in such desperate state that, if I had the money, I sure would pay experts-exchange (and the bad guys would win, I know :( ). Unfortunaly, I can´t do that for many reasons (not having a credit card is one of them).</p>
<p>Your help would be greatly appreciated!</p>
<p>PS: sorry for my not so good english. It´s not my mother tongue. Next time I will be better at it. :)</p>
| 0 | 2,695 |
Eclipse: Could not open the editor: No editor descriptor for id org.eclipse.jdt.ui.CompilationUnitEditor
|
<p>When I updated Eclipse using "Help -> Check for Updates" I got a problem. </p>
<p>If I try to start Eclipse, Eclipse opens but show a error message like this:</p>
<pre><code> Could not open the editor: No editor descriptor
for id org.eclipse.jdt.ui.CompilationUnitEditor
</code></pre>
<p>And inside "Details" of the error, I have the following description:</p>
<pre><code> org.eclipse.ui.PartInitException: No editor descriptor for id org.eclipse.jdt.ui.CompilationUnitEditor
at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:601)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:465)
at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:595)
at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:313)
at org.eclipse.ui.internal.presentations.PresentablePart.setVisible(PresentablePart.java:180)
at org.eclipse.ui.internal.presentations.util.PresentablePartFolder.select(PresentablePartFolder.java:270)
at org.eclipse.ui.internal.presentations.util.LeftToRightTabOrder.select(LeftToRightTabOrder.java:65)
at org.eclipse.ui.internal.presentations.util.TabbedStackPresentation.selectPart(TabbedStackPresentation.java:473)
at org.eclipse.ui.internal.PartStack.refreshPresentationSelection(PartStack.java:1245)
at org.eclipse.ui.internal.PartStack.handleDeferredEvents(PartStack.java:1213)
at org.eclipse.ui.internal.LayoutPart.deferUpdates(LayoutPart.java:400)
at org.eclipse.ui.internal.PartSashContainer.handleDeferredEvents(PartSashContainer.java:1409)
at org.eclipse.ui.internal.LayoutPart.deferUpdates(LayoutPart.java:400)
at org.eclipse.ui.internal.WorkbenchPage.handleDeferredEvents(WorkbenchPage.java:1495)
at org.eclipse.ui.internal.WorkbenchPage.deferUpdates(WorkbenchPage.java:1485)
at org.eclipse.ui.internal.WorkbenchPage.closeEditors(WorkbenchPage.java:1459)
at org.eclipse.ui.internal.WorkbenchPage.closeEditor(WorkbenchPage.java:1514)
at org.eclipse.ui.internal.EditorPane.doHide(EditorPane.java:61)
at org.eclipse.ui.internal.PartStack.close(PartStack.java:537)
at org.eclipse.ui.internal.EditorStack.close(EditorStack.java:206)
at org.eclipse.ui.internal.PartStack$1.close(PartStack.java:120)
at org.eclipse.ui.internal.presentations.util.TabbedStackPresentation$1.handleEvent(TabbedStackPresentation.java:83)
at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:269)
at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:278)
at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder.access$1(DefaultTabFolder.java:1)
at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder$1.closeButtonPressed(DefaultTabFolder.java:71)
at org.eclipse.ui.internal.presentations.PaneFolder.notifyCloseListeners(PaneFolder.java:631)
at org.eclipse.ui.internal.presentations.PaneFolder$3.close(PaneFolder.java:206)
at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1598)
at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:261)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3588)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3209)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2696)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2660)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2494)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:674)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:667)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:123)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
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:601)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.Main.main(Main.java:1386)
</code></pre>
<p>What can I do to solve this problem? I don't do anything, I just update Eclipse from their own "Check for Updates". </p>
| 0 | 1,927 |
Error: AppModule is not an NgModule
|
<p>I updated version 2.4.1 recently.</p>
<pre><code>"@angular/common": "~2.4.1",
"@angular/compiler": "~2.4.1",
"@angular/compiler-cli": "^2.4.1",
"@angular/core": "~2.4.1",
"@angular/forms": "~2.4.1",
"@angular/http": "~2.4.1",
"@angular/platform-browser": "~2.4.1",
"@angular/platform-browser-dynamic": "~2.4.1",
"@angular/router": "~3.4.1",
"angular-cli": "^1.0.0-beta.24"
</code></pre>
<p>When I used 2.0.0, it doesn't make an error, but now, it makes an error like <code>GET http://localhost:4200/null 404 (Not Found)</code>.</p>
<p>Also when I try to deploy, it makes an error like '<strong><code>AppModule is not an NgModule</code></strong>'.</p>
<p>Even though it makes an error, it's working well on local.
If anyone knows about this, please let me know.
Thank you :)</p>
<p><strong>app.module.ts</strong></p>
<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { DeliveryComponent } from './delivery/delivery.component';
import { AreaManagementComponent } from './area-management/area-management.component';
import { CountryComponent } from './area-management/country/country.component';
import { routing } from './app.routing';
import { AreaService } from "./area-management/area-management.service";
import { FDeliveryService } from "./f-delivery-setting/f-delivery.service";
import { ProvinceComponent } from './area-management/province/province.component';
import { SigninComponent } from './signin/signin.component';
import { CityComponent } from './area-management/city/city.component';
import { AreaComponent } from './area-management/area/area.component';
import { DeliveryAreaComponent } from './area-management/delivery-area/delivery-area.component';
import { FDeliverySettingComponent } from './f-delivery-setting/f-delivery-setting.component';
import { TermsComponent } from './terms/terms.component';
import { TermsListComponent } from './terms-list/terms-list.component';
import { TermsListService } from "./terms-list/terms-list.service";
import { TermsService } from "./terms/terms.service";
import { UserManagementComponent } from './user-management/user-management.component';
import { UserService} from "./user-management/user.service";
import { NavComponent } from './nav/nav.component';
import { MaterialModule } from '@angular/material';
import 'hammerjs';
import {
DialogModule,
ButtonModule,
DataTableModule,
InputTextModule,
TabViewModule,
DropdownModule,
EditorModule,
SharedModule,
AutoCompleteModule,
PanelMenuModule,
MenuModule,
ContextMenuModule,
PasswordModule,
FileUploadModule,
InputTextareaModule,
RadioButtonModule,
CalendarModule,
CheckboxModule,
ConfirmDialogModule,
ConfirmationService, InputMaskModule, BlockUIModule
} from "primeng/primeng";
import { SignupComponent } from './signin/signup.component';
import { LicenseComponent } from './license/license.component';
import { TermsShowComponent } from './terms-show/terms-show.component';
import { AuthGuardService } from "./signin/auth-guard.service";
import { AuthService } from "./signin/auth.service";
import { UserDetailComponent } from './user-detail/user-detail.component';
import { LicenseDetailComponent } from './license/license-detail/license-detail.component';
import { UserDetailService } from "./user-detail/user-detail.service";
import { LicenseService } from "./license/license.service";
import { BranchManagementComponent } from './branch-management/branch-management.component';
import { BranchService } from "./branch-management/branch.service";
import { BranchDetailComponent } from './branch-management/branch-detail/branch-detail.component';
import { InternalComponent } from './home/internal/internal.component';
import { ExternalComponent } from './home/external/external.component';
import { ClassificationComponent } from './classification/classification.component';
import { ClientComponent } from './client/client.component';
import { DmBillingComponent } from './payment-billing/dm-billing/dm-billing.component';
import { PartnerBillingComponent } from './payment-billing/partner-billing/partner-billing.component';
import { WowbillingComponent } from './payment-billing/wowbilling/wowbilling.component';
import { DailyReportingComponent } from './daily-reporting/daily-reporting.component';
import { AccountClosingComponent } from './account-closing/account-closing.component';
import { AccountingComponent } from "./accounting-balance/accounting-balance.component";
import { DeliveryService } from "./delivery/delivery.service";
import { UserAddComponent } from './user-add/user-add.component';
import { NavService } from "./nav/nav.service";
import { PartnerService } from "./shared/partner.service";
import { ClientService } from "./shared/client.service";
import { PartnerComponent } from './partner/partner.component';
import { PartnerDetailComponent } from './partner/partner-detail/partner-detail.component';
import { NewBranchComponent } from './branch-management/new-branch/new-branch.component';
import { ForgetPasswordComponent } from './signin/forget-password/forget-password.component';
import { DeliveryDetailComponent } from './delivery/delivery-detail/delivery-detail.component';
import {FileUploadService} from "./shared/file-upload.service";
import { PartnerEditComponent } from './partner/partner-edit/partner-edit.component';
import {AgmCoreModule} from "angular2-google-maps/core/core-module";
@NgModule({
declarations: [
AppComponent,
HomeComponent,
DeliveryComponent,
AreaManagementComponent,
CountryComponent,
ProvinceComponent,
SigninComponent,
CityComponent,
AreaComponent,
DeliveryAreaComponent,
FDeliverySettingComponent,
TermsComponent,
TermsListComponent,
UserManagementComponent,
NavComponent,
SignupComponent,
LicenseComponent,
TermsShowComponent,
UserDetailComponent,
LicenseDetailComponent,
BranchManagementComponent,
BranchDetailComponent,
InternalComponent,
ExternalComponent,
AccountingComponent,
ClassificationComponent,
ClientComponent,
DmBillingComponent,
PartnerBillingComponent,
WowbillingComponent,
DailyReportingComponent,
AccountClosingComponent,
UserAddComponent,
PartnerComponent,
PartnerDetailComponent,
NewBranchComponent,
ForgetPasswordComponent,
DeliveryDetailComponent,
PartnerEditComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing,
MaterialModule.forRoot(),
ReactiveFormsModule,
AgmCoreModule.forRoot({
apiKey: Key
}),
//primeNG
InputTextareaModule,
InputTextModule,
DataTableModule,
DialogModule,
DropdownModule,
ButtonModule,
TabViewModule,
EditorModule,
SharedModule,
PanelMenuModule,
MenuModule,
ContextMenuModule,
PasswordModule,
FileUploadModule,
RadioButtonModule,
CalendarModule,
CheckboxModule,
ConfirmDialogModule,
InputMaskModule
],
providers: [
AreaService,
FDeliveryService,
TermsListService,
TermsService,
UserService,
AuthGuardService,
AuthService,
UserDetailService,
LicenseService,
BranchService,
DeliveryService,
NavService,
PartnerService,
ClientService,
ConfirmationService,
FileUploadService
],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p><strong>Packages.json</strong></p>
<pre><code>{
"name": "five-delivery-admin",
"version": "0.0.0",
"license": "MIT",
"angular-cli": {},
"scripts": {
"start": "ng serve",
"lint": "tslint \"src/**/*.ts\"",
"test": "ng test",
"pree2e": "webdriver-manager update",
"e2e": "protractor"
},
"private": true,
"dependencies": {
"@angular/common": "~2.4.1",
"@angular/compiler": "~2.4.1",
"@angular/compiler-cli": "^2.4.1",
"@angular/core": "~2.4.1",
"@angular/forms": "~2.4.1",
"@angular/http": "~2.4.1",
"@angular/material": "^2.0.0-beta.0",
"@angular/platform-browser": "~2.4.1",
"@angular/platform-browser-dynamic": "~2.4.1",
"@angular/router": "~3.4.1",
"@types/moment-timezone": "^0.2.33",
"angular-cli": "^1.0.0-beta.24",
"angular2": "^2.0.0-beta.21",
"angular2-google-maps": "^0.17.0",
"bootstrap": "^3.3.7",
"bourbon": "^4.2.7",
"core-js": "^2.4.1",
"es6-promise": "^4.0.5",
"es6-shim": "^0.35.2",
"font-awesome": "^4.7.0",
"hammerjs": "^2.0.8",
"moment": "^2.17.1",
"moment-timezone": "^0.5.10",
"node-sass": "^3.13.0",
"primeng": "^1.1.0",
"pubnub-angular2": "^1.0.0-beta.7",
"quill": "^1.1.8",
"reflect-metadata": "^0.1.9",
"rxjs": "^5.0.2",
"ts-helpers": "^1.1.1",
"typescript": "^2.0.10",
"zone.js": "^0.7.4"
},
"devDependencies": {
"@types/hammerjs": "^2.0.33",
"@types/jasmine": "^2.2.30",
"@types/moment": "^2.13.0",
"@types/moment-timezone": "^0.2.33",
"@types/node": "^6.0.42",
"angular-cli": "^1.0.0-beta.24",
"bootstrap-sass": "^3.3.7",
"codelyzer": "~0.0.26",
"jasmine-core": "2.4.1",
"jasmine-spec-reporter": "2.5.0",
"karma": "1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "4.0.9",
"ts-loader": "^1.3.3",
"ts-node": "1.2.1",
"tslint": "4.2.0",
"typescript": "2.0.10"
}
}
</code></pre>
<p><strong>angular-cli.json</strong></p>
<pre><code>{
"project": {
"version": "1.0.0-beta.24",
"name": "five-delivery-admin"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": ["assets"],
"index": "index.html",
"main": "main.ts",
"test": "test.ts",
"tsconfig": "tsconfig.json",
"prefix": "app",
"mobile": false,
"styles": [
"styles.scss",
"../node_modules/hammerjs/hammer.min.js",
"../node_modules/primeng/resources/themes/omega/theme.css",
"../node_modules/primeng/resources/primeng.min.css",
"../node_modules/font-awesome/css/font-awesome.min.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"../node_modules/quill/dist/quill.core.css",
"../node_modules/quill/dist/quill.snow.css",
"../node_modules/quill/dist/quill.bubble.css"
],
"scripts": [
"../node_modules/quill/dist/quill.min.js",
"../node_modules/hammerjs/hammer.min.js"
],
"environments": {
"source": "environments/environment.ts",
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"addons": [],
"packages": [],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "scss",
"prefixInterfaces": false
}
}
</code></pre>
<p><strong>tsconfig.json</strong></p>
<pre><code>{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"lib": ["es6", "dom"],
"mapRoot": "./",
"module": "es6",
"moduleResolution": "node",
"outDir": "../dist/out-tsc",
"sourceMap": true,
"target": "es5",
"typeRoots": [
"../node_modules/@types"
]
}
}
</code></pre>
<p><strong>typings.json</strong></p>
<pre><code>{
"globalDependencies": {
"es6-collections": "registry:dt/es6-collections#0.5.1+20160316155526",
"es6-promise": "registry:dt/es6-promise#0.0.0+20160614011821"
}
}
</code></pre>
| 0 | 4,589 |
PHP : How to put and pass variable in modal URL
|
<p>So, I have a button to give a direct link to modal in same page.</p>
<p>this is the button and url</p>
<pre><code><a data-toggle="modal"
href="main_user.php?user_id=<?php echo $user['user_id']; ?>#myModal"
class="btn btn-warning">
</code></pre>
<p>( I try to echo the <code>$user_id</code> on before <code>#modal</code> ) is it right ?</p>
<p>and after I click the button, the modal will appear.
This is the modal with the form.</p>
<pre><code><form class="form-login" action="action/doEditUserStatus.php" method="post">
<div class="login-wrap">
<div class="changestatus">
<p>Banning or Activing User Status</p></div>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success active">
<input type="radio" name="options" value="1" autocomplete="off" checked> Actived
</label>
<label class="btn btn-primary">
<input type="radio" name="options" value="2" autocomplete="off"> Banned
</label>
</div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
<button class="btn btn-theme" name="modalSubmit" type="submit">Submit</button>
</div>
</form>
</code></pre>
<p>And then I try to submit the modal form, but the action cannot read the <code>$user_id</code> which I put before <code>#modal</code>.</p>
<p>UPDATE :
Table code :</p>
<p>So this is my table :</p>
<pre><code><tr class="success">
<th class="numeric">ID</th>
<th class="numeric">E-mail</th>
<th class="numeric">Name</th>
<th class="numeric">Phone</th>
<th class="numeric">Picture</th>
<th class="numeric">Status</th>
<th colspan="2" class="numeric">Action</th>
</tr>
<tr>
<td class="numeric"><?php echo $user['user_id']; ?></td>
<td class="numeric"><?php echo $user['email']; ?></td>
<td class="numeric"><?php echo $user['name']; ?></td>
<td class="numeric"><?php echo $user['phone']; ?></td>
<td class="numeric"><?php echo $user['picture']; ?></td>
<td class="numeric">
<a data-toggle="modal" href="main_user.php?user_id=<?php echo $user['user_id']; ?>#myModal" class="btn btn-warning">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>&nbsp;Change Status
</a>
</td>
</tr>
</code></pre>
<p>The main problem is :
When I click the button, then the modal will appear but it can't get the <code>$user_id</code> from that button?</p>
| 0 | 1,573 |
How to calculate subtotal and grand total in javascript?
|
<p><strong>What I need</strong>
I want to sum all to amount as the images but I can't do it </p>
<p><strong>As below code how can to total all amount after quantity multiple with unitPrice?</strong></p>
<p><strong>Here is Html element</strong></p>
<pre><code> <html>
<form>
<div>
Quantity:<input type="text" class="qty"> Unit price:<input type="text" class="unit">
Amount: <input type='text' class='amount'>
</div>
<div>
Quantity:<input type="text" class="qty"> Unit price:<input type="text" class="unit">
Amount: <input type='text' class='amount'>
</div>
<div>
Quantity:<input type="text" class="qty"> Unit price:<input type="text" class="unit">
Amount: <input type='text' class='amount'>
</div>
<div>
Quantity:<input type="text" class="qty"> Unit price:<input type="text" class="unit">
Amount: <input type='text' class='amount'>
</div>
<div>
Quantity:<input type="text" class="qty"> Unit price:<input type="text" class="unit">
Amount: <input type='text' class='amount'>
</div>
<div>
Quantity:<input type="text" class="qty"> Unit price:<input type="text" class="unit">
Amount: <input type='text' class='amount'>
</div>
Total All:<input type="text" class="result">
</form>
</html>
</code></pre>
<p><strong>Here is Javascript code</strong>
This js can only total from unit price with quantity like <strong>amount = quant*unit</strong></p>
<p><strong>And result should be Result = amount+amount1+amount2+amount3+amount4+amount5. But i can't do that</strong> </p>
<pre><code><script>
$(document).ready(function(){
$('.qty,.unit').on('change', function(){
var qty = parseFloat($('.quant').val() );
var unit = parseFloat( $('.unit_p').val());
var quant1 = parseFloat($('.quant1').val() );
var unit1 = parseFloat( $('.unit1').val());
var quant2 = parseFloat($('.quant2').val() );
var unit2 = parseFloat( $('.unit2').val());
var quant3 = parseFloat($('.quant3').val() );
var unit3 = parseFloat( $('.unit3').val());
var quant4 = parseFloat($('.quant4').val() );
var unit4 = parseFloat( $('.unit4').val());
var quant5 = parseFloat($('.quant5').val() );
var unit5 = parseFloat( $('.unit5').val());
var amount = qty * unit;
var amount1 = quant1*unit1;
var amount2 = quant2*unit2;
var amount3 = quant3*unit3;
var amount4 = quant4*unit4;
var amount5 = quant5*unit5;
var result = [];
if(isNaN(qty) || isNaN(unit)){
$('.amount').val('');
}else{
$('.amount').val(amount);
}if(isNaN(quant1)||isNaN(unit1)){
$('.amount1').val('');
}else{
$('.amount1').val(amount1);
}if(isNaN(quant2) || isNaN(unit2)){
$('.amount2').val('');
}else{
$('.amount2').val(amount2);
}if(isNaN(amount3) || isNaN(amount3)){
$('.amount3').val('');
}else{
$('.amount3').val(amount3);
}if(isNaN(quant4) || isNaN(unit4)){
$('.amount4').val('');
}else{
$('.amount4').val(amount4);
}if(isNaN(quant5)||isNaN(quant5)){
$('.amount5').val('');
}else{
$('.amount5').val(amount5);
}
});
</script>
</code></pre>
<p>I can't sum all amount for total</p>
<p>Please help</p>
<p><img src="https://i.stack.imgur.com/8Ngoo.jpg" alt="enter image description here"></p>
| 0 | 2,116 |
WCF logging, set max file size?
|
<p>Im using Microsoft Service Configuration Editor to setup diagnostics(WCF logging) and I can´t find any way to set the max file size?</p>
<p>I have found the MaxSizeOfMessageToLog but that do nothing about the file size?</p>
<p><strong>Edit 1:</strong> According to this : <a href="http://msdn.microsoft.com/en-us/library/aa395205.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa395205.aspx</a>
There should be a maxFileSizeKB at the sharedListeners level but when hitting space in the add tag I do not get the possibility to type maxFileSizeKB?</p>
<p><strong>Edit 2:</strong> When adding the maxFileSizeKB the serivce will not start anymore, instead I will get the following excetion : </p>
<p><em>'maxFileSizeKB' is not a valid configuration attribute for type 'System.Diagnostics.XmlWriterTraceListener'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Configuration.ConfigurationErrorsException: 'maxFileSizeKB' is not a valid configuration attribute for type 'System.Diagnostics.XmlWriterTraceListener'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</em></p>
<p>Edit 3 :</p>
<p>I had to download the Circular TraceListener sample and include it in my project, there is no built in fileSize limiter.</p>
<p>My config looks like this now : </p>
<pre><code><system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
<listeners>
<add name="ServiceModelMessageLoggingListener"/>
</listeners>
</source>
<source name="System.ServiceModel" switchValue="Warning,ActivityTracing"
propagateActivity="false">
<listeners>
<add name="ServiceModelTraceListener"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\My\MyRelease 0.31\Host\My.Host.Dev\web_messages.svclog"
type="Microsoft.Samples.ServiceModel.CircularTraceListener,CircularTraceListener"
name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp" maxFileSizeKB="1024">
<filter type="" />
</add>
<add initializeData="C:\My\MyRelease 0.31\Host\My.Host.Dev\web_tracelog.svclog"
type="Microsoft.Samples.ServiceModel.CircularTraceListener,CircularTraceListener"
name="ServiceModelTraceListener" traceOutputOptions="Timestamp" maxFileSizeKB="1024">
<filter type="" />
</add>
</sharedListeners>
</code></pre>
<p>This is limiting the message log file but not the trace log file?</p>
| 0 | 1,034 |
redirect to another page after submitting a form
|
<p>How can I redirect to another page after submitting a form? What code is needed to add my code?? This is my code simple.js</p>
<pre><code>import React from 'react';
import { Field, reduxForm } from 'redux-form';
const SimpleForm = props => {
const { handleSubmit, pristine, reset, submitting } = props;
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<div>
<Field
name="firstName"
component="input"
type="text"
placeholder="First Name"
required
/>
</div>
</div>
<div>
<label>Last Name</label>
<div>
<Field
name="lastName"
component="input"
type="text"
placeholder="Last Name"
required
/>
</div>
</div>
<div>
<label>Email</label>
<div>
<Field
name="email"
component="input"
type="email"
placeholder="Email"
required
/>
</div>
</div>
<div>
<label>Sex</label>
<div>
<label>
<Field name="sex" component="input" type="radio" value="male" />
{' '}
Male
</label>
<label>
<Field name="sex" component="input" type="radio" value="female" />
{' '}
Female
</label>
</div>
</div>
<div>
<label>Favorite Color</label>
<div>
<Field name="favoriteColor" component="select" >
<option />
<option value="ff0000">Red</option>
<option value="00ff00">Green</option>
<option value="0000ff">Blue</option>
</Field>
</div>
</div>
<div>
<label htmlFor="employed">Employed</label>
<div>
<Field
name="employed"
id="employed"
component="input"
type="checkbox"
/>
</div>
</div>
<div>
<label>Notes</label>
<div>
<Field name="notes" component="textarea" required />
</div>
</div>
<div>
<button type="submit" disabled={pristine || submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
);
};
export default reduxForm({
form: 'simple', // a unique identifier for this form
})(SimpleForm);
</code></pre>
<p>This is the simple form , I want to direct to a login page called asyncValidateform.js.. HERE IS THAT PAGE..</p>
<pre><code>import React from 'react';
import { Field, reduxForm } from 'redux-form';
import validate from './validate';
import asyncValidate from './asyncValidate';
const renderField = (
{ input, label, type, meta: { asyncValidating, touched, error } },
) => (
<div>
<label>{label}</label>
<div className={asyncValidating ? 'async-validating' : ''}>
<input {...input} type={type} placeholder={label} />
{touched && error && <span>{error}</span>}
</div>
</div>
);
const AsyncValidationForm = props => {
const { handleSubmit, pristine, reset, submitting } = props;
return (
<form onSubmit={handleSubmit}>
<Field
name="username"
type="text"
component={renderField}
label="Username"
/>
<Field
name="password"
type="password"
component={renderField}
label="Password"
/>
<Field
name="confirmpassword"
type="password"
component={renderField}
label="Confirm Password"
/>
<div>
<button type="submit" disabled={submitting}>Sign Up</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
);
};
export default reduxForm({
form: 'asyncValidation', // a unique identifier for this form
validate,
asyncValidate,
asyncBlurFields: ['username'],
})(AsyncValidationForm);
</code></pre>
<p>& this is my validate page</p>
<pre><code>const validate = values => {
const errors = {};
if (!values.username) {
errors.username = 'Required';
}
if (!values.password) {
errors.password = 'Required';
}
if (!values.confirmpassword ) {
errors.confirmpassword = 'Required' ;
}
else if (values.confirmpassword !== values.password) {
errors.confirmpassword = 'Password mismatched' ;
}
return errors;
};
export default validate;
</code></pre>
<p>index.js page</p>
<pre><code>import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Values } from "redux-form-website-template";
import store from "./store";
import showResults from "./showResults";
import SimpleForm from "./SimpleForm";
const rootEl = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<div style={{ padding: 15 }}>
<h2>Simple Form</h2>
<SimpleForm onSubmit={showResults} />
<Values form="simple" />
</div>
</Provider>,
rootEl
);
</code></pre>
<p>What all changes need to make in my code??I want to first enter into the simple.js page after entering details and by clicking the submit the page must redirect to asynValidateForm.js page.. Please help me to sort out this problem..
Thank you ...</p>
| 0 | 2,898 |
WebGL Unavailable, GPU Process unable to boot
|
<p>I'm running Chrome 54.0.2840.87 on Windows 10. I have two GPUs: an Intel(R) HD Graphics 520, and a AMD Radeon R5 M335.</p>
<p>Up until a couple of weeks ago, WebGL was running just fine in chrome. Now, after not having changed any settings anywhere, WebGL is no longer available.</p>
<p>When trying to run a chrome experiment for example, I get a message saying that my graphics card does not seem to support WebGL. I know my graphics cards work fine (they have been updated with the latest drivers), plus WebGL runs perfectly in firefox. I know my GPUs have not been blacklisted (on either browser).</p>
<p>On <code>chrome:gpu</code>, I am told that WebGL is unavailable, and that the GPU process was unable to boot. When checking <code>chrome:flags</code> enabling or disabling WebGL no longer seems to be an option.</p>
<p>Enabling/disabling anything else that involves WebGL has not made any difference. Is there something else that can be done to get it working again? At what level is the issue? (The issue persists on Chrome Canary.) I am not the most technologically savvy person, but I've had no luck finding answers anywhere else.</p>
<p>The following is what I see on my <code>chrome:gpu</code> page:</p>
<p><strong>Graphics Feature Status</strong></p>
<blockquote>
<p>Canvas: Software only, hardware acceleration unavailable</p>
<p>Flash: Software only, hardware acceleration unavailable</p>
<p>Flash Stage3D: Software only, hardware acceleration unavailable</p>
<p>Flash Stage3D Baseline profile: Software only, hardware acceleration
unavailable</p>
<p>Compositing: Software only, hardware acceleration unavailable</p>
<p>Multiple Raster Threads: Unavailable</p>
<p>Native GpuMemoryBuffers: Software only. Hardware acceleration disabled</p>
<p>Rasterization: Software only, hardware acceleration unavailable</p>
<p>Video Decode: Software only, hardware acceleration unavailable</p>
<p>Video Encode: Software only, hardware acceleration unavailable</p>
<p>VPx Video Decode: Software only, hardware acceleration unavailable</p>
<p>WebGL: Unavailable</p>
</blockquote>
<p><strong>Driver Bug Workarounds</strong></p>
<blockquote>
<p>clear_uniforms_before_first_program_use</p>
<p>disable_d3d11</p>
<p>disable_discard_framebuffer</p>
<p>disable_dxgi_zero_copy_video</p>
<p>disable_nv12_dxgi_video</p>
<p>disable_framebuffer_cmaa</p>
<p>exit_on_context_lost</p>
<p>scalarize_vec_and_mat_constructor_args</p>
</blockquote>
<p><strong>Problems Detected</strong></p>
<blockquote>
<p>GPU process was unable to boot: GPU process launch failed.</p>
<p>Disabled Features: all</p>
<p>Some drivers are unable to reset the D3D device in the GPU process
sandbox</p>
<p>Applied Workarounds: exit_on_context_lost</p>
<p>Clear uniforms before first program use on all platforms: 124764,
349137</p>
<p>Applied Workarounds: clear_uniforms_before_first_program_use</p>
<p>Always rewrite vec/mat constructors to be consistent: 398694</p>
<p>Applied Workarounds: scalarize_vec_and_mat_constructor_args</p>
<p>Disable Direct3D11 on systems with AMD switchable graphics: 451420</p>
<p>Applied Workarounds: disable_d3d11</p>
<p>Framebuffer discarding can hurt performance on non-tilers: 570897</p>
<p>Applied Workarounds: disable_discard_framebuffer</p>
<p>NV12 DXGI video hangs or displays incorrect colors on AMD drivers:
623029, 644293</p>
<p>Applied Workarounds: disable_dxgi_zero_copy_video,
disable_nv12_dxgi_video</p>
<p>Limited enabling of Chromium GL_INTEL_framebuffer_CMAA: 535198</p>
<p>Applied Workarounds: disable_framebuffer_cmaa</p>
<p>Native GpuMemoryBuffers have been disabled, either via about:flags or
command line.</p>
<p>Disabled Features: native_gpu_memory_buffers</p>
</blockquote>
<p><strong>Version Information</strong></p>
<blockquote>
<p>Data exported 11/7/2016, 2:09:57 PM</p>
<p>Chrome version Chrome/54.0.2840.87</p>
<p>Operating system Windows NT 10.0.14393</p>
<p>Software rendering list version 11.12</p>
<p>Driver bug list version 9.00</p>
<p>ANGLE commit id 905fbdea9ef0</p>
<p>2D graphics backend Skia/54 a21f10dd8b19c6cb47d07d94d0a0525c16461969</p>
<p>Command Line Args Files (x86)\Google\Chrome\Application\chrome.exe"
--flag-</p>
<p>switches-begin --enable-gpu-rasterization --enable-unsafe-es3-apis
--enable-</p>
<p>webgl-draft-extensions --flag-switches-end</p>
<p>Driver Information</p>
<p>Initialization time 0</p>
<p>In-process GPU true</p>
<p>Sandboxed false</p>
<p>GPU0 VENDOR = 0x1002, DEVICE= 0x6660</p>
<p>GPU1 VENDOR = 0x8086, DEVICE= 0x1916</p>
<p>Optimus false</p>
<p>AMD switchable true</p>
<p>Desktop compositing Aero Glass</p>
<p>Diagonal Monitor Size of \.\DISPLAY1 15.5"</p>
<p>Driver vendor Advanced Micro Devices, Inc.</p>
<p>Driver version 16.200.2001.0</p>
<p>Driver date 6-16-2016</p>
<p>Pixel shader version </p>
<p>Vertex shader version </p>
<p>Max. MSAA samples </p>
<p>Machine model name </p>
<p>Machine model version </p>
<p>GL_VENDOR </p>
<p>GL_RENDERER </p>
<p>GL_VERSION </p>
<p>GL_EXTENSIONS </p>
<p>Disabled Extensions </p>
<p>Window system binding vendor </p>
<p>Window system binding version </p>
<p>Window system binding extensions </p>
<p>Direct rendering Yes</p>
<p>Reset notification strategy 0x0000</p>
<p>GPU process crash count 0</p>
<p>Compositor Information</p>
<p>Tile Update Mode One-copy</p>
<p>Partial Raster Enabled</p>
<p>GpuMemoryBuffers Status</p>
<p>ATC Software only</p>
<p>ATCIA Software only</p>
<p>DXT1 Software only</p>
<p>DXT5 Software only</p>
<p>ETC1 Software only</p>
<p>R_8 Software only</p>
<p>BGR_565 Software only</p>
<p>RGBA_4444 Software only</p>
<p>RGBX_8888 Software only</p>
<p>RGBA_8888 Software only</p>
<p>BGRX_8888 Software only</p>
<p>BGRA_8888 Software only</p>
<p>YVU_420 Software only</p>
<p>YUV_420_BIPLANAR Software only</p>
<p>UYVY_422 Software only</p>
<p>Diagnostics
... loading ...</p>
</blockquote>
<p><strong>Log Messages</strong></p>
<pre><code>[1268:3756:1107/133435:ERROR:gl_surface_egl.cc(252)] : No suitable EGL configs found.
[1268:3756:1107/133435:ERROR:gl_surface_egl.cc(1012)] : eglCreatePbufferSurface failed with error EGL_BAD_CONFIG
[1268:3756:1107/133435:ERROR:gpu_info_collector.cc(35)] : gl::GLContext::CreateOffscreenGLSurface failed
[1268:3756:1107/133435:ERROR:gpu_info_collector.cc(108)] : Could not create surface for info collection.
[1268:3756:1107/133435:ERROR:gpu_main.cc(506)] : gpu::CollectGraphicsInfo failed (fatal).
GpuProcessHostUIShim: The GPU process exited normally. Everything is okay.
</code></pre>
| 0 | 2,750 |
how to get id of selected item in autocompletetextview in android
|
<p>I am retrieving values from server for autocompletetextview, I am getting the list of user names along with their user ids,
now what I want is when i select any username from list I want to get user id of that username.</p>
<p>Please have look at my code:</p>
<p><strong>SearchFriendsAdapter.java</strong></p>
<pre><code>public class SearchFriendsAdapter extends ArrayAdapter<String> {
private ArrayList<SearchFriends> items;
public static SearchFriends searchFriends;
public static ArrayList<String> friends_id;
boolean iNetAvailable;
Context context = getContext();
public SearchFriendsAdapter(Activity context, String nameFilter) {
super(context, R.layout.row_search_friend);
items = new ArrayList<SearchFriends>();
}
@Override
public int getCount() {
return items.size();
}
@Override
public String getItem(int index) {
return items.get(index).getFriend_name();
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row_search_friend, null);
}
searchFriends = items.get(position);
if (searchFriends != null) {
TextView tv_friend_name = (TextView) v.findViewById(R.id.search_friend_txt_friend_name);
TextView tv_friend_email = (TextView) v.findViewById(R.id.search_friend_txt_friend_email);
SimpleDraweeView iv_friend_pic = (SimpleDraweeView)v.findViewById(R.id.search_friend_img_friend_pic);
tv_friend_name.setText(searchFriends.getFriend_name());
tv_friend_email.setText(searchFriends.getFriend_email_id());
iv_friend_pic.setImageURI(Uri.parse(searchFriends.getFriend_profile_pic()));
}
return v;
}
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
iNetAvailable = Utility.isNetworkAvaliable(context);
SearchFriendsAsyncTask sf = new SearchFriendsAsyncTask();
if (constraint != null) {
List<SearchFriends> new_suggestions = sf.getParseJsonWCF(context, constraint.toString());
items.clear();
items.addAll(new_suggestions);
filterResults.values = items;
filterResults.count = items.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
</code></pre>
<p><strong>SearchFriendsAsyncTask.java</strong> </p>
<pre><code> public class SearchFriendsAsyncTask {
public SearchFriendsAsyncTask() {
super();
}
public List<SearchFriends> getParseJsonWCF(Context mContext, String sName){
List<SearchFriends> ListData = new ArrayList<SearchFriends>();
SearchFriendsModel searchFriendsModel = null;
String webUrl = Constant.URL_SEARCH_FRIEND;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(Constant.USER_ID,
Utility.getAppPrefString(mContext ,Constant.USER_ID)));
nameValuePairs
.add(new BasicNameValuePair("name", sName));
String response = Utility.postRequest(webUrl, nameValuePairs);
JSONObject jObject = new JSONObject(response);
Log.v("SEARCH FRIENDS RESPONSE : ", jObject.toString());
searchFriendsModel = (SearchFriendsModel) new Gson().fromJson(
jObject.toString(), SearchFriendsModel.class);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return searchFriendsModel.getFriends();
}
}
</code></pre>
<p><strong>SearchModel.java</strong> </p>
<pre><code>public class SearchFriends {
String friend_user_id;
String friend_name;
String friend_email_id;
String friend_profile_pic;
public SearchFriends(String friend_user_id, String friend_name,
String friend_email_id, String friend_profile_pic) {
super();
this.friend_user_id = friend_user_id;
this.friend_name = friend_name;
this.friend_email_id = friend_email_id;
this.friend_profile_pic = friend_profile_pic;
}
public String getFriend_user_id() {
return friend_user_id;
}
public void setFriend_user_id(String friend_user_id) {
this.friend_user_id = friend_user_id;
}
public String getFriend_name() {
return friend_name;
}
public void setFriend_name(String friend_name) {
this.friend_name = friend_name;
}
public String getFriend_email_id() {
return friend_email_id;
}
public void setFriend_email_id(String friend_email_id) {
this.friend_email_id = friend_email_id;
}
public String getFriend_profile_pic() {
return friend_profile_pic;
}
public void setFriend_profile_pic(String friend_profile_pic) {
this.friend_profile_pic = friend_profile_pic;
}
}
</code></pre>
<p><strong>SearchFriendsModel.java</strong> </p>
<pre><code>public class SearchFriendsModel {
private String response;
private String message;
private List<SearchFriends> friends;
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<SearchFriends> getFriends() {
return friends;
}
public void setFriends(List<SearchFriends> friends) {
this.friends = friends;
}
}
</code></pre>
<p>Here i am setting the adapter </p>
<pre><code>et_search.setAdapter(new SearchFriendsAdapter(this, et_search.getText().toString()));
et_search.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
SearchFriendsAdapter adapter = ((SearchFriendsAdapter)
et_search.getAdapter());
String friend_id = ((SearchFriends)adapter
.getItem(position)).getFriend_user_id();
}
});
</code></pre>
<p>while I am trying to get user_id as above it gives me error "Cannot cast from String to SearchFriends"</p>
<p>Please help me to achieve what I want.
Thanks in advance.</p>
| 0 | 2,684 |
The module has not been deployed [netbeans+glassfish]
|
<p>i am developping a project base on J2EE EJB JSF, database is MYsql, the project works very well last week. but today, it can't be deployed when i run it. here are some exception:</p>
<pre><code> Initial deploying ECOM to C:\Users\John624\Documents\NetBeansProjects\PromoCoupon\ECOM\dist\gfdeploy\ECOM
Completed initial distribution of ECOM
Initializing...
invalid header field name: Exception Description
C:\Users\John624\Documents\NetBeansProjects\PromoCoupon\ECOM\nbproject\build-impl.xml:307: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 5 seconds)
</code></pre>
<p><strong>Glassfish:</strong></p>
<pre><code> <code> SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
SEVERE: Exception while invoking class org.glassfish.javaee.full.deployment.EarDeployer prepare method
SEVERE: org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:180)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:431)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:724)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:1950)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1941)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:322)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:199)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:107)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922)
at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:307)
at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:88)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:153)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:150)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:230)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:239)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:265)
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:150)
... 35 more
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:230)
... 53 more
Caused by: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.exceptions.ValidationException.errorProcessingNamedQuery(ValidationException.java:824)
at org.
SEVERE: Exception while preparing the app
SEVERE: eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.process(NamedQueryMetadata.java:194)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processQueries(MetadataProject.java:1628)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.addNamedQueries(MetadataProcessor.java:148)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1894)
... 51 more
Caused by: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:626)
at org.eclipse.persistence.jpa.jpql.parser.RangeVariableDeclaration.accept(RangeVariableDeclaration.java:98)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:577)
at org.eclipse.persistence.jpa.jpql.parser.IdentificationVariableDeclaration.accept(IdentificationVariableDeclaration.java:71)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:566)
at org.eclipse.persistence.jpa.jpql.parser.FromClause.accept(FromClause.java:48)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver.populateImp(DeclarationResolver.java:417)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver.populate(DeclarationResolver.java:407)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper$DescriptorCollector.collectDescriptors(JPQLQueryHelper.java:179)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper$DescriptorCollector.visit(JPQLQueryHelper.java:204)
at org.eclipse.persistence.jpa.jpql.parser.FromClause.accept(FromClause.java:48)
at org.eclipse.persistence.jpa.jpql.parser.AbstractSelectStatement.acceptChildren(AbstractSelectStatement.java:93)
at org.eclipse.persistence.jpa.jpql.parser.SelectStatement.acceptChildren(SelectStatement.java:110)
at org.eclipse.persistence.jpa.jpql.parser.AbstractTraverseChildrenVisitor.visit(AbstractTraverseChildrenVisitor.java:32)
at org.eclipse.persistence.jpa.jpql.parser.AnonymousExpressionVisitor.visit(AnonymousExpressionVisitor.java:470)
at org.eclipse.persistence.jpa.jpql.parser.SelectStatement.accept(SelectStatement.java:102)
at org.eclipse.persistence.jpa.jpql.parser.JPQLExpression.acceptChildren(JPQLExpression.java:143)
at org.eclipse.persistence.jpa.jpql.parser.AbstractTraverseChildrenVisitor.visit(AbstractTraverseChildrenVisitor.java:32)
at org.eclipse.persistence.jpa.jpql.parser.AnonymousExpressionVisitor.visit(AnonymousExpressionVisitor.java:302)
at org.eclipse.persistence.jpa.jpql.parser.JPQLExpression.accept(JPQLExpression.java:136)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper.getClassDescriptors(JPQLQueryHelper.java:87)
at org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.addJPAQuery(NamedQueryMetadata.java:105)
at org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.process(NamedQueryMetadata.java:192)
... 54 more
<code>
</code></pre>
<p><strong>entity bean</strong></p>
<pre><code>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author John624
*/
@Entity
@Table(name = "Adresse")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Adresse.maxId", query = "SELECT max(idAdresse) FROM Adresse"),
@NamedQuery(name = "Adresse.findAll", query = "SELECT a FROM Adresse a"),
@NamedQuery(name = "Adresse.findByIdAdresse", query = "SELECT a FROM Adresse a WHERE a.idAdresse = :idAdresse"),
@NamedQuery(name = "Adresse.findByNumEtRue", query = "SELECT a FROM Adresse a WHERE a.numEtRue = :numEtRue"),
@NamedQuery(name = "Adresse.findByComple", query = "SELECT a FROM Adresse a WHERE a.comple = :comple"),
@NamedQuery(name = "Adresse.findByCodePostale", query = "SELECT a FROM Adresse a WHERE a.codePostale = :codePostale"),
@NamedQuery(name = "Adresse.findByVille", query = "SELECT a FROM Adresse a WHERE a.ville = :ville"),
@NamedQuery(name = "Adresse.findByPays", query = "SELECT a FROM Adresse a WHERE a.pays = :pays"),
@NamedQuery(name = "Adresse.findByDateModif", query = "SELECT a FROM Adresse a WHERE a.dateModif = :dateModif")})
public class Adresse implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "idAdresse")
private Long idAdresse;
@Size(max = 100)
@Column(name = "numEtRue")
private String numEtRue;
@Size(max = 100)
@Column(name = "comple")
private String comple;
@Size(max = 5)
@Column(name = "codePostale")
private String codePostale;
@Size(max = 35)
@Column(name = "ville")
private String ville;
@Size(max = 35)
@Column(name = "pays")
private String pays;
@Column(name = "dateModif")
@Temporal(TemporalType.DATE)
private Date dateModif;
@OneToMany(mappedBy = "adrU")
private Collection<Utilisateur> utilisateurCollection;
@OneToMany(mappedBy = "adrRecep")
private Collection<Livraison> livraisonCollection;
@OneToMany(mappedBy = "adrE")
private Collection<Entreprise> entrepriseCollection;
public Adresse() {
}
public Adresse(Long idAdresse) {
this.idAdresse = idAdresse;
}
public Long getIdAdresse() {
return idAdresse;
}
public void setIdAdresse(Long idAdresse) {
this.idAdresse = idAdresse;
}
public String getNumEtRue() {
return numEtRue;
}
public void setNumEtRue(String numEtRue) {
this.numEtRue = numEtRue;
}
public String getComple() {
return comple;
}
public void setComple(String comple) {
this.comple = comple;
}
public String getCodePostale() {
return codePostale;
}
public void setCodePostale(String codePostale) {
this.codePostale = codePostale;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getPays() {
return pays;
}
public void setPays(String pays) {
this.pays = pays;
}
public Date getDateModif() {
return dateModif;
}
public void setDateModif(Date dateModif) {
this.dateModif = dateModif;
}
@XmlTransient
public Collection<Utilisateur> getUtilisateurCollection() {
return utilisateurCollection;
}
public void setUtilisateurCollection(Collection<Utilisateur> utilisateurCollection) {
this.utilisateurCollection = utilisateurCollection;
}
@XmlTransient
public Collection<Livraison> getLivraisonCollection() {
return livraisonCollection;
}
public void setLivraisonCollection(Collection<Livraison> livraisonCollection) {
this.livraisonCollection = livraisonCollection;
}
@XmlTransient
public Collection<Entreprise> getEntrepriseCollection() {
return entrepriseCollection;
}
public void setEntrepriseCollection(Collection<Entreprise> entrepriseCollection) {
this.entrepriseCollection = entrepriseCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idAdresse != null ? idAdresse.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Adresse)) {
return false;
}
Adresse other = (Adresse) object;
if ((this.idAdresse == null && other.idAdresse != null) || (this.idAdresse != null && !this.idAdresse.equals(other.idAdresse))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entities.Adresse[ idAdresse=" + idAdresse + " ]";
}
}
</code></pre>
<p><strong>session bean</strong></p>
<p>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package session;</p>
<pre><code>import entities.Adresse;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author John624
*/
@Stateless
@LocalBean
public class AdresseManager {
@PersistenceContext(unitName = "ECOM-ejbPU")
private EntityManager em;
public List<Adresse> getAllAdresses() {
Query query=em.createNamedQuery("Adresse.findAll");
return query.getResultList();
}
public Adresse update(Adresse adresse) {
return em.merge(adresse);
}
public void persist(Object object) {
em.persist(object);
}
public Long nextId(){
Query query = em.createNamedQuery("Adresse.maxId");
long res;
res = query.getResultList().indexOf(0)+1;
return res;
}
}
</code></pre>
<p><strong>JSF managedbean</strong></p>
<pre><code>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package managedbeans;
import entities.Adresse;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import session.AdresseManager;
/**
*
* @author John624
*/
@Named(value="adresseMBean")
@SessionScoped
public class AdresseMBean implements Serializable{
private List<Adresse> adresses;
private Adresse adresse;
@EJB
private AdresseManager adresseManager;
public AdresseMBean() {
adresse=new Adresse();
adresseManager = new AdresseManager();
}
/**
* returns customer list for display in a datatable DataTable
* @return
*/
public List<Adresse> getAdresses() {
if((adresses == null) || (adresses.isEmpty()))
adresses = adresseManager.getAllAdresses();
return adresseManager.getAllAdresses();
}
// public void refresh() {
// tousLesComptes = compteBancaireFacade.findAll();
// }
/**
* returns details of a customer. Useful for displaying in a form a customer's details
* @return
*/
public Adresse getDetails() {
return adresse;
}
/**
* Action handler - Called when a line in the table is clicked
* @param adresse
* @return
*/
public String showDetails(Adresse adresse) {
this.adresse = adresse;
return "AdresseDetails"; // will display CustomerDetails.xml JSF page
}
/**
* Action handler - update the customer model in the database.
* called when one press the update button in the form
* @return
*/
public String update() {
System.out.println("###UPDATE###");
adresse = adresseManager.update(adresse);
return "AdresseList"; // will display the customer list in a table
}
/**
* Action handler - returns to the list of customers in the table
*/
public String list() {
System.out.println("###LIST###");
return "AdresseList";
}
public void update(Adresse adrU) {
System.out.println("###UPDATE###");
adresseManager.update(adrU);
}
}
</code></pre>
<p>Thanks in advance.</p>
| 0 | 8,013 |
How do I find out how macPorts stole my port:80?
|
<p>I had MAMP installed (and working fine) then I tried to install mongoDB through macPorts. macports then began installing a bunch of dependencies. after that, <a href="http://localhost" rel="noreferrer">http://localhost</a> started giving an "It Works!" screen. after rebooting to see if it might fix it, I found that I could not start my MAMP server. console said this:</p>
<pre><code>9/13/10 1:20:54 PM [0x0-0x12012].de.appsolute.MAMP[133] (48)Address already in use: make_sock: could not bind to address [::]:80
</code></pre>
<p>I know that macPorts did something stupid to mess with me. how can I find out what it installed thats stealing port:80?</p>
<p>here's some command I've tried: (:80 didn't work, so I just used 80)</p>
<pre><code>$ sudo netstat -an | grep 80
Password:
tcp46 0 0 *.80 *.* LISTEN
udp6 0 0 fe80::21e:52ff:f.123 *.*
udp6 0 0 fe80::1%lo0.123 *.*
</code></pre>
<p>and:</p>
<pre><code>$ lsof -i :80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
firefox-b 451 biting_duck 39u IPv4 0x0ab806b0 0t0 TCP 192.168.0.198:49515->stackoverflow.com:http (ESTABLISHED)
firefox-b 451 biting_duck 40u IPv4 0x0ab87ec8 0t0 TCP 192.168.0.198:49517->sstatic.net:http (ESTABLISHED)
firefox-b 451 biting_duck 41u IPv4 0x0ab88aec 0t0 TCP 192.168.0.198:49516->pz-in-f95.1e100.net:http (ESTABLISHED)
firefox-b 451 biting_duck 42u IPv4 0x0ab97334 0t0 TCP 192.168.0.198:49518->sstatic.net:http (ESTABLISHED)
firefox-b 451 biting_duck 47u IPv4 0x0ab87abc 0t0 TCP 192.168.0.198:49519->sstatic.net:http (ESTABLISHED)
firefox-b 451 biting_duck 48u IPv4 0x0ab886e0 0t0 TCP 192.168.0.198:49520->sstatic.net:http (ESTABLISHED)
firefox-b 451 biting_duck 50u IPv4 0x0ab89b1c 0t0 TCP 192.168.0.198:49521->sstatic.net:http (ESTABLISHED)
firefox-b 451 biting_duck 51u IPv4 0x0ab86680 0t0 TCP 192.168.0.198:49522->peak-colo-196-216.peak.org:http (ESTABLISHED)
firefox-b 451 biting_duck 54u IPv4 0x0ab81ef8 0t0 TCP 192.168.0.198:49523->gravatar.com:http (ESTABLISHED)
firefox-b 451 biting_duck 55u IPv4 0x0ab82710 0t0 TCP 192.168.0.198:49524->gravatar.com:http (ESTABLISHED)
firefox-b 451 biting_duck 56u IPv4 0x0ab8a334 0t0 TCP 192.168.0.198:49526->64.34.80.176:http (ESTABLISHED)
firefox-b 451 biting_duck 57u IPv4 0x0ab812d4 0t0 TCP 192.168.0.198:49525->pv-in-f101.1e100.net:http (ESTABLISHED)
</code></pre>
| 0 | 1,255 |
IFrame OnReadyStateChange function
|
<p>I have an asp.webforms application and on page a i have a hidden div with progressbar and iframe. To iframe i try loaded form from another application on same domain.</p>
<pre><code><div id="pagePreview" style="display: none;">
<div class="progressBarWrapper" id="waitDialog" style="opacity:1;filter:alpha(opacity=100);display:none;">
<div class="progressBarDetail" style="margin-top:25%;">
<asp:Image ID="imgLoading" runat="server" ImageUrl="~/Images/wait.gif" />
</div>
</div>
<iframe id="previewContent" onreadystatechange="iframeLoaded(this);"></iframe>
</div>
</code></pre>
<p>On a click event i call a function to show this div in jqueryUI dialog and i Want show progressbar until the page in Iframe is not loaded.</p>
<pre><code>var isClickedForDialog = false;
function iframeLoaded(args) {
if (args.readyState == "complete" && isClickedForDialog) {
var pagePreview = $('#pagePreview'); // dialog
var waitDialog = $('#waitDialog'); // progress
waitDialog.hide();
isClickedForDialog = false;
}
}
function showModalWindow(url, hideCloseButton) {
isClickedForDialog = true;
var previewContent = $('#previewContent'); // Iframe
var pagePreview = $('#pagePreview'); // dialog
var waitDialog = $('#waitDialog'); // progresss
waitDialog.show();
previewContent.attr('src', url);
pagePreview.dialog(
{
draggable: false,
resizable: false,
height: 764,
width: 1020,
modal: true,
close: function (event, ui) {
previewContent.attr('src', '');
},
open: function (event, ui) {
if (hideCloseButton) {
$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
}
}
});
}
</code></pre>
<p>In IE everything works fine. The dialog box and progressbar displays and when the URL is loaded in an iframe, progressbar disappears and i see only webforms in IFrame.</p>
<p>But in FireFox and Chrome this does not work.</p>
<p>The browser ignores the onreadystatechange event. I tried to handle an event as following:</p>
<pre><code>$('#previewContent').bind('onreadystatechange', iframeLoaded, false);
$('#previewContent').on('onreadystatechange', iframeLoaded);
</code></pre>
<p>but without success.</p>
<p>know how to solve this? thanks</p>
| 0 | 1,366 |
Django File Upload
|
<p>Here is the code in views:</p>
<pre><code>def index(request):
if request.method == 'POST':
a=request.POST
# logging.debug(a["title"])
# logging.debug(a["file"])
#form = UploadFileForm()
form = UploadFileForm(request.POST, request.FILES)
#handle_uploaded_file(request.FILES['file'])
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/')
else:
form = UploadFileForm()
return render('upload.html', {'form': form})
def handle_uploaded_file(file):
# logging.debug("upload_here")
if file:
destination = open('/tmp/'+file.name, 'wb+')
#destination = open('/tmp', 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()
</code></pre>
<p>Here is the code in models:</p>
<pre><code>class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(type="file")
</code></pre>
<p>Here is the code in upload.html:</p>
<pre><code>{% block upload %}
<form enctype="multipart/form-data" method="post" action="/upload/">
{% csrf_token %}
<table>
<tr><td>
<input type="file" value="title" name="title" id="title" /><br />
<input type="submit" value="Submit" id="Save"/>
</td></tr>
</table>
</form>
{% endblock %}
</code></pre>
<h1>After I select a file, then press the submit button, an error appears:</h1>
<p>AttributeError at /upload/</p>
<p>'WSGIRequest' object has no attribute 'chunks'</p>
<p>Request Method: POST
Request URL: <a href="http://www.mywebsite.com/upload/">http://www.mywebsite.com/upload/</a>
Django Version: 1.3
Exception Type: AttributeError
Exception Value: </p>
<p>'WSGIRequest' object has no attribute 'chunks'</p>
<h1>Exception Location: /usr/src/wpcms/views.py in handle_uploaded_file, line 63</h1>
<p>Any ideas what I am doing wrong here? Am I forgetting a settings line? Or, an import line?
Thank you.</p>
<p>settings.py is:</p>
<pre><code>TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware',
'django.middleware.doc.XViewMiddleware',
'django_authopenid.middleware.OpenIDMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'cms.context_processors.media',
'django_authopenid.context_processors.authopenid',
)
CMS_TEMPLATES = (
# ('basic.html', 'Basic Template'),
# ('template_1.html', 'Template One'),
# ('template_2.html', 'Template Two'),
('home.html', gettext('Default')),
('about.html', gettext('About')),
# ('blog.html', gettext('blog')),
('contact.html', gettext('Contact')),
)
ROOT_URLCONF = 'urls'
CMS_APPLICATIONS_URLS = (
('cmsplugin_news.urls', 'News'),
)
CMS_NAVIGATION_EXTENDERS = (
('cmsplugin_news.navigation.get_nodes', 'News navigation'),
)
THUMBNAIL_PROCESSORS = (
'easy_thumbnails.processors.colorspace',
'easy_thumbnails.processors.autocrop',
#'easy_thumbnails.processors.scale_and_crop',
'filer.thumbnail_processors.scale_and_crop_with_subject_location',
'easy_thumbnails.processors.filters',
)
CMS_MODERATOR = False
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.comments',
'registration',
'django_authopenid',
'cms',
'menus',
'mptt',
'appmedia',
'south',
'cms.plugins.text',
'cms.plugins.picture',
'cms.plugins.link',
'cms.plugins.file',
'easy_thumbnails',
'filer',
'cmsplugin_filer_file',
'cmsplugin_filer_folder',
'cmsplugin_filer_image',
'cmsplugin_filer_teaser',
'cmsplugin_filer_video',
'cms.plugins.snippet',
'cms.plugins.googlemap',
'publisher',
'reversion',
'cms.plugins.teaser',
'cms.plugins.video',
'cms.plugins.twitter',
'cmsplugin_facebook',
'cmsplugin_news',
'cmsplugin_comments',
'captcha',
)
</code></pre>
| 0 | 2,134 |
How come jobParameters cannot be found in ItemProcessor using annotations?
|
<p>I am having issues using the job parameters in my item processor. At this time, the code is basically setup like: <a href="https://stackoverflow.com/questions/31737209/how-to-get-job-parameteres-in-to-item-processor-using-spring-batch-annotation">How to get Job parameteres in to item processor using spring Batch annotation</a> but I am receiving an error at runtime. Also, please note that my example code does use some spring integration for processing. </p>
<pre><code>[ERROR] [restartedMain] o.s.b.SpringApplication - Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'claimFileMessageToJobRequest': Unsatisfied dependency expressed through field 'job': Error creating bean with name 'importClaimJob' defined in class path resource [com/healthcloud/batch/config/ClaimBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Job]: Factory method 'importClaimJob' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'importClaimStep1' defined in class path resource [com/healthcloud/batch/config/ClaimBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Step]: Factory method 'importClaimStep1' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'claimLineItemProcessor': Unsatisfied dependency expressed through field 'clientName': Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'importClaimJob' defined in class path resource [com/healthcloud/batch/config/ClaimBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Job]: Factory method 'importClaimJob' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'importClaimStep1' defined in class path resource [com/healthcloud/batch/config/ClaimBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Step]: Factory method 'importClaimStep1' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'claimLineItemProcessor': Unsatisfied dependency expressed through field 'clientName': Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134)
at com.healthcloud.batch.Application.main(Application.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'importClaimJob' defined in class path resource [com/healthcloud/batch/config/ClaimBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Job]: Factory method 'importClaimJob' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'importClaimStep1' defined in class path resource [com/healthcloud/batch/config/ClaimBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Step]: Factory method 'importClaimStep1' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'claimLineItemProcessor': Unsatisfied dependency expressed through field 'clientName': Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1214)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
... 22 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Job]: Factory method 'importClaimJob' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'importClaimStep1' defined in class path resource [com/healthcloud/batch/config/ClaimBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Step]: Factory method 'importClaimStep1' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'claimLineItemProcessor': Unsatisfied dependency expressed through field 'clientName': Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 35 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'importClaimStep1' defined in class path resource [com/healthcloud/batch/config/ClaimBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Step]: Factory method 'importClaimStep1' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'claimLineItemProcessor': Unsatisfied dependency expressed through field 'clientName': Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:381)
at com.healthcloud.batch.config.ClaimBatchConfiguration$$EnhancerBySpringCGLIB$$2b3b47e8.importClaimStep1(<generated>)
at com.healthcloud.batch.config.ClaimBatchConfiguration.importClaimJob(ClaimBatchConfiguration.java:185)
at com.healthcloud.batch.config.ClaimBatchConfiguration$$EnhancerBySpringCGLIB$$2b3b47e8.CGLIB$importClaimJob$6(<generated>)
at com.healthcloud.batch.config.ClaimBatchConfiguration$$EnhancerBySpringCGLIB$$2b3b47e8$$FastClassBySpringCGLIB$$ecf5444c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at com.healthcloud.batch.config.ClaimBatchConfiguration$$EnhancerBySpringCGLIB$$2b3b47e8.importClaimJob(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 36 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.Step]: Factory method 'importClaimStep1' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'claimLineItemProcessor': Unsatisfied dependency expressed through field 'clientName': Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 57 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'claimLineItemProcessor': Unsatisfied dependency expressed through field 'clientName': Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:381)
at com.healthcloud.batch.config.ClaimBatchConfiguration$$EnhancerBySpringCGLIB$$2b3b47e8.claimLineItemProcessor(<generated>)
at com.healthcloud.batch.config.ClaimBatchConfiguration.importClaimStep1(ClaimBatchConfiguration.java:196)
at com.healthcloud.batch.config.ClaimBatchConfiguration$$EnhancerBySpringCGLIB$$2b3b47e8.CGLIB$importClaimStep1$7(<generated>)
at com.healthcloud.batch.config.ClaimBatchConfiguration$$EnhancerBySpringCGLIB$$2b3b47e8$$FastClassBySpringCGLIB$$ecf5444c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at com.healthcloud.batch.config.ClaimBatchConfiguration$$EnhancerBySpringCGLIB$$2b3b47e8.importClaimStep1(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 58 common frames omitted
Caused by: org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:164)
at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1418)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1041)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
... 80 common frames omitted
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:224)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:81)
at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:51)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:87)
at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:242)
at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:161)
... 84 common frames omitted
</code></pre>
<p>Using the example at <a href="https://stackoverflow.com/questions/31737209/how-to-get-job-parameteres-in-to-item-processor-using-spring-batch-annotation">How to get Job parameteres in to item processor using spring Batch annotation</a>, I have the following code. One would think this would be a simple cut and paste and then be on my way. I am using jobParameters elsewhere just fine, but it definitely fails in the ItemProcessor.</p>
<p>ClaimBatchConfiguration:</p>
<pre><code>...
@Configuration
@EnableBatchProcessing
public class ClaimBatchConfiguration {
...
@Bean
public ClaimLineItemProcessor claimLineItemProcessor() {
return new ClaimLineItemProcessor();
}
@Bean
public Job importClaimJob() {
return claimJobBuilderFactory.get("importClaimJob").incrementer(new RunIdIncrementer())
.listener(claimListener()).flow(importClaimStep1()).end().build();
}
@Bean
public Step importClaimStep1() {
return claimStepBuilderFactory.get("importClaimStep1").<ClaimLine, ClaimLine> chunk(1)
.reader(claimFileReader(OVERRIDDEN_BY_EXPRESSION)).processor(claimLineItemProcessor())
.writer(claimLineWriter()).faultTolerant().retryLimit(retryLimit)
.retry(DeadlockLoserDataAccessException.class).skipLimit(1) // default is 0
.skip(Exception.class).build();
}
</code></pre>
<p>ClaimFileMessagetoJobRequest.java:</p>
<pre><code>...
@Component
public class ClaimFileMessageToJobRequest implements ApplicationContextAware {
...
@Transformer(inputChannel = "claimInputChannel", outputChannel = "commonJobGateway")
public JobLaunchRequest messageToRequest(Message<File> message) {
logger.info("Load Claim Started at " + DateFormat.getCurrentDateTime());
String[] fileNameParts = message.getPayload().getName().split("[_]");
// handle error
JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
jobParametersBuilder.addString("clientName", fileNameParts[1]);
logger.debug("Job Paramaters: " + jobParametersBuilder.toJobParameters());
JobLaunchRequest request = new JobLaunchRequest(job, jobParametersBuilder.toJobParameters());
return request;
}
...
}
</code></pre>
<p>ClaimLineItemProcessor.java:</p>
<pre><code>@Scope("step")
public class ClaimLineItemProcessor implements ItemProcessor<ClaimLine, ClaimLine> {
@Value("#{jobParameters['clientName']}")
private String clientName;
// client name getter and setter here
@Override
public ClaimLine process(ClaimLine claimline) throws Exception {
logger.debug("Current Client Name" + clientName);
// bunch or work to really do
return claimline;
}
}
</code></pre>
| 0 | 7,526 |
How do I make Firefox reload page when back button is pressed?
|
<p>I have tried every combination and permutation of meta tags that are supposed to stop a page from being cached, but Firefox STILL caches the page! <strong>I just need the URL to reload when a user presses the back button.</strong> Works fine in IE8.</p>
<p>I have tried all of these...</p>
<pre><code><meta http-equiv="Cache-Control" content="no-store" />
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="-1"/>
<meta http-equiv="Expires" content="Sat, 1 Jan 2000 00:00:00 GMT" />
</code></pre>
<p>...and I have also tried the following JavaScript...</p>
<pre><code><input type="hidden" id="refreshed" value="no"/>
<script type="text/javascript">
onload=function(){
var e=document.getElementById("refreshed");
if(e.value=="no"){
e.value="yes";
}
else{
e.value="no";
location.reload();
}
}
</script>
</code></pre>
<p>... all to no avail. What am I missing here? Pages are generated with PHP if that matters.</p>
<p><strong>UPDATE 1:</strong></p>
<p>I have tried every suggestion thus far but I still cannot get this to work. When I use Chris's PHP code I use it like this...</p>
<pre><code><?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<!--the rest of my page-->
</code></pre>
<p>.. and as you can see it is at the EXTREME top of my webpage, before the <code>DOCTYPE</code> header.</p>
<p>I have also experimented with <code>session_start()</code> but even after reading the manual I am not sure I am using it right. I was putting it right at the very top of my page as well.</p>
<p><strong>I am open to ANY SUGGESTIONS that make this work without breaking other page functionality. I know I have seen pages that reload EVERY TIME the back button is used, HOW ARE THEY DOING IT?!</strong></p>
<p><strong>SOLVED!</strong></p>
<p>Turns out I had multiple issues working against me, but through due diligence I was able to eliminate those issues and emerge victorious.</p>
<p>After Chris updated his code to...</p>
<pre><code><?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo time();
?><a href="http://google.com">aaaaaaaaaaaaa</a>
</code></pre>
<p>I found that his code did indeed work when I used it EXACTLY how he had it with NOTHING else, but when I put it into my pages it didn't work. All of my pages are either <code>.php</code> or <code>.html</code> and all are attached to a DWT (Dynamic Web Template), so I was updating all of them at once with Chris's code. What I didn't realize was that the DWT starts RIGHT AFTER the <code>DOCTYPE</code> header, so the code was never inserted into my pages. I could find no way to make the DWT include the <code>DOCTYPE</code> header so I went into all my pages and manually inserted the code above the <code>DOCTYPE</code> header.</p>
<p>Next I found that even though my server is set to parse <code>.htm</code> and <code>.html</code> as <code>.php</code> the <code>.html</code> pages were generating an error at the very where I had inserted Chris's code saying something to the effect of "cannot modify headers, headers have already been sent". I didn't really care what my extensions were so I just changed all my <code>.html</code> extensions to <code>.php</code> extensions.</p>
<p>A final minor annoyance was that even though the page was now not being cached (just like I wanted) Firefox was placing the user at their last location on the previous page when they used the back button (i.e. if a user was at the bottom of page a when they navigated to page b, then the user used the back button on page b they would be returned to the bottom of page a, not the top of page a as desired). Trimming down my original JavaScript fixed this...</p>
<pre><code> <script type="text/javascript">
onload=function(){
document.getElementById('content').scrollTop=0;
}
</script>
</code></pre>
<p>Even though this seems very involved for such a simple problem I am glad it is fixed. Thanks for your help everyone (especially Chris).</p>
| 0 | 1,520 |
Error:java.lang.NullPointerException (no error message)
|
<p>This question have asked for several times and I follow those questions and tried to solve the problem. The project was successfully build and running I shut down my computer few hours ago. This problem is making me mad please help.</p>
<p>Message:</p>
<pre><code> Information:Gradle tasks [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2420Library UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72420Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72420Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2420Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72420Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCompat2420Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCoreUi2420Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCoreUtils2420Library UP-TO-DATE
:app:prepareComAndroidSupportSupportFragment2420Library UP-TO-DATE
:app:prepareComAndroidSupportSupportMediaCompat2420Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42420Library UP-TO-DATE
:app:prepareComAndroidSupportSupportVectorDrawable2420Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:mergeDebugShaders
Error:java.lang.NullPointerException (no error message)
Information:BUILD FAILED
Information:Total time: 1.422 secs
Information:1 error
Information:0 warnings
Information:See complete output in console
</code></pre>
<p>build.gradle :</p>
<pre><code> apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion '24.0.0'
defaultConfig {
applicationId "np.com.yipl.yiplandroidlistme"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:design:24.2.0'
compile 'com.android.support:recyclerview-v7:24.2.0'
compile 'com.android.support:cardview-v7:24.2.0'
compile 'com.mcxiaoke.volley:library:1.0.19'
}
</code></pre>
<p>Please help .</p>
| 0 | 1,049 |
org.hibernate.exception.DataException: Could not execute JDBC batch update
|
<pre><code>AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: org.hibernate.exception.DataException: Could not execute JDBC batch update
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}hostname:XXX
org.hibernate.exception.DataException: Could not execute JDBC batch update
at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:601)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2938)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:395)
at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at stickler.webservice.v1.WebServicePortBindingStub.publish(WebServicePortBindingStub.java:548)
at com.infopath.main.Main.moduleRequestOne(Main.java:41)
at com.infopath.main.Main.main(Main.java:23)
</code></pre>
| 0 | 1,110 |
jQuery Ajax does not update the result inside the div
|
<p>This question might be basic for most of the people out here, but I'm really fed up of not getting the desired o/p. I want to make AJAX calls when an item from the list(id = vzlabs_data) is being clicked and its respective data should be updated inside the table(id = table_data). </p>
<p>Currently, I'm able to POST the data, make the db calls against it, fetches it data and the data fetched is being printed in the python interpreter but is not updated inside the table.</p>
<p>Where I'm going wrong?</p>
<p><strong>HTML template</strong> </p>
<pre><code><div class="navbar">
<div class="navbar-inner">
<ul class="nav" id="nav_bar">
<li class="active"><a href="#">Home</a>
</li>
<li><a href="#device">Device</a>
</li>
<li><a href="#content">Content</a>
</li>
<li><a href="#about">About</a>
</li>
<li><a href="#help">Help</a>
</li>
</ul>
</div>
</div>
<div class="pull-right">From :
<input type="text" id="from" name="from" />To :
<input type="text" id="to" name="to" />
</div>
<br>
<br>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2 pull-left">//****** An item is picked up from this list**********
<ul class="nav nav-tabs nav-stacked"
id="vzlabs_data">
<li class="active"><a href="#">All Data</a>
</li>
<li><a href="#">VZW3RD</a>
</li>
<li><a href="#">VZWLAB</a>
</li>
<li><a href="#">VZW2ND</a>
</li>
</ul>
</div>
<!-- end of div span2-->
<div id="pie_chart" class="span4" style="height: 275px"></div>
<!-- end of div span4-->
<div class="span5">
<table class="table table-striped" id="table_data">
<thead>
<tr>
<th>Categories</th>
<th>Subscribers</th>
<th>Rate(bps)</th>
<th>Tonage(Bytes)</th>
</tr>
</thead>
<tbody>// Data is updated over here. {% for key, value in vzlab_data.items %}
<tr>
<td>{{key}}</td>
<td>{{value.subscriber}}</td>
<td>{{value.rate_bps}}</td>
<td>{{value.tonage_bytes}}
<div class="progress">
<div class="bar" style="width: 60%;"></div>
</div>
</td>
</tr>{%endfor%}</tbody>
</table>
</div>
<!-- end of div span7-->
</div>
<!-- end of div row-->
</code></pre>
<p><strong>JS function</strong></p>
<pre><code>$(function () {
$("#vzlabs_data li").click(function () {
$.ajax({
type: "POST",
url: "/dashboard/",
data: {
'lab': $(this).text()
},
success: function (result) {
$("#table_data").html(result);
}
});
});
});
</code></pre>
<p><strong>views.py</strong> </p>
<pre><code>def dashboard(request):
vzlab_data = get_vzlab_data("All Data")
if request.is_ajax():
lab = request.POST['lab']
vzlab_data = get_vzlab_data(lab)
return HttpResponse(simplejson.dumps(vzlab_data), mimetype='application/javascript')
ctx = {'vzlab_data' : vzlab_data}
return render_to_response('dashboard/dashboard1.html',ctx, context_instance = RequestContext(request))
</code></pre>
| 0 | 2,484 |
Parse error: syntax error, unexpected end of file
|
<p>Its working at first but when I re-edit it since it looks messy, the result is now error, can somebody please help me. </p>
<p>I think i already closed the braces and scripts, i dont know what's wrong with it.</p>
<pre><code><?php
session_start();
require("functions.php");
if(!isset($_GET['id'])&&isset($_SESSION['username'])) header("Location: ?id=".getId($_SESSION['username']));
?>
<!-- HEAD -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>System of Account</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<link rel="stylesheet" href="animate.css">
<link href="fonts/css/font-awesome.min.css" rel="stylesheet">
<link rel="shortcut icon" href="favicon.png">
<link href="css/animate.min.css" rel="stylesheet">
<link href="fonts/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
<!--<link type="text/css" rel="stylesheet" href="styles.css" />-->
<style>
body{
margin: 0 auto;
background-image:url("../clsimages/GG.jpg");
background-repeat: no-repeat;
background-size: 100% 720px;
-webkit-background-size:cover;
-moz-background-size:cover;
-o-background-size:cover;
}
.container{
width: 65%;
height:615px;
background-color: rgba(52, 73, 94, 0.3);
margin-top: 50px;
border-radius:4px;
border: 2px solid black;
}
</style>
<style>
table{
float:left;
border: 1px solid ;
}
</style>
<style>
ul {
width: 70%;
margin: auto;
}
</style>
<style>
.div{
width: 250%;
}
.form-control{
border: 2px dashed #D1C7AC;
width: 230px;
color: #1E049E;
onfocus="this.value=''
font-weight: bold;
font-size: 18px;
font-family: "Times New Roman";
}
</style>
<script>
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<nav>" +
divElements + "</nav>";
//Print Page
window.print();
//*Restore orignal HTML
// document.body.innerHTML = oldPage;
// window.location='print.php';
}
</script>
</head>
<!-- BODY -->
<body>
<div id="container">
<?php
if(!isset($_SESSION['username']))
{
?>
</br></br></br></br></br></br></br></br></br></br>
<center>
<font color="black"> <h2 class="form-signin-heading"> Please Login <i class="fa fa-sign-in"> </i></h2> </font>
</br></br>
<form action="authenticate.php" class="form-signin" method="POST">
<div class="input-group" style="margin-left:42%">
<span class="input-group-addon" id="basic-addon1">Username:</span>
<input type="text" name="username" class="form-control" style="width:23%; height: 40px;" required><br />
</div>
</br>
<div class="input-group" style="margin-left:42%">
<span class="input-group-addon" id="basic-addon1" >Password:</span>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Enter Your Password" style="width:23%; height:40px;"required>
</div>
<br /> </br>
<button class="btn btn-lg btn-primary btn-block" type="submit" style="width:25%;"> Login <i class="fa fa-sign-in"> </i> </button>
</center>
</form>
<?php
if(isset($_GET["feedback"]))
echo $_GET["feedback"];
}
?>
<!-- NEXT PAGE -->
<?php
if(isset($_SESSION['username']))
{
$profileUsersData = getUsersData(mysql_real_escape_string($_GET['id']));
?>
<div id="menu">
<a class="button" href="logout.php">Logout</a>
</div>
<?php if(userExists(mysql_real_escape_string($_GET['id']))){ ?>
<!--Button print -->
<button class="btn btn-default" onclick="javascript:printDiv('printablediv')" class = "btn btn-success" ><i class="fa fa-print"> </i> <b> Print the fees</b></button>
<!-- End -->
<!--PRINT -->
<div class="" id="printablediv">
<p><img src="clsimages/STATEMENT.png"></p>
<div align="right">
<script>
var y = new Date();
var currentyear = y.getFullYear();
var nextyear= y.getFullYear() +1;
document.write("<p class='navbar-text pull-right'><font style = 'Impact' color = 'black'><h3> SY:<font color='blue'> "+ currentyear +"-"+ nextyear +" </h3></font></font></p>");
</script> </th>
</div>
<br>
<!-- Table -->
<table border='1' style='border-collapse:collapse; width:100%; border-bottom: hidden;'>
<col style='width:50%;'>
<tr>
<td>
<ul>
<p><font size='2%' face='Arial'> <b>
</br>
<?php
if(isset($_SESSION['username']))
{
$profileUsersData = getUsersData(mysql_real_escape_string($_GET['id']));
?>
<?php if(userExists(mysql_real_escape_string($_GET['id']))){ ?>
<div id="header">
<?php echo 'STUDENT NAME: '. $profileUsersData['LastName'].", ".$profileUsersData['FirstName']. " ".$profileUsersData['MiddleName'].""; ?>
</br></br>
<?php echo ' </br> LEVEL: '. $profileUsersData['Level'].""; ?>
</b>
</ul>
</td>
<td>
<ul>
<p><font size="2%" face="Arial"><b> TELEPHONE: (63 2) 834-2915
</br></br>
EMAIL: christianloveschool@yahoo.com
</p>
</b>
</ul>
</table>
<table border="1" style="border-collapse:collapse; width:100%;">
<col style="width:50%;">
<tr>
<td>
<ul>
<font size="2%" face="Arial">
<b>
<?php echo ' </br> DATE: '. $profileUsersData['TuitionDate'].""; ?>
<b>
</br>
<?php echo ' </br> TUITION FEE: '. $profileUsersData['Tuition'].""; ?>
</br> </br>
<?php echo ' </br> BOOKS: '. $profileUsersData['Books'].""; ?>
</br> </br>
<?php echo ' </br> SCHOOL/ PE UNIFORM: '. $profileUsersData['Uniform'].""; ?>
</br> </br>
<?php echo ' </br> OLD ACCOUNT: '. $profileUsersData['OldAcct'].""; ?>
</br>
</b>
</ul>
</td>
</font>
<td>
<font size="2%" face="Arial">
<ul>
<b>
<?php echo ' </br> BALANCE: '. $profileUsersData['Balance'].""; ?>
</b>
</ul>
</td>
</font>
</tr>
</table>
<?php } else echo "Invalid ID"; ?>
<?php } ?>
<!-- RULES OF PAYMENT -->
<table border="1" style="border-collapse:collapse; width:100%; border-top:hidden;">
<tr>
<td>
<font size="3%" face="Arial">
<ul>
<b><u>RULES ON PAYMENT:</u></b>
</font>
</br></br>
<font size="2%" face="Arial">
1. Tuition fee payment must be made every 5th day of the scheduled payment scheme. </br></br>
2.Payments should be made on time in order to take the exam needed. </br></br>
3. Reservations and Miscellaneous fees are non-refundable. </br></br>
4.A student who withdraws before the start of the school year shall be charged 50% on miscellaneous fee. </br></br>
5. A student who transfers or otherswise withdraws within two weeks after the beginning of classes and has already paid the
pertinent and other school fees in full may be charged to pay the whole amount of miscellaneous fees and the amount supposed tp be paid pertaining to tuition fee. </br></br>
6. A student who transfers or withdraws within two weeks after the beginning of classes and has not yet paid the pertinent
and other school fees shall be charged to pay the whole amount of miscellaneous fees in full and the amount supposed to be paid pertaining to tuition fee. </br></br>
7. A student who withdraws any time after the second week of classes, full payment of tuition and miscellaneous fees shall be charged. </br></br>
8. Discounts shall only be applied at the last payment. </br></br>
9. Any discounts granted will be forfeited if the payment is delayed. </br></br>
10. All fees should be paid in full before the end of the school year.
</font>
</br></br>
<hr></hr>
<br>
<table>
<font size="3%">
Any discount granted will be <b> forfeited </b> if the payment is delayed.
<br>
<u> <font color="red"> <b>
<br>
Bring this notice upon payment and have the Examination Permit validated from the office.
</font> </u>
</table>
</br></br>
<font color="blue" size="3%">
Contact the school if payment has been made, thank you.
</u> </font> </b>
</ul>
</table>
</td>
</tr>
</div>
</div>
</body>
</html>
</code></pre>
| 0 | 5,283 |
error C2143: syntax error : missing ';' before '*'
|
<p>I'm not new to C++ but I am used to running a g++ compiler vs Microsoft's VS C++. I understand what this error should mean. It should mean that I'm missing a ';' on the line before or in the class Polygon. I can't seem to find anything wrong. g++ compiles the code without error. It seems like the Polygon Class isn't being loaded. Can anyone please show me what I'm missing please.I have the Application.cpp, Polygon.h, and Polygon.cpp below.</p>
<p>Application.cpp throwing errors but if I can fix the first others will follow:</p>
<p>application.cpp(121) : error C2143: syntax error : missing ';' before '*'<br/>
application.cpp(121) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int<br/>
application.cpp(121) : error C2365: 'Polygon' : redefinition; previous definition was 'function'
c:\program files\microsoft sdks\windows\v6.0a\include\wingdi.h(4203) : see declaration of 'Polygon'</p>
<pre><code>#include <sstream>
#include <numeric>
#include <math.h>
#include "Polygon.h"
#define PI 3.14159265
//use standard namespace
using namespace std;
/**************************** Window Variables ****************************/
double _window_height = 500;
double _window_width = 500;
double _window_position_x = 0;
double _window_position_y = 0;
string _window_title ("Assignment 5");
/**************************** Object Variables ****************************/
int _my_shape = 0;
GLint _object_shine = 40;
double _object_y_rotation = 0;
GLfloat ambient_reflection[3] = {1.0, 1.0, 1.0};
GLfloat diffuse_reflection[3] = {1.0, 1.0, 1.0};
GLfloat specular_reflection[3] = {1.0, 1.0, 1.0};
GLfloat emissive_color[3] = {0.0, 0.0, 0.0};
int specular_exponent = 0;
/*************************** Lighting Variables ***************************/
//Global Light settings
GLfloat _global_ambient_light[] = {0.5, 0.5, 0.5, 1.0};
GLfloat _global_diffuse_light[] = {0.7, 0.7, 0.7, 1.0};
int rotation_int = 0;
int rotation_angle = 90;
int _CAMERA_DISTANCE = 2;
//Light 0 Settings
GLfloat _z_axis_rotations[8][4] = {{(_CAMERA_DISTANCE*cos((90)*PI/180)), (_CAMERA_DISTANCE*sin((90)*PI/180)), 0.0, 1.0},
{(_CAMERA_DISTANCE*cos((45)*PI/180)), (_CAMERA_DISTANCE*sin((45)*PI/180)), 0.0, 1.0},
{(_CAMERA_DISTANCE*cos((0)*PI/180)), (_CAMERA_DISTANCE*sin((0)*PI/180)), 0.0, 1.0},
{(_CAMERA_DISTANCE*cos((315)*PI/180)), (_CAMERA_DISTANCE*sin((315)*PI/180)), 0.0, 1.0},
{(_CAMERA_DISTANCE*cos((270)*PI/180)), (_CAMERA_DISTANCE*sin((270)*PI/180)), 0.0, 1.0},
{(_CAMERA_DISTANCE*cos((225)*PI/180)), (_CAMERA_DISTANCE*sin((225)*PI/180)), 0.0, 1.0},
{(_CAMERA_DISTANCE*cos((180)*PI/180)), (_CAMERA_DISTANCE*sin((180)*PI/180)), 0.0, 1.0},
{(_CAMERA_DISTANCE*cos((135)*PI/180)), (_CAMERA_DISTANCE*sin((135)*PI/180)), 0.0, 1.0}};
GLfloat _ambient_0_light[] = {0.3f, 0.3f, 0.3f, 1.0f};
GLfloat _diffuse_0_light[] = {0.6f, 0.6f, 0.6f, 1.0f};
GLfloat _specular_0_light[] = {0.6f, 0.6f, 0.6f, 1.0f};
GLfloat _specular_0_property[] = {0.6f, 0.6f, 0.6f, 1.0f};
//Light 1 Settings
// Green Spotlight with narrow angle
GLfloat _light_1_position[] = {2.0, 0.0, -0.5, 1.0};
GLfloat _diffuse_1_light[] = {0.2, 0.4, 0.9, 1.0};
GLfloat _spot_1_direction[] = {-0.3, -2.0, -0.3};
//Light 2 Settings
// Red Spotlight with wide angle
GLfloat _light_2_position[] = {0.3, -0.5, 4.0, 1.0};
GLfloat _diffuse_2_light[] = {1.0, 0.2, 0.6, 1.0};
GLfloat _spot_2_direction[] = {0.3, -0.5, -2.0};
GLfloat _cutoff = 90.0;
GLfloat _AMBIENT_CONSTANT = 0.1;
GLfloat _DIFFUSE_CONSTANT = 0.1;
GLfloat _EMISSION_CONSTANT = 0.05;
GLfloat _SPECULAR_CONSTANT = 0.1;
int _SPECULAR_EXPONENT_CONSTANT = 1;
int _CUTOFF_CONSTANT = 1;
/*************************** Shading Variables ***************************/
bool _shade_model_smooth = true;
/**************************** File Variables *****************************/
//Error String printed if the file is not found
string _FILE_OPEN_ERROR = "Error: File could not be found or opened.";
//Error String printed if the file is not formed correctly
string _CHOICE_INVALID_ERROR = "Error: The choice you made was not one that is defined.";
/** for file reading **/
//The Array for holding all the Polygons
Polygon** _Polygons;
//the current size of the Polygon Array
int _polygons_max = 10;
//the current element for processing in the Polygon Array
int _polygons_current = 0;
/* ReadFromFile
*
* This method will ask a filename from the user and either return to
* the user a file not found error or will read in from the file the
* coordinates and place them in the coordinate array, while also setting
* the number of lines that make up a shape.
*/
void ReadFromFile(){
ifstream input; // input file stream
string filename = ""; // used to store filename
string line = ""; // temporary storage for reading lines at a time
// cout << "Type a filename and press Enter: ";
// cin >> filename;
//cout << "Type a filename and press Enter: dodecahedron.dat" << endl;
filename = "dodec.dat";//"dodecahedron.dat"; //should be 36 polygons
input.open (filename.c_str(), ifstream::in);//try to open the file
if(input.is_open()){ //check if file is open
_Polygons = new Polygon*[_polygons_max];
double _light_settings[12] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
int SH = 0;
double _normals[3] = {0.0, 0.0, 0.0};
int _coordinate_count = 0;
int _coordinate_max = 4;
double** _coordinates = new double*[_coordinate_max];
while (input.good()){ //not eof or failbit
/* Ensure space is available */
if(_polygons_current >= _polygons_max){
_polygons_max = _polygons_max * 2; //double max size
Polygon** temp = new Polygon*[_polygons_max]; //create bigger array
for (int j = 0; j <_polygons_current; j++) {
temp[j] = _Polygons[j]; // copy values to new array.
}
delete [] _Polygons; //free old array memory
_Polygons = temp; //transfer polygons
}
getline(input, line); //get the line from input
string::size_type _last_pos = line.find_first_not_of(" ", 0);
string::size_type _pos = line.find_first_of(" ", _last_pos);
if((line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == '#'){ //comment
//do nothing for this line
}else if((line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == 'J' ||
(line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == 'j'){ //polygon start
if(_coordinate_count != 0){
//cout << "Polygon #" << _polygons_current << endl;
_Polygons[_polygons_current] = new Polygon(_coordinate_count, _coordinates);
_Polygons[_polygons_current]->setAmbientReflection(_light_settings[0], _light_settings[1], _light_settings[2]);
_Polygons[_polygons_current]->setDiffuseReflection(_light_settings[3], _light_settings[4], _light_settings[5]);
_Polygons[_polygons_current]->setSpecularReflection(_light_settings[6], _light_settings[7], _light_settings[8]);
_Polygons[_polygons_current]->setEmissiveColor(_light_settings[9], _light_settings[10], _light_settings[11]);
_Polygons[_polygons_current]->setSurfaceNormals(_normals[0], _normals[1], _normals[2]);
_Polygons[_polygons_current]->setSpecularExponent(SH);
for(int i=0; i<_coordinate_count; i++){
delete _coordinates[i];
}
_coordinate_count = 0;
_polygons_current++;
}
if(line.find_first_not_of(" ", _pos) != string::npos){
for(int i=0; i<12; i++){
_last_pos = line.find_first_not_of(" ", _pos);
_pos = line.find_first_of(" ", _last_pos);
_light_settings[i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
}
_last_pos = line.find_first_not_of(" ", _pos);
_pos = line.find_first_of(" ", _last_pos);
SH = atoi(line.substr(_last_pos, _pos - _last_pos).c_str());
for(int i=0; i<3; i++){
_last_pos = line.find_first_not_of(" ", _pos);
_pos = line.find_first_of(" ", _last_pos);
_normals[i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
}
}
}else{
/* Ensure space is available */
if(_coordinate_count >= _coordinate_max){
_coordinate_max = _coordinate_max * 2; //double max size
double** temp = new double*[_coordinate_max]; //create bigger array
for (int i = 0; i < _coordinate_count; i++) {
temp[i] = new double[3];
temp[i][0] = _coordinates[i][0]; // copy values to new array.
temp[i][1] = _coordinates[i][1];
temp[i][2] = _coordinates[i][3];
}
delete [] _coordinates; //free old array memory
_coordinates = temp; //transfer polygons
}
_coordinates[_coordinate_count] = new double[3];
for(int i=0; i<3; i++){
_coordinates[_coordinate_count][i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
_last_pos = line.find_first_not_of(" ", _pos);
_pos = line.find_first_of(" ", _last_pos);
}
_coordinate_count++;
}
}
input.close();
}else{
//if the file could not be opened output to the screen the error
cout << _FILE_OPEN_ERROR;
exit(0);
}
}
/* InitializeWindow
*
* Initializes the GLUT Library settings and creates a window for the
* program to be displayed in.
*
*/
void InitializeWindow(int argc, char** argv){
glutInit(&argc,argv); /* Initialize GLUT */
glutInitDisplayMode( GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH );/* Specify display mode */
glutInitWindowSize(_window_width, _window_height); /* Set window size */
glutInitWindowPosition(_window_position_x, _window_position_y); /* Set window position */
glutCreateWindow(_window_title.c_str()); /* Create Window */
}
/* InitializeEnvironment
*
* Initializes the Glut environment in which the drawing is to be done.
*/
void InitializeEnvironment(){
glClearColor (0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);
glLoadIdentity();
glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[0]);
glLightfv(GL_LIGHT0, GL_SPECULAR, _specular_0_light);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0);
glLoadIdentity();
glLightfv(GL_LIGHT1, GL_POSITION, _light_1_position);
glLightfv(GL_LIGHT1, GL_DIFFUSE, _diffuse_1_light);
//
// glLoadIdentity();
// glLightfv(GL_LIGHT2, GL_POSITION, light3_position);
// glLightfv(GL_LIGHT2, GL_DIFFUSE, light3_diffuse_light);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
if(_my_shape == 1){
glFrontFace(GL_CW);
}else{
glFrontFace(GL_CCW);
}
glEnable(GL_CULL_FACE);
}
// In the main method we registered this method as the callback function for
// Keyboard input. Anytime a key is pressed the ascii value of the key and
// the x and y positions of the mouse cursor within the window are passed to
// this function.
void Keyboard(unsigned char key, int x, int y) {
switch (key) {
case '1':
glEnable(GL_LIGHT0);
break;
case '2':
glEnable(GL_LIGHT1);
break;
case '+': /* Increase the cutoff angle of the positional light. */
if(_cutoff == 90){
_cutoff = 180;
}else if((_cutoff-_CUTOFF_CONSTANT) > 180){
_cutoff = 180;
}else{
_cutoff += _CUTOFF_CONSTANT;
}
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
break;
case '-': /* Decrease the cutoff angle of the positional light. */
if(_cutoff == 180){
_cutoff = 90;
}else if((_cutoff-_CUTOFF_CONSTANT) < 0){
_cutoff = 0;
}else{
_cutoff -= _CUTOFF_CONSTANT;
}
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
break;
case '0': /* Turn off the directional and positional light. */
glDisable(GL_LIGHT0);
glDisable(GL_LIGHT1);
break;
case 'a': /* Decrease the ambient light. */
if(_global_ambient_light[0]>0){
_global_ambient_light[0] = _global_ambient_light[1] = _global_ambient_light[2] -= _AMBIENT_CONSTANT;
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
}
break;
case 'A': /* Increase the ambient light. */
if(_global_ambient_light[0]<1){
_global_ambient_light[0] = _global_ambient_light[1] = _global_ambient_light[2] += _AMBIENT_CONSTANT;
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
}
break;
case 'd': /* Decrease the diffuse light. */
if(_global_diffuse_light[0]>0){
_global_diffuse_light[0] = _global_diffuse_light[1] = _global_diffuse_light[2] -= _DIFFUSE_CONSTANT;
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);
}
break;
case 'D': /* Increase the diffuse light. */
if(_global_diffuse_light[0]<1){
_global_diffuse_light[0] = _global_diffuse_light[1] = _global_diffuse_light[2] += _DIFFUSE_CONSTANT;
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);
}
break;
case 's': /* Decrease the specular component of the positional light. */
if(_my_shape != 1){
for(int i=0; i<3; i++){
if((specular_reflection[i]-_SPECULAR_CONSTANT) < -1.0){
specular_reflection[i] = -1.0;
}else{
specular_reflection[i] -= _SPECULAR_CONSTANT;
}
}
}else{
for(int i=0; i < _polygons_current; i++){ //Over all Polygons
double* sr = _Polygons[i]->getSpecularReflection();
for(int j=0; j<3; j++){
if((sr[j]-_SPECULAR_CONSTANT) < -1.0){
sr[j] = -1.0;
}else{
sr[j] -= _SPECULAR_CONSTANT;
}
}
}
}
break;
case 'S': /* Increase the specular component of the positional light. */
if(_my_shape != 1){
for(int i=0; i<3; i++){
if((specular_reflection[i]+_SPECULAR_CONSTANT) > 1.0){
specular_reflection[i] = 1.0;
}else{
specular_reflection[i] += _SPECULAR_CONSTANT;
}
}
}else{
for(int i=0; i < _polygons_current; i++){ //Over all Polygons
double* sr = _Polygons[i]->getSpecularReflection();
for(int j=0; j<3; j++){
if((sr[j]+_SPECULAR_CONSTANT) > 1.0){
sr[j] = 1.0;
}else{
sr[j] += _SPECULAR_CONSTANT;
}
}
}
}
break;
case 'h': /* Decrease the shininess of the object. */
if(_my_shape != 1){
if((specular_exponent-_SPECULAR_EXPONENT_CONSTANT) < 0){
specular_exponent = 0;
}else{
specular_exponent-=_SPECULAR_EXPONENT_CONSTANT;
}
}else{
for(int i=0; i < _polygons_current; i++){ //Over all Polygons
int sh = _Polygons[i]->getSpecularExponent();
if((sh-_SPECULAR_EXPONENT_CONSTANT) < 0){
_Polygons[i]->setSpecularExponent(0);
}else{
_Polygons[i]->setSpecularExponent(sh-_SPECULAR_EXPONENT_CONSTANT);
}
}
}
break;
case 'H': /* Increase the shininess of the object. */
if(_my_shape != 1){
if((specular_exponent+_SPECULAR_EXPONENT_CONSTANT) > 128){
specular_exponent = 128;
}else{
specular_exponent+=_SPECULAR_EXPONENT_CONSTANT;
}
}else{
for(int i=0; i < _polygons_current; i++){ //Over all Polygons
int sh = _Polygons[i]->getSpecularExponent();
if((sh+_SPECULAR_EXPONENT_CONSTANT) > 128){
_Polygons[i]->setSpecularExponent(128);
}else{
_Polygons[i]->setSpecularExponent(sh+_SPECULAR_EXPONENT_CONSTANT);
}
}
}
break;
case 'e': /* Decrease the emissive light of the object. */
if(_my_shape != 1){
if((emissive_color[0]-_EMISSION_CONSTANT) < 0){
emissive_color[0] = 0;
}else{
emissive_color[0] -= _EMISSION_CONSTANT;
}
if((emissive_color[1]-_EMISSION_CONSTANT) < 0){
emissive_color[1] = 0;
}else{
emissive_color[1] -= _EMISSION_CONSTANT;
}
if((emissive_color[2]-_EMISSION_CONSTANT) < 0){
emissive_color[2] = 0;
}else{
emissive_color[2] -= _EMISSION_CONSTANT;
}
}else{
for(int i=0; i < _polygons_current; i++){ //Over all Polygons
double* ep = _Polygons[i]->getEmissiveColor();
if((ep[0]-_EMISSION_CONSTANT) < 0){
ep[0] = 0;
}else{
ep[0] -= _EMISSION_CONSTANT;
}
if((ep[1]-_EMISSION_CONSTANT) < 0){
ep[1] = 0;
}else{
ep[1] -= _EMISSION_CONSTANT;
}
if((ep[2]-_EMISSION_CONSTANT) < 0){
ep[2] = 0;
}else{
ep[2] -= _EMISSION_CONSTANT;
}
}
}
break;
case 'E': /* Increase the emissive light of the object. */
if(_my_shape != 1){
if((emissive_color[0]+_EMISSION_CONSTANT) > 1){
emissive_color[0] = 1;
}else{
emissive_color[0] += _EMISSION_CONSTANT;
}
if((emissive_color[1]+_EMISSION_CONSTANT) > 1){
emissive_color[1] = 1;
}else{
emissive_color[1] += _EMISSION_CONSTANT;
}
if((emissive_color[2]+_EMISSION_CONSTANT) > 1){
emissive_color[2] = 1;
}else{
emissive_color[2] += _EMISSION_CONSTANT;
}
}else{
for(int i=0; i < _polygons_current; i++){ //Over all Polygons
double* ep = _Polygons[i]->getEmissiveColor();
if((ep[0]+_EMISSION_CONSTANT) > 1){
ep[0] = 1;
}else{
ep[0] += _EMISSION_CONSTANT;
}
if((ep[1]+_EMISSION_CONSTANT) > 1){
ep[1] = 1;
}else{
ep[1] += _EMISSION_CONSTANT;
}
if((ep[2]+_EMISSION_CONSTANT) > 1){
ep[2] = 1;
}else{
ep[2] += _EMISSION_CONSTANT;
}
}
}
break;
case 'p': /* Rotate the positional light about the Z-axis */
glLoadIdentity();
if(rotation_int == 7){
rotation_int = 0;
}else{
rotation_int++;
}
glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[rotation_int]);
break;
case 'P': /* Rotate the positional light about the Z-axis */
glLoadIdentity();
if(rotation_int == 0){
rotation_int = 7;
}else{
rotation_int--;
}
glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[rotation_int]);
break;
case 'o': /* Rotate the objects around the Y-axis : negative */
_object_y_rotation -= 15.0;
break;
case 'O': /* Rotate the objects around the Y-axis : positive */
_object_y_rotation += 15.0;
break;
case 'q': case 'Q': /* Quit the program */
exit(0);
}
//Call redisplay to draw changes
glutPostRedisplay();
}
void DrawFromFile(){
glPushMatrix();
for(int i=0; i < _polygons_current; i++){ //Over all Polygons
double* ap = _Polygons[i]->getAmbientReflection();
double* dp = _Polygons[i]->getDiffuseReflection();
double* ep = _Polygons[i]->getEmissiveColor();
double* sp = _Polygons[i]->getSpecularReflection();
GLfloat amt[] = {ap[0], ap[1], ap[2], 1};
GLfloat dif[] = {dp[0], dp[1], dp[2], 1};
GLfloat emc[] = {ep[0], ep[1], ep[2], 1};
GLfloat spc[] = {sp[0], sp[1], sp[2], 1};
int _p_sides = _Polygons[i]->getSides();
glMaterialfv(GL_FRONT, GL_AMBIENT, amt);
glMaterialfv(GL_FRONT, GL_DIFFUSE, dif);
glMaterialfv(GL_FRONT, GL_EMISSION, emc);
glMaterialfv(GL_FRONT, GL_SPECULAR, spc);
glMateriali(GL_FRONT, GL_SHININESS, _Polygons[i]->getSpecularExponent());
glBegin(GL_POLYGON);
for(int j=0; j < _p_sides; j++){
glNormal3dv(_Polygons[i]->getSurfaceNormals());
glVertex3dv(_Polygons[i]->getVertex(j));
}
glEnd();
}
glPopMatrix();
}
void Display(void){
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glShadeModel (GL_SMOOTH);
//Perspective data here
glMatrixMode(GL_PROJECTION);
gluPerspective(45, 1, 0, 2);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
switch(_my_shape){
case 1:
glTranslated(0, 0, -1);
glRotated(_object_y_rotation, 0, 1, 0);
DrawFromFile();
break;
case 2:
glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
glRotated(_object_y_rotation, 0, 1, 0);
glutSolidTeapot(0.8);
break;
case 3:
glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
glRotated(_object_y_rotation, 0, 1, 0);
glutSolidIcosahedron();
break;
case 4:
glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
glRotated(_object_y_rotation, 0, 1, 0);
glutSolidTorus(0.3, 0.8, 10, 30);
break;
default:
cout << _CHOICE_INVALID_ERROR << endl;
exit(1);
break;
}
glPopMatrix();
glFlush();
}
int PollUser(){
int choice = 0;
cout << "Use the menu below to pick a shape to draw:" << endl << endl;
cout << "1: Dodecahedron (Drawn from file)" << endl;
cout << "2: Teapot (GLUT drawn)" << endl;
cout << "3: Icosahedron (GLUT drawn)" << endl;
cout << "4: Torus (GLUT drawn)" << endl;
cout << endl << "Enter choice: ";
cin >> choice;
return choice;
}
int main(int argc, char** argv){
_my_shape = PollUser();
InitializeWindow(argc, argv); /* Initialize window */
InitializeEnvironment(); /* Initialize other parameter */
glutDisplayFunc(Display); /* Redisplay callback event handling */
glutKeyboardFunc(Keyboard); /* Keyboard callback function */
ReadFromFile(); /* Read from file */
glutMainLoop(); /* Start glut functions */
return 0;
}
</code></pre>
<p>Polygon.h</p>
<pre><code>#ifndef POLYGON_H_
#define POLYGON_H_
#include <iostream>
#include <cstdlib>
#include <new>
class Polygon {
public:
Polygon();
Polygon(int, double**);
virtual ~Polygon();
void *operator new(size_t size);
void operator delete(void *p);
void *operator new[](size_t size);
void operator delete[](void *p);
double* getVertex(int);
void setSpecularExponent(int);
void setSurfaceNormals(double,double,double);
void setAmbientReflection(double,double,double);
void setDiffuseReflection(double,double,double);
void setSpecularReflection(double,double,double);
void setEmissiveColor(double,double,double);
int getSides(void);
int getSpecularExponent(void);
double* getSurfaceNormals(void);
double* getAmbientReflection(void);
double* getDiffuseReflection(void);
double* getSpecularReflection(void);
double* getEmissiveColor(void);
private:
double** verticies;
double surface_normals[3];
double ambient_reflection[3];
double diffuse_reflection[3];
double specular_reflection[3];
double emissive_color[3];
int sides;
int spec_ex;
};
#endif /* POLYGON_H_ */
</code></pre>
<p>Polygon.cpp</p>
<pre><code>#include "Polygon.h"
using namespace std;
Polygon::Polygon(){
sides = 0;
}
Polygon::Polygon(int numberOfSides, double** polyVerticies){
sides = numberOfSides;
verticies = new double*[numberOfSides];
for(int n=0; n<numberOfSides; n++){
verticies[n] = new double[3];
verticies[n][0] = polyVerticies[n][0];
verticies[n][1] = polyVerticies[n][1];
verticies[n][2] = polyVerticies[n][2];
}
}
void *Polygon::operator new(size_t size){
void *p;
p = malloc(size);
if(!p) {
bad_alloc ba;
throw ba;
}
return p;
}
void Polygon::operator delete(void *p){
free(p);
}
// new overloaded for loc arrays.
void *Polygon::operator new[](size_t size){
void *p;
p = malloc(size);
if(!p) {
bad_alloc ba;
throw ba;
}
return p;
}
void Polygon::operator delete[](void *p){
free(p);
}
void Polygon::setSpecularExponent(int exponent){
spec_ex = exponent;
}
void Polygon::setSurfaceNormals(double x, double y, double z){
surface_normals[0] = x;
surface_normals[1] = y;
surface_normals[2] = z;
}
void Polygon::setAmbientReflection(double r, double g, double b){
ambient_reflection[0] = r;
ambient_reflection[1] = g;
ambient_reflection[2] = b;
}
void Polygon::setDiffuseReflection(double r, double g, double b){
diffuse_reflection[0] = r;
diffuse_reflection[1] = g;
diffuse_reflection[2] = b;
}
void Polygon::setSpecularReflection(double r, double g, double b){
specular_reflection[0] = r;
specular_reflection[1] = g;
specular_reflection[2] = b;
}
void Polygon::setEmissiveColor(double r, double g, double b){
emissive_color[0] = r;
emissive_color[1] = g;
emissive_color[2] = b;
}
double* Polygon::getVertex(int index){
if(index < sides){
double* _temp = new double[3];
_temp[0] = verticies[index][0];
_temp[1] = verticies[index][1];
_temp[2] = verticies[index][2];
return _temp;
}
return new double;
}
int Polygon::getSides(){
return sides;
}
int Polygon::getSpecularExponent(){
return spec_ex;
}
double* Polygon::getSurfaceNormals(){
return surface_normals;
}
double* Polygon::getAmbientReflection(){
return ambient_reflection;
}
double* Polygon::getDiffuseReflection(){
return diffuse_reflection;
}
double* Polygon::getSpecularReflection(){
return specular_reflection;
}
double* Polygon::getEmissiveColor(){
return emissive_color;
}
Polygon::~Polygon() {
delete[] verticies;
}
</code></pre>
<p>Thanks for any help anyone can offer.</p>
| 0 | 10,411 |
How to create a ODBC connection to SQL Server?
|
<p>I try to use Access to call a stored procedure in SQL Server. But have trouble to build the
ODBC connection, I do not know am I missing something? Or just need do some set in sql site? </p>
<p>I have a screen like this:</p>
<p><img src="https://i.stack.imgur.com/X0Ptq.jpg" alt="enter image description here"> </p>
<p>and code behind the OK button is this:</p>
<pre><code> Dim dbPUBS As dao.Database
Dim tdfPUBS As dao.TableDef
Dim qdfPUBS As dao.QueryDef
Dim strMsg As String
Dim strSQL As String
' Check for existence of Server, Database and User Name.
' If missing, inform user and exit.
If IsNull(Me!txtServer) Then
strMsg = "Enter name of your company's Server." & _
& "(See your database administrator)"
MsgBox strMsg, vbInformation, "Missing Data"
Me!txtServer.SetFocus
ElseIf IsNull(Me!txtDatabase) Then
strMsg = "Enter name of database. (Example: xxxx)"
MsgBox strMsg, vbInformation, "Missing Data"
Me!txtDatabase.SetFocus
ElseIf IsNull(Me!txtUID) Then
strMsg = "Enter user login. (Example: xx)" = ""
MsgBox strMsg, vbInformation, "Missing Data"
Me!txtDatabase.SetFocus
Else
strServer = Me!txtServer
strDatabase = Me!txtDatabase
strUID = Me!txtUID
' Password may be NULL, so provide for that possibility
strPWD = Nz(Me!txtPWD, "")
' Prepare connection string
strConnect = "ODBC;DRIVER={SQL Server}" _
& ";SERVER=" & strServer _
& ";DATABASE=" & strDatabase _
& ";UID=" & strUID _
& ";PWD=" & strPWD & ";"
End If
Private Function ValidateConnectString() As Boolean
On Error Resume Next
Err.Clear
DoCmd.Hourglass True
' Assume success
ValidateConnectString = True
' Create test Query and set properties
Set qdfPUBS = dbPUBS.CreateQueryDef("")
qdfPUBS.Connect = strConnect
qdfPUBS.ReturnsRecords = False
qdfPUBS.ODBCTimeout = 5
' Attempt to delete a record that doesn't exist
qdfPUBS.SQL = "DELETE FROM Authors WHERE au_lname = 'Lesandrini'"
' Simply test one Pass Through query to see that previous
' connect string is still valid (server has not changed)
qdfPUBS.Execute
' If there was an error, connection failed
If Err.Number Then ValidateConnectString = False
Set qdfPUBS = Nothing
DoCmd.Hourglass False
End Function
</code></pre>
| 0 | 1,114 |
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code, C#
|
<p>Im trying to work with databases and Entity-framework.</p>
<p>Here Is my Database:</p>
<p><a href="https://i.stack.imgur.com/8LfWi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8LfWi.png" alt="Database"></a></p>
<p>I have the following file that creates an context:</p>
<pre><code>namespace SportsStore.domain.Concrete
{
//Associate the model with the database
//This class then automatically defines a property for each table in the database that I want to work with.
public class EFDbContext : DbContext {
public DbSet<Product> Products { get; set; }
/*protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}*/
}
}
</code></pre>
<p>Here IS my file that Initialize the context-class:</p>
<pre><code>namespace SportsStore.domain.Concrete
{
public class EFProductRepository : IProductRepository
{
private EFDbContext context = new EFDbContext();
public IEnumerable<Product> Products
{
get { return context.Products.ToList(); }
}
}
}
</code></pre>
<p>When I run my application, I get the following error:</p>
<blockquote>
<p>An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code</p>
<p>Additional information: Failed to set database initializer of type 'SportsStore.domain.Concrete, EFProductRepository' for DbContext type 'SportsStore.domain.Concrete, EFDbContext' specified in the application configuration. See inner exception for details.</p>
</blockquote>
<p>Here Is the details message of the inner exception:</p>
<blockquote>
<p>Can not load file or assembly EFDbContext or one of its dependencies. The system can not find the file EFDbContext</p>
</blockquote>
<p>Here Is my App.config:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="EFDbContext" connectionString="data source=(LocalDb)\MSSQLLocalDB;initial catalog=SportsStore.domain.Concrete;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
</code></pre>
<p>Here is my Web.Config:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<contexts>
<context type="SportsStore.domain.Concrete, EFDbContext">
<databaseInitializer type="SportsStore.domain.Concrete, EFProductRepository" />
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
</code></pre>
<p>How does it know which database to use?</p>
<p>I'm new to Entity framework and databases in .NET. </p>
| 0 | 2,997 |
Play Store having new version of the app, but not showing update
|
<p>I have my app installed in my cell with version 1.0.5 ( Version code 9)</p>
<p>In Google Play Store, I can see my app with version 1.0.7 ( Version code 11 ), but it doesn't show me the button update ( it is showing me the button "Open")</p>
<p>Is it something I have to include in my app???</p>
<p>Is it a bug in Play Store???</p>
<p>Is it a configuration problem???</p>
<p>I join my AndroidManifest.xml</p>
<p>
</p>
<pre><code><uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.spg.googlemaps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.BATTERY_STATS" />
-->
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-feature
android:name="android.hardware.camera.front"
android:required="false" />
<permission
android:name="com.spg.googlemaps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:name="com.myapp.MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:logo="@drawable/ic_logo"
android:theme="@style/Theme.AppCompat" >
<uses-library android:name="com.google.android.maps" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity
android:name="com.myapp.SplashScreen"
android:label="@string/app_name"
android:noHistory="true"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Black.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.myapp.LoginActivity"
android:label="@string/title_activity_login"
android:noHistory="true"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize|stateVisible" >
</activity>
<activity
android:name="com.myapp.DashBoard"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.myapp.FragmentTabsPdv"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.myapp.DashBoard" />
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/maps_key" />
<activity
android:name="com.myapp.RutaActivity"
android:label="@string/title_activity_ruta"
android:screenOrientation="portrait" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.myapp.FragmentTabsPdv" />
</activity>
<activity
android:name="com.myapp.BaseActivity"
android:label="@string/title_activity_base"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.myapp.SettingsActivity"
android:label="@string/title_activity_settings"
android:screenOrientation="portrait" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.myapp.DashBoard" />
</activity>
<activity
android:name="com.myapp.InformacionPdvActivity"
android:label="@string/infoPdv"
android:screenOrientation="portrait" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.myapp.RutaActivity" />
</activity>
<receiver android:name="com.myapp.BaseActivity$NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<activity
android:name="com.myapp.MetricaTabs"
android:label="@string/title_activity_metrica_tabs"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.myapp.RutaActivity" />
</activity>
<meta-data
android:name="com.crashlytics.ApiKey"
android:value="7d80161d908dd5424f232598dba254c7d2a43307" />
<activity
android:name="com.myapp.SendMessageActivity"
android:label="@string/title_activity_send_message" >
</activity>
</application>
</code></pre>
<p></p>
| 0 | 2,560 |
Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?) in Angular RC 5 when unit testing
|
<p>I just upgraded to Angular RC 5 and now all component that uses 'ROUTER_DIRECTIVES' fails with 'Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?)' when I try to unit test the component. </p>
<pre><code>import { inject, addProviders } from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/core/testing';
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { HomeComponent } from './home.component';
import { UserService } from '../_services/user.service';
describe('Component: Home', () => {
beforeEach(() => {
addProviders([HomeComponent, UserService, ROUTER_DIRECTIVES, Router]);
});
it('should inject the component', inject([HomeComponent, UserService, ROUTER_DIRECTIVES, Router],
(component: HomeComponent) => {
expect(component).toBeTruthy();
// expect(component.currentUser.firstname).toEqual('Jan');
}));
</code></pre>
<p>The full error log: </p>
<pre><code> Chrome 52.0.2743 (Windows 10 0.0.0)
Error: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?).
at new BaseException (webpack:///C:/ng/anbud/~/@angular/compiler/src/facade/exceptions.js:27:0 <- src/test.ts:2943:23)
at CompileMetadataResolver.getDependenciesMetadata (webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:551:0 <- src/test.ts:24542:19)
at CompileMetadataResolver.getTypeMetadata (webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:448:0 <- src/test.ts:24439:26)
at webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:594:0 <- src/test.ts:24585:41
at Array.forEach (native)
at CompileMetadataResolver.getProvidersMetadata (webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:575:0 <- src/test.ts:24566:19)
at CompileMetadataResolver.getNgModuleMetadata (webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:305:0 <- src/test.ts:24296:58)
at RuntimeCompiler._compileComponents (webpack:///C:/ng/anbud/~/@angular/compiler/src/runtime_compiler.js:150:0 <- src/test.ts:37986:47)
at RuntimeCompiler._compileModuleAndAllComponents (webpack:///C:/ng/anbud/~/@angular/compiler/src/runtime_compiler.js:78:0 <- src/test.ts:37914:37)
at RuntimeCompiler.compileModuleAndAllComponentsSync (webpack:///C:/ng/anbud/~/@angular/compiler/src/runtime_compiler.js:52:0 <- src/test.ts:37888:21)
</code></pre>
<p>Any ideas how to unit test components with routing? </p>
| 0 | 1,033 |
Having Troubles with UnixODBC, FreeTDS, and PyODBC
|
<p>I am having great difficulty getting all three of these to work together in harmony. I guess I'll list all the various configurations, along with the test code to see if a pair of fresh eyes can realize my stupidity.</p>
<p>I'm running 12.04 Ubuntu Server and I'm trying to connect to a MSSQL Server 2008 and end up using it with PyODBC. </p>
<p>However, when just putting in </p>
<pre><code>tsql -S T2 -U Foo -P Bar
</code></pre>
<p>I get the </p>
<pre><code>1>
2>
3>
4>
5>
6>
7>
8>
9>
10>
11>
</code></pre>
<p>and etc.</p>
<p>Anyway, if anyone would be able to help (and I would be eternally grateful if you can clear me of this haze), here are my current configurations.</p>
<p>This is my /etc/odbc.ini</p>
<pre><code>[ODBC Data Sources]
odbcname = MySQL
T2 = MSSQL
[odbcname]
Driver = /usr/lib/odbc/libmyodbc.so
Description = MyODBC 3.51 Driver DSN
SERVER = Foobar
PORT = 3306
USER = Foo
Password = Bar
Database = Foobar
OPTION = 3
SOCKET =
[T2]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
SERVER = FOOBAR
PORT = 1433
USER = Foo
Password = Bar
Database = Foobar
OPTION = 3
SOCKET =
[Default]
Driver = /usr/local/lib/libmyodbc3.so
Description = MyODBC 3.51 Driver DSN
SERVER = FOOBAR
PORT = 3306
USER = foo
Password = bar
Database = FOOBAR
OPTION = 3
SOCKET =
</code></pre>
<p>The following is my /etc/odbcinst.ini</p>
<pre><code>[FreeTDS]
Description=FreeTDS Driver
Driver=/usr/lib/odbc/libtdsodbc.so
Setup=/usr/lib/odbc/libtdsS.so
CPTimeout=
CPReuse=
FileUsage=1
</code></pre>
<p>The following is my freetds.conf</p>
<pre><code># This file is installed by FreeTDS if no file by the same
# name is found in the installation directory.
#
# For information about the layout of this file and its settings,
# see the freetds.conf manpage "man freetds.conf".
# Global settings are overridden by those in a database
# server specific section
[global]
# TDS protocol version
; tds version = 4.2
# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
; dump file = /tmp/freetds.log
; debug flags = 0xffff
# Command and connection timeouts
; timeout = 10
; connect timeout = 10
# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
#text size = 64512
[T2]
host = FOOBAR
port = 1433
tds version = 7.0
client charset = UTF-8
text size = 20971520
[global]
# TDS protocol version
tds version = 7.0
</code></pre>
<p>And my Python test file just for good measure</p>
<pre><code>import pyodbc
import sys
try:
#tempsystrends = pyodbc.connect('DRIVER=FreeTDS;SERVER=FOOBAR;PORT=1433;DATABASE=T2;UID=FOO;PWD=bar;TDS_Version=7.0;')
cursor = tempsystrends.cursor()
except pyodbc.Error as e:
print "Error: %s" % (e.args[1])
sys.exit(1)
</code></pre>
| 0 | 1,384 |
Error Using Drive Mount with Google Colab
|
<p>I had been working on Colab using:</p>
<pre class="lang-py prettyprint-override"><code>from google.colab import drive
.mount('/content/gdrive')
</code></pre>
<p>with no problems, until today.</p>
<p>I don't know why this error was raised:</p>
<pre class="lang-py prettyprint-override"><code>Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly&response_type=code
Enter your authorization code:
··········
---------------------------------------------------------------------------
TIMEOUT Traceback (most recent call last)
<ipython-input-4-d05fe204dd76> in <module>()
1 from google.colab import drive
----> 2 drive.mount('/content/gdrive')
4 frames
/usr/local/lib/python3.6/dist-packages/google/colab/drive.py in mount(mountpoint, force_remount, timeout_ms, use_metadata_server)
223 oauth_prompt,
224 problem_and_stopped,
--> 225 drive_exited,
226 ])
227 if case == 0:
/usr/local/lib/python3.6/dist-packages/pexpect/spawnbase.py in expect(self, pattern, timeout, searchwindowsize, async_, **kw)
342 compiled_pattern_list = self.compile_pattern_list(pattern)
343 return self.expect_list(compiled_pattern_list,
--> 344 timeout, searchwindowsize, async_)
345
346 def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1,
/usr/local/lib/python3.6/dist-packages/pexpect/spawnbase.py in expect_list(self, pattern_list, timeout, searchwindowsize, async_, **kw)
370 return expect_async(exp, timeout)
371 else:
--> 372 return exp.expect_loop(timeout)
373
374 def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1,
/usr/local/lib/python3.6/dist-packages/pexpect/expect.py in expect_loop(self, timeout)
179 return self.eof(e)
180 except TIMEOUT as e:
--> 181 return self.timeout(e)
182 except:
183 self.errored()
/usr/local/lib/python3.6/dist-packages/pexpect/expect.py in timeout(self, err)
142 exc = TIMEOUT(msg)
143 exc.__cause__ = None # in Python 3.x we can use "raise exc from None"
--> 144 raise exc
145
146 def errored(self):
TIMEOUT: <pexpect.popen_spawn.PopenSpawn object at 0x7f58fb7ab4e0>
searcher: searcher_re:
0: re.compile('google.colab.drive MOUNTED')
1: re.compile('root@e7a376888b95-b97a84955c154714b7850ceb4ecf0e8e: ')
2: re.compile('(Go to this URL in a browser: https://.*)$')
3: re.compile('Drive File Stream encountered a problem and has stopped')
4: re.compile('drive EXITED')
<pexpect.popen_spawn.PopenSpawn object at 0x7f58fb7ab4e0>
searcher: searcher_re:
0: re.compile('google.colab.drive MOUNTED')
1: re.compile('root@e7a376888b95-b97a84955c154714b7850ceb4ecf0e8e: ')
2: re.compile('(Go to this URL in a browser: https://.*)$')
3: re.compile('Drive File Stream encountered a problem and has stopped')
4: re.compile('drive EXITED')
</code></pre>
<p>As everyone knows, this code opens a new tab where you have to select a Google account, click on the 'Allow' button, and copy a long password to Colab</p>
<p><strong>EDIT:</strong></p>
<p>I tried to do the same in another way with:</p>
<pre class="lang-py prettyprint-override"><code>#Installing PyDrive
!pip install PyDrive
#Importing modules
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
#Authenticating and creating the PyDrive client
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
#Getting the file
downloaded2 = drive.CreateFile({'id':"1QGtoo1wqCP2yrjl8kFu4kTfjWqh3EOdt"}) # replace the id with id of file you want to access
downloaded2.GetContentFile('estructura_cc_felipe.xlsx')
</code></pre>
<p>But it raises this error:</p>
<pre class="lang-py prettyprint-override"><code>Go to the following link in your browser:
https://accounts.google.com/o/oauth2/auth?client_id=32555940559.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&code_challenge=WkM1RS8Flu1_txc3jn4V_FfutgZuRaHSzYbDvs134PM&code_challenge_method=S256&access_type=offline&response_type=code&prompt=select_account
Enter verification code: ··········
---------------------------------------------------------------------------
AuthorizationError Traceback (most recent call last)
<ipython-input-2-bb96e063f8ef> in <module>()
6
7 #Authenticating and creating the PyDrive client
----> 8 auth.authenticate_user()
9 gauth = GoogleAuth()
10 gauth.credentials = GoogleCredentials.get_application_default()
1 frames
/usr/local/lib/python3.6/dist-packages/google/colab/auth.py in authenticate_user(clear_output)
147 context_manager = _output.temporary if clear_output else _noop
148 with context_manager():
--> 149 _gcloud_login()
150 _install_adc()
151 colab_tpu_addr = _os.environ.get('COLAB_TPU_ADDR', '')
/usr/local/lib/python3.6/dist-packages/google/colab/auth.py in _gcloud_login()
97 _os.remove(name)
98 if gcloud_process.returncode:
---> 99 raise _errors.AuthorizationError('Error fetching credentials')
100
101
AuthorizationError: Error fetching credentials
</code></pre>
<p>Does anyone know what is wrong? I have been working for a long time importing files located on my Google drive and never had these problems.</p>
| 0 | 2,674 |
jQuery logical operator not working as expected
|
<p>I have below code which is not working.</p>
<pre><code>var book_id = $('#indexBookSearch');
var tag_id = $('#indexTagSearch');
if((book_id.val() == "") || (tag_id.val() == ""))
{
$('#userMessages').html('<div class="alert alert-info">'+
'<button type="button" class="close" data-dismiss="alert">&times;'+
'</button>'+
'<strong>Information ! </strong> Please select search criteria first.'+
'</div>');
return false;
}
</code></pre>
<p><code>if((book_id.val() == "") || (tag_id.val() == ""))</code> this line is not working if even if either of the field has <code>value</code> inside of it.</p>
<p>Both <code>Book</code> and <code>Tag</code> is <code>select box</code> i have checked their value using <code>console.log()</code> and its coming perfectly.</p>
<p><strong>I have also changed</strong> </p>
<pre><code>if((book_id.val() == "") || (tag_id.val() == ""))
</code></pre>
<p><strong>to</strong> </p>
<pre><code>if(book_id.val() == "" || tag_id.val() == "")
</code></pre>
<p><strong>EDIT</strong></p>
<p>HTML FORM</p>
<pre><code><form id="indexSearchForm" action="books/listTags" method="POST">
<fieldset>
<legend>Search Criteria</legend>
<label>Select Book</label>
<select class="input-large" name="book_id" id="indexBookSearch">
<option value="">--Select--</option>
<option value="109">book 1</option>
</select>
<label>Select Tag</label>
<select class="input-large" name="tag_id" id="indexTagSearch">
<option value="">--Select--</option>
<option value="10">adding</option>
<option value="1">Apples</option>
<option value="39">article</option>
<option value="34">bhg</option>
<option value="40">boon</option>
</select>
<button class="btn btn-primary" type="submit">Submit</button>
</fieldset>
</form>
</code></pre>
<p>jQuery Code</p>
<pre><code>$('#indexSearchForm').submit(function(e)
{
e.preventDefault();
var book_id = $('#indexBookSearch');
var tag_id = $('#indexTagSearch');
if( !book_id.val() || !tag_id.val())
{
$('#userMessages').html('<div class="alert alert-info">'+
'<button type="button" class="close" data-dismiss="alert">&times;</button>'+
'<strong>Information ! </strong> Please select search criteria first.'+
'</div>');
return false;
}
// more process
});
</code></pre>
<p>Thanks.</p>
| 0 | 1,294 |
Can't click anything after i open my Bootstrap modal
|
<p>sorry for the basic question, I'm working on MVC ASP.NET and I'm trying to add a bootstrap modal in my navbar, I run the code, i can see the button i can touch on it, but after it open, the screen is unclickable i have to f5 to click anywhere again, it's the first time i use modals from bootstrap, and search all around google if I have to write some JavaScript code, but everywhere says that you just need jquery , bootstrap.js and .css and nothing else. If I'm missing something just let me know. Thanks, Here is my code.</p>
<p>PD: I have a carousel already working from bootstrap</p>
<pre><code>@if (Session["usuario"] == null)
{
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Ingresar
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">Iniciar Sesión</h4>
</div>
<div class="modal-body">
<form method="post" action="@Url.Action("DoLogin","Usuario")">
<span class="alert-danger">@ViewBag.NoUser</span>
<label for="NombreDeUsuario" class="sr-only">Nombre de Usuario</label>
<input type="text" id="NombreDeUsuario" name="NombreDeUsuario" class="form-control" placeholder="Ingresa tu Usuario" required="" autofocus="" />
<br />
<label for="Contrasena" class="sr-only">Contraseña</label>
<input type="password" id="Contrasena" name="Contrasena" class="form-control" placeholder="Ingresa tu Contraseña" required="" />
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">Ingresar</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
}
</code></pre>
<p>Here is a screenshot of the problem
<a href="https://i.stack.imgur.com/3JjS6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3JjS6.png" alt="enter image description here"></a></p>
| 0 | 1,778 |
How To Add a jFreeChart to a jPanel in a jFrame?
|
<p>I've looked at lots of questions/answers that are similar and found one which is <a href="https://stackoverflow.com/questions/20297961/how-to-add-chartpanel-in-jpanel-inside-a-jframe">exactly the same</a>, but I have not managed to get my program to work. The output is a blank JFrame, it should output a JFrame with a graph(100x200) inside it.</p>
<p>Here is the contained code:</p>
<pre><code>package my.Project;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class ChartTest extends javax.swing.JFrame {
public ChartTest() {
try {
XYSeries Goals = new XYSeries("Goals Scored");
Goals.add(1, 1.0);
Goals.add(2, 3.0);
Goals.add(3, 2.0);
Goals.add(4, 0.0);
Goals.add(5, 3.0);
XYDataset xyDataset = new XYSeriesCollection(Goals);
JFreeChart chart = ChartFactory.createXYLineChart("Goals Scored Over Time", "Fixture Number", "Goals", xyDataset, PlotOrientation.VERTICAL, true, true, false);
JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setVisible(true);
jPanel1.setSize(300, 300);
ChartPanel CP = new ChartPanel(chart);
CP.setPreferredSize(new Dimension(100, 200));
CP.setMouseWheelEnabled(true);
jPanel1.add(CP, BorderLayout.CENTER);
jPanel1.validate();
} catch (Exception e) {
System.out.print("Chart exception:" + e);
}
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChartTest().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
</code></pre>
| 0 | 1,375 |
Why are KD-trees so damn slow for nearest neighbor search in point sets?
|
<p>I am using CGAL's (the latest) KD-tree implementation for searching nearest neighbors in point sets. And also Wikipedia and other resources seem to suggest that KD-trees are the way to go. But somehow they are too slow and Wiki also suggests their worst-case time of O(n), which is far from ideal.</p>
<p>[BEGIN-EDIT]
<strong>I am now using "nanoflann", which is about 100-1000 times faster than the equivalent in CGAL for K-neighbor search. And I am using "Intel Embree" for raycasting, which is about 100-200 times faster than CGAL's AABB trees.</strong>
[END-EDIT]</p>
<p>My task looks like this:</p>
<p>I have a HUGE point set, say like up to a few 100 mio. points!! and their distribution is on surfaces of triangulated geometry (yes, a photon tracer). So one could say that their distribution is 2D in 3D space, because it is sparse in 3D but dense when looking at the surfaces... This could be the problem right? Because to me this seems to trigger the worst-case performance of a KD-tree which probably could deal much better with 3D dense point sets...</p>
<p>CGAl is quite good at what it does, so I have a bit doubt that their implementation just sucks. Their AABB tree I am using for raytracing burns a straight billion raytraces in a few mintues in the ground... That is remarkable I guess. But their KD-tree on the other hand can't even deal with a mio. points and 250k samples (point queries) in any reasonable time...</p>
<p>I came up with two solutions which kick the crap out of KD-trees:</p>
<p>1) Use texture maps to store the photons in a linked list on the geometry. This is always an O(1) operation, since you have to do the raycast anyway...</p>
<p>2) Use view dependent sliced hashsets. That is the farther away you get, the more coarse the hashsets get. So basically you can think of a 1024x1024x1024 raster in NDC coordinates, but with hashsets, to save memory in sparse areas. This basically has O(1) complexity and can be parallelized efficiently, both for inserts (micro-sharding) and queries (lock-free). </p>
<p>The former solution has the disadvantage that it is close to impossible to average over neighboring photon lists, which is important in darker regions to avoid noise.
The latter solution doesn't have this problem and should be on par feature wise with KD-trees, just that it has O(1) worst case performance, lol.</p>
<p>So what do you think? Bad KD-tree implementation? If not, is there something "better" than a KD-tree for bounded nearest neighbor queries? I mean I have nothing against my second solution above, but a "proven" data-structure that delivers similar performance would be nicer!</p>
<p>Thanks!</p>
<p>Here is the code (not compilable though) that I used:</p>
<pre><code>#include "stdafx.h"
#include "PhotonMap.h"
#pragma warning (push)
#pragma warning (disable: 4512 4244 4061)
#pragma warning (disable: 4706 4702 4512 4310 4267 4244 4917 4820 4710 4514 4365 4350 4640 4571 4127 4242 4350 4668 4626)
#pragma warning (disable: 4625 4265 4371)
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Orthogonal_incremental_neighbor_search.h>
#include <CGAL/basic.h>
#include <CGAL/Search_traits.h>
#include <CGAL/point_generators_3.h>
#pragma warning (pop)
struct PhotonicPoint
{
float vec[3];
const Photon* photon;
PhotonicPoint(const Photon& photon) : photon(&photon)
{
vec[0] = photon.hitPoint.getX();
vec[1] = photon.hitPoint.getY();
vec[2] = photon.hitPoint.getZ();
}
PhotonicPoint(Vector3 pos) : photon(nullptr)
{
vec[0] = pos.getX();
vec[1] = pos.getY();
vec[2] = pos.getZ();
}
PhotonicPoint() : photon(nullptr) { vec[0] = vec[1] = vec[2] = 0; }
float x() const { return vec[0]; }
float y() const { return vec[1]; }
float z() const { return vec[2]; }
float& x() { return vec[0]; }
float& y() { return vec[1]; }
float& z() { return vec[2]; }
bool operator==(const PhotonicPoint& p) const
{
return (x() == p.x()) && (y() == p.y()) && (z() == p.z()) ;
}
bool operator!=(const PhotonicPoint& p) const
{
return ! (*this == p);
}
};
namespace CGAL
{
template <>
struct Kernel_traits<PhotonicPoint>
{
struct Kernel
{
typedef float FT;
typedef float RT;
};
};
}
struct Construct_coord_iterator
{
typedef const float* result_type;
const float* operator()(const PhotonicPoint& p) const
{
return static_cast<const float*>(p.vec);
}
const float* operator()(const PhotonicPoint& p, int) const
{
return static_cast<const float*>(p.vec+3);
}
};
typedef CGAL::Search_traits<float, PhotonicPoint, const float*, Construct_coord_iterator> Traits;
typedef CGAL::Orthogonal_incremental_neighbor_search<Traits> NN_incremental_search;
typedef NN_incremental_search::iterator NN_iterator;
typedef NN_incremental_search::Tree Tree;
struct PhotonMap_Impl
{
Tree tree;
PhotonMap_Impl(const PhotonAllocator& allocator) : tree()
{
int counter = 0, maxCount = allocator.GetAllocationCounter();
for(auto& list : allocator.GetPhotonLists())
{
int listLength = std::min((int)list.size(), maxCount - counter);
counter += listLength;
tree.insert(std::begin(list), std::begin(list) + listLength);
}
tree.build();
}
};
PhotonMap::PhotonMap(const PhotonAllocator& allocator)
{
impl = std::make_shared<PhotonMap_Impl>(allocator);
}
void PhotonMap::Sample(Vector3 where, float radius, int minCount, std::vector<const Photon*>& outPhotons)
{
NN_incremental_search search(impl->tree, PhotonicPoint(where));
int count = 0;
for(auto& p : search)
{
if((p.second > radius) && (count > minCount) || (count > 50))
break;
count++;
outPhotons.push_back(p.first.photon);
}
}
</code></pre>
| 0 | 2,278 |
OnScreen keyboard opens automatically when Activity starts
|
<p>When my Activity with a <code>ScrollView</code> layout and <code>EditText</code>s starts, the <code>EditText</code>s get focus and the Android OnScreen keyboard opens.</p>
<p>How I can avoid that?</p>
<p>When I was using <code>LinearLayout</code> and <code>RelativeLayout</code> without the <code>ScrollView</code> it doesn't happen.</p>
<p>I've tried it this way, and it works, but it's not a good way to do it:</p>
<pre><code>TextView TextFocus = (TextView) findViewById(R.id.MovileLabel);
TextFocus.setFocusableInTouchMode(true);
TextFocus.requestFocus();
</code></pre>
<p>Next you have an example of some of my layouts with this problem, when this Activity starts, focus goes to the first <code>EditText</code>, <em>Description</em> and the Android keyboard opens automatically, this is very annoying.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10px">
<RelativeLayout
android:gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/UserLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="13px"
android:text="@string/userlabel"/>
<TextView
android:id="@+id/User"
android:layout_alignBaseline="@id/UserLabel"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test"/>
</RelativeLayout>
<View
android:layout_gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#808080"
android:layout_marginTop="5px"
android:layout_marginBottom="12px"/>
<RelativeLayout
android:gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/DescriptionLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/desclabel"
android:layout_marginTop="13px"/>
<EditText
android:id="@+id/Description"
android:layout_alignBaseline="@id/DescriptionLabel"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="180px"/>
</RelativeLayout>
<RelativeLayout
android:gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/EmailLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/emaillabel"
android:layout_marginTop="13px"/>
<EditText
android:id="@+id/Email"
android:layout_alignBaseline="@+id/EmailLabel"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="180px"/>
</RelativeLayout>
<RelativeLayout
android:gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/MovilePhoneLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/movilephonelabel"
android:layout_marginTop="13px"/>
<EditText
android:id="@+id/MovilePhone"
android:layout_alignBaseline="@+id/MovilePhoneLabel"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="180px"/>
</RelativeLayout>
<View
android:layout_gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#808080"
android:layout_marginTop="5px"
android:layout_marginBottom="10px"/>
<RelativeLayout
android:gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/applybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/apply"
android:width="100px"
android:layout_marginLeft="40dip"/>
<Button
android:id="@+id/cancelbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:width="100px"
android:layout_alignBaseline="@+id/applybutton"
android:layout_alignParentRight="true"
android:layout_marginRight="40dip"/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</code></pre>
| 0 | 2,975 |
Dynamically adding rows to datatable using ajax with pagination and sorting
|
<p>I am trying to achieve <a href="https://almsaeedstudio.com/themes/AdminLTE/pages/tables/data.html" rel="nofollow noreferrer">https://almsaeedstudio.com/themes/AdminLTE/pages/tables/data.html</a> - "Data Table With Full Features"</p>
<p>When I added tbody statically, pagination and sorting works fine but when I add tbody using jquery as given below, rows are added but pagination and sorting fails.</p>
<p><strong>HTML</strong></p>
<pre><code><table id="tblItems">
<thead>
<tr>
<th>code</th>
<th>Name</th>
<th>Description</th>
<th>Image</th>
<th>Parent</th>
<th>Location</th>
<th>Category</th>
</tr>
</thead>
</table>
</code></pre>
<p><strong>jquery</strong></p>
<pre><code>$(document).ready(function() {
$('#tblItems').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"sDom": 'lfrtip'
});
$('#tblItems').append('<tbody><tr><td>asdsa34id</td><td> asdsa34id </td><td>asdsa34id </td><td> asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td></tr></tbody>');
});
</code></pre>
<p><a href="https://jsfiddle.net/techjerk2013/vwpsxhaL/" rel="nofollow noreferrer">https://jsfiddle.net/techjerk2013/vwpsxhaL/</a></p>
<p><strong>Updated Code</strong></p>
<p>The updated code doesn't populate the table though there are data from the response. Though I set the deferRender to true, still the datatable is empty.</p>
<pre><code>$(document).ready(function() {
PopulateItemsTable();
BindTable();
});
function BindTable() {
$("#tblItems").DataTable({
"deferRender": true,
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"sDom": 'lfrtip'
});
}
function PopulateItemsTable() {
var txt = "";
$.ajax({
type: "POST",
url: "Item.aspx/Search",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var jsonObject = JSON.parse(response.d);
if (jsonObject) {
var len = jsonObject.length;
if (len > 0) {
for (var i = 0; i < len; i++) {
if (jsonObject[i].Id) {
Id = jsonObject[i].Id;
}
else {
Id = '';
}
if (jsonObject[i].Name) {
Name = jsonObject[i].Name;
}
else {
Name = '';
}
if (jsonObject[i].Description) {
Description = jsonObject[i].Description;
}
else {
Description = '';
}
if (jsonObject[i].Image) {
Image = jsonObject[i].Image;
}
else {
Image = '';
}
if (jsonObject[i].Parent) {
Parent = jsonObject[i].Parent;
}
else {
Parent = '';
}
if (jsonObject[i].Location) {
Location = jsonObject[i].Location;
}
else {
Location = '';
}
Category = '';
txt += "<tr><td>" + Id + "</td><td>" + Name + "</td><td>" + Description + "</td><td>" + Image + "</td><td>" + Parent + "</td><td>" + Location + "</td><td>" + Category + "</td></tr>";
$('#tblItems').append('<tbody>' + txt + '</tbody>');
}
}
else {
$("#tblItems").append("No records found");
}
}
},
failure: function () {
$("#tblItems").append(" Error when fetching data please contact administrator");
}
});
}
</code></pre>
<h1>Answer</h1>
<p>With the help of people answered below, the code below works as expected.</p>
<pre><code><script type="text/javascript">
var myTable;
$(document).ready(function () {
BindItemTable();
PopulateItemsTable();
});
function BindItemTable() {
myTable = $("#tblItems").DataTable({
"deferRender": true,
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"sDom": 'lfrtip'
});
}
function PopulateItemsTable() {
$.ajax({
type: "POST",
url: "ItemManagement.aspx/SearchIdList",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var jsonObject = JSON.parse(response.d);
var result = jsonObject.map(function (item) {
var result = [];
result.push(item.Id);
result.push(item.Name);
result.push(item.Description);
result.push(item.Image);
result.push(item.Parent);
result.push(item.Location);
result.push("");
return result;
});
myTable.rows.add(result);
myTable.draw();
},
failure: function () {
$("#tblItems").append(" Error when fetching data please contact administrator");
}
});
}
</script>
</code></pre>
| 0 | 3,738 |
@ModelAttribute controller spring-mvc mocking
|
<p>I want to test a controller which is using <code>@ModelAttribute</code> for one of its method arguments.</p>
<pre><code>public String processSaveAction(@ModelAttribute("exampleEntity") ExampleEntity exampleEntity)
</code></pre>
<p><code>@ModelAttribute</code> method <code>getExampleEntity</code> is using <code>@RequestParam</code>:</p>
<pre><code>@ModelAttribute("exampleEntity")
public ExampleEntity getExampleEntity(@RequestParam(value = "id", required = true) ExampleEntity exampleEntity) {
</code></pre>
<p>My controller is using <code>WebDataBinder</code> to call a factory, which returns an object based on param "id".</p>
<pre><code>@Controller
public class ExampleController(){
@Autowired private IdEditorFactory idEditorFactory;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(ExampleEntity.class, idEditorFactory.createEditor(ExampleEntity.class));
}
@ModelAttribute("exampleEntity")
public ExampleEntity getExampleEntity(@RequestParam(value = "id", required = true) ExampleEntity exampleEntity) {
//Irrelevant operations
return exampleEntity;
}
@RequestMapping(method = RequestMethod.POST, params = "action=save")
public String processSaveAction(
@RequestParam(value = "confirmed") String exampleString,
@ModelAttribute("exampleEntity") ExampleEntity exampleEntity,
BindingResult result, HttpServletRequest request)
throws IOException {
boolean success = editorProcessor.processSaveAction(exampleString,
exampleEntity, result, request);
return success ? getSuccessView(exampleEntity) : VIEW_NAME;
}
}
</code></pre>
<p>And my test:</p>
<pre><code>@WebAppConfiguration
public class ExampleControllerTest{
@Mock private EditorProcessor editorProcessor;
@Mock private IdEditorFactory idEditorFactory;
@InjectMocks private ExampleController exampleController;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(exampleController).build();
WebDataBinder webDataBinder = new WebDataBinder(ExampleEntity.class);
webDataBinder.registerCustomEditor(ExampleEntity.class, idEditorFactory.createEditor(ExampleEntity.class));
}
@Test
public void shouldProcessSaveAction() throws Exception {
// given
BindingResult result = mock(BindingResult.class);
ExampleEntity exampleEntity = mock(ExampleEntity.class);
HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
given(editorProcessor.processSaveAction("confirmed", exampleEntity, result, httpServletRequest)).willReturn(true);
// when
ResultActions perform = mockMvc.perform(post("/").sessionAttr("exampleEntity", exampleEntity)
.param("id", "123456"
.param("action","save"));
// then
perform.andDo(print())
.andExpect(status().isOk());
}
}
</code></pre>
<p>I want to somehow mock <code>getExampleEntity()</code> so that every time I perform a POST with parameter "id", I receive a mocked object ("exampleEntity") for the test.</p>
<p>I could introduce <code>@Binding</code> to the test, but then I would have to mock many levels of methods (like initBinder -> idEditoryFactory-> editor -> hibernateTemplate and so on) only to get an entity from some source (for example, a database).</p>
| 0 | 1,272 |
Import Classes Into Java Files
|
<p>I am currently learning to develop in Java and am interested in creating Java classes that other users can import into their program and use. Yes, I know my example class is simple and stupid but I want to learn the concept and start making more complex classes that people can import into their projects.</p>
<p>I created a simple "<em>Logger</em>" class that when called logs both text to the console and to a text file for readability. You can call this class by using the following commands...</p>
<pre><code>Logger Logger = new Logger();
Logger.create();
Logger.log("This text will be logged to the console and log.log");
</code></pre>
<p>See below for the <strong>Logger</strong> class.</p>
<pre><code>import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Logger {
FileWriter fw;
BufferedWriter br;
File file = new File("log.log");
boolean fileExists = file.exists();
public void log(String message) {
try {
fw = new FileWriter(file, true);
br = new BufferedWriter(fw);
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
if(hour > 12)
hour = hour - 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int millis = cal.get(Calendar.MILLISECOND);
int ampm = cal.get(Calendar.AM_PM);
String ampmString;
if(ampm == 1)
ampmString = "PM";
else
ampmString = "AM";
String now = String.format("%02d:%02d:%02d.%03d %s", hour, minute, second, millis, ampmString);
System.out.println(now + " - " + message);
br.write(now + " - " + message);
br.newLine();
br.close();
} catch (Exception err) {
System.out.println("Error");
}
}
public void create() {
try {
fw = new FileWriter(file, true);
br = new BufferedWriter(fw);
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-YYYY");
String dateString = sdf.format(new Date());
if(file.length() != 0)
br.newLine();
System.out.println("Log: " + file.getAbsolutePath());
br.write("--------------------" + dateString + "--------------------");
br.newLine();
br.close();
} catch (Exception err) {
System.out.println("Error");
}
}
}
</code></pre>
<p>The issue I am having is in order to use this class I have to add it to every single project I create and want to use this. Is there a way I can add an import like, <code>mydomain.Logger.*;</code> and be able to access this class and the methods it contains?</p>
<p>My question, <strong>What is the best way to allow anyone to import/use my Logger class in the simplest way? What steps do I need to take to allow them to do this?</strong></p>
| 0 | 1,455 |
java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of
|
<p>I've created an app that loads a question from my web services, and it works fine. But, sometimes it crashes and I do not get the reason why this is happening, especially because I have also given it the required permissions. It works fine, but at random, it crashes and gives me this report.</p>
<pre><code>private void sendContinentQuestions(int id) {
// TODO Auto-generated method stub
//Get the data (see above)
JSONArray json = getJSONfromURL(id);
try{
for(int i=0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = json.getJSONObject(i);
longitude":"72.5660200"
String category_id = jObject.getString("category_id");
String question_id = jObject.getString("question_id");
String question_name = jObject.getString("question_name");
String latitude = jObject.getString("latitude");
String longitude = jObject.getString("longitude");
String answer = jObject.getString("answer");
String ansLatLng = latitude+"|"+longitude ;
Log.v("## data:: ###",question_id+"--"+question_name+"-cat id-"+category_id+"--ansLatLng "+ansLatLng+" answer: "+answer);
all_question.add(new QuestionData(game_id,category_id,question_id,question_name,ansLatLng,answer));
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
public JSONArray getJSONfromURL(int id){
String response = "";
URL url;
try {
url = new URL(Consts.GET_URL+"index.php/Api/getQuestion?cat_id="+id);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
InputStream is = http.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
response = br.readLine();
Log.v("###Response :: ###",response);
http.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//try parse the string to a JSON object
JSONArray jArray = null;
try{
jArray = new JSONArray(response);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
</code></pre>
<hr>
<pre><code>11-13 15:02:52.307: W/System.err(8012): java.net.UnknownHostException: Unable to resolve host "www.xyz.com": No address associated with hostname
11-13 15:02:52.317: W/System.err(8012): at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
11-13 15:02:52.317: W/System.err(8012): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-13 15:02:52.317: W/System.err(8012): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
11-13 15:02:52.317: W/System.err(8012): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
11-13 15:02:52.327: W/System.err(8012): at com.abc.xyz.ContinentActivity.getJSONfromURL(ContinentActivity.java:400)
11-13 15:02:52.327: W/System.err(8012): at com.abc.xyz.ContinentActivity.sendContinentQuestions(ContinentActivity.java:327)
11-13 15:02:52.327: W/System.err(8012): at com.abc.xyz.ContinentActivity.access$2(ContinentActivity.java:323)
11-13 15:02:52.327: W/System.err(8012): at com.abc.xyz.ContinentActivity$LoadQuestions.doInBackground(ContinentActivity.java:254)
11-13 15:02:52.327: W/System.err(8012): at com.abc.xyz.ContinentActivity$LoadQuestions.doInBackground(ContinentActivity.java:1)
11-13 15:02:52.327: W/System.err(8012): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-13 15:02:52.327: W/System.err(8012): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-13 15:02:52.327: W/System.err(8012): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-13 15:02:52.327: W/System.err(8012): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-13 15:02:52.337: W/System.err(8012): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-13 15:02:52.337: W/System.err(8012): at java.lang.Thread.run(Thread.java:841)
11-13 15:02:52.337: W/System.err(8012): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
11-13 15:02:52.337: W/System.err(8012): at libcore.io.Posix.getaddrinfo(Native Method)
11-13 15:02:52.337: W/System.err(8012): at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
11-13 15:02:52.337: W/System.err(8012): at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
11-13 15:02:52.337: W/System.err(8012): ... 24 more
11-13 15:02:52.337: E/log_tag(8012): Error parsing data org.json.JSONException: End of input at character 0 of
11-13 15:02:52.337: W/dalvikvm(8012): threadid=194: thread exiting with uncaught exception (group=0x417c1700)
11-13 15:02:52.337: E/AndroidRuntime(8012): FATAL EXCEPTION: AsyncTask #5
11-13 15:02:52.337: E/AndroidRuntime(8012): java.lang.RuntimeException: An error occured while executing doInBackground()
11-13 15:02:52.337: E/AndroidRuntime(8012): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-13 15:02:52.337: E/AndroidRuntime(8012): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-13 15:02:52.337: E/AndroidRuntime(8012): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-13 15:02:52.337: E/AndroidRuntime(8012): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-13 15:02:52.337: E/AndroidRuntime(8012): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-13 15:02:52.337: E/AndroidRuntime(8012): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-13 15:02:52.337: E/AndroidRuntime(8012): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-13 15:02:52.337: E/AndroidRuntime(8012): at java.lang.Thread.run(Thread.java:841)
11-13 15:02:52.337: E/AndroidRuntime(8012): Caused by: java.lang.NullPointerException
11-13 15:02:52.337: E/AndroidRuntime(8012): at com.abc.xyz.ContinentActivity.sendContinentQuestions(ContinentActivity.java:328)
11-13 15:02:52.337: E/AndroidRuntime(8012): at com.abc.xyz.ContinentActivity.access$2(ContinentActivity.java:323)
11-13 15:02:52.337: E/AndroidRuntime(8012): at com.abc.xyz.ContinentActivity$LoadQuestions.doInBackground(ContinentActivity.java:254)
11-13 15:02:52.337: E/AndroidRuntime(8012): at com.abc.xyz.ContinentActivity$LoadQuestions.doInBackground(ContinentActivity.java:1)
11-13 15:02:52.337: E/AndroidRuntime(8012): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-13 15:02:52.337: E/AndroidRuntime(8012): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
</code></pre>
| 0 | 3,463 |
Is it fine if first response is private with AppCache (Symfony2)?
|
<p>I'm trying to use http caching. In my controller I'm setting a response as follows: </p>
<pre><code>$response->setPublic();
$response->setMaxAge(120);
$response->setSharedMaxAge(120);
$response->setLastModified($lastModifiedAt);
</code></pre>
<p><strong>dev mode</strong></p>
<p>In dev environment first response is a 200 with following headers:</p>
<pre><code>cache-control:max-age=120, public, s-maxage=120
last-modified:Wed, 29 Feb 2012 19:00:00 GMT
</code></pre>
<p>For next 2 minutes every response is a 304 with following headers:</p>
<pre><code>cache-control:max-age=120, public, s-maxage=120
</code></pre>
<p>This is basically what I expect it to be.</p>
<p><strong>prod mode</strong></p>
<p>In prod mode response headers are different. Note that in app.php I wrap the kernel in AppCache.</p>
<p>First response is a 200 with following headers:</p>
<pre><code>cache-control:must-revalidate, no-cache, private
last-modified:Thu, 01 Mar 2012 11:17:35 GMT
</code></pre>
<p>So it's a private no-cache response.</p>
<p>Every next request is pretty much what I'd expect it to be; a 304 with following headers:</p>
<pre><code>cache-control:max-age=120, public, s-maxage=120
</code></pre>
<p><strong>Should I worry about it? Is it an expected behaviour?</strong> </p>
<p><strong>What will happen if I put Varnish or Akamai server in front of it?</strong></p>
<p>I did a bit of debugging and I figured that response is private because of last-modified header. HttpCache kernel <a href="https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php#L210">uses EsiResponseCacheStrategy</a> to update the cached response (<a href="https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php#L171">HttpCache::handle()</a> method). </p>
<pre><code>if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->esiCacheStrategy->update($response);
}
</code></pre>
<p>EsiResponseCacheStrategy <a href="https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/HttpCache/EsiResponseCacheStrategy.php#L42">turns a response into non cacheable</a> if it uses either Last-Response or ETag (<a href="https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/HttpCache/EsiResponseCacheStrategy.php#L40">EsiResponseCacheStrategy::add()</a> method):</p>
<pre><code>if ($response->isValidateable()) {
$this->cacheable = false;
} else {
// ...
}
</code></pre>
<p><a href="https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Response.php#L407">Response::isValidateable()</a> returns true if Last-Response or ETag header is present.</p>
<p>It results in <a href="https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/HttpCache/EsiResponseCacheStrategy.php#L62">overwriting the Cache-Control header</a> (<a href="https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/HttpCache/EsiResponseCacheStrategy.php#L55">EsiResponseCacheStrategy::update()</a> method):</p>
<pre><code>if (!$this->cacheable) {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
return;
}
</code></pre>
<p>I asked this question on Symfony2 user group but I didn't get an answer so far: <a href="https://groups.google.com/d/topic/symfony2/6lpln11POq8/discussion">https://groups.google.com/d/topic/symfony2/6lpln11POq8/discussion</a></p>
<p><strong>Update.</strong></p>
<p>Since I no longer have access to the original code I tried to <a href="https://github.com/jakzal/symfony-standard/blob/cache/src/Acme/DemoBundle/Controller/DemoController.php#L62">reproduce the scenario with the latest Symfony standard edition</a>.</p>
<p>Response headers are more consistent now, but still seem to be wrong. </p>
<p>As soon as I set a <code>Last-Modified</code> header on the response, the first response made by a browser has a: </p>
<pre><code>Cache-Control:must-revalidate, no-cache, private
</code></pre>
<p>Second response has an expected:</p>
<pre><code>Cache-Control:max-age=120, public, s-maxage=120
</code></pre>
<p>If I avoid sending <code>If-Modified-Since</code> header, every request returns <code>must-revalidate, no-cache, private</code>.</p>
<p>It doesn't matter if the request was made in <code>prod</code> or <code>dev</code> environment anymore.</p>
| 0 | 1,578 |
mat-table angular 6 not showing any data despite having the dataSource
|
<p>I want to show a list through Angular material design's data table mat-table.
Here is my component:</p>
<pre><code>import { LeaveapplicationService } from './../../services/leaveapplication.service';
import { leaveapplication } from './../../models/leaveapplication';
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
// import { DataSource } from '@angular/cdk/table';
@Component({
selector: 'app-leaveapplication-list',
templateUrl: './leaveapplication-list.component.html',
styleUrls: ['./leaveapplication-list.component.scss']
})
export class LeaveapplicationListComponent implements OnInit {
leaveApplications: leaveapplication[];
displayedColumns: ['id', 'applicant', 'manager', 'leavetype', 'start', 'end', 'return', 'status'];
dataSource: MatTableDataSource<leaveapplication>;
constructor(private leaveApplicationService: LeaveapplicationService) { }
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.leaveApplicationService.getLeaveApplications().subscribe(leaveapplications => {
this.leaveApplications = leaveapplications;
this.dataSource = new MatTableDataSource<leaveapplication>(this.leaveApplications);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
console.log(this.dataSource);
});
}
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
this.dataSource.filter = filterValue;
}
}
</code></pre>
<p>The leaveapplication interface:</p>
<pre><code>export interface leaveapplication {
id: number;
applicant: string;
manager: string;
startdate: Date;
enddate: Date;
returndate: Date;
leavetype: string;
status: string;
}
</code></pre>
<p>I am getting the dataSource properly in the console:</p>
<p><a href="https://i.stack.imgur.com/8ELb3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8ELb3.png" alt="enter image description here"></a></p>
<p>But the mat-table return empty cells:</p>
<p><a href="https://i.stack.imgur.com/Qbt1b.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Qbt1b.png" alt="enter image description here"></a></p>
<p>Here is my template:</p>
<pre><code><mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<mat-table #table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Form ID </th>
<td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.id}} </td>
</ng-container>
<ng-container matColumnDef="applicant">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Applicant </th>
<td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.applicant}} </td>
</ng-container>
<ng-container matColumnDef="manager">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Manager </th>
<td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.manager}} </td>
</ng-container>
<ng-container matColumnDef="leavetype">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Leave Type </th>
<td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.leaveType}} </td>
</ng-container>
<ng-container matColumnDef="start">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Start Date </th>
<td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.startDate | date:'dd-MM-yyyy'}} </td>
</ng-container>
<ng-container matColumnDef="end">
<th mat-header-cell *matHeaderCellDef mat-sort-header> End Date </th>
<td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.endDate | date:'dd-MM-yyyy'}} </td>
</ng-container>
<ng-container matColumnDef="return">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Return Date </th>
<td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.returnDate | date:'dd-MM-yyyy'}} </td>
</ng-container>
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Status </th>
<td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.status}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</mat-table>
<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
</code></pre>
<p>Why am I not getting the mat-table populated? Is it because of the asynchronous nature of the response?</p>
| 0 | 1,900 |
jquery .prop('disabled', true) not working
|
<p>I am attempting to toggle <code>disabled = true|false</code> on a <code><input type="text"></code>, using a checkbox. I am able to get the value of the input, but I cannot set the input to disabled.</p>
<p>my jquery/js code</p>
<pre><code><script>
$(function () {
$('.date').datepicker();
$('body').on('change', '.housing', function () {
if ($(this).val() == 'dorms') {
$(this).parent().next(".dorms").show();
} else {
$(this).parent().siblings(".dorms").hide();
}
});
$('body').on('change', '.single', function () {
if ($(this).checked) {
$('#echo1').text($(this).prev(".roommate").val()); // this works
$(this).prev(".roommate").val(''); // does not empty the input
$(this).prev(".roommate").disabled = true; // does not set to disabled
$(this).prev(".roommate").prop('disabled', true); // does not set to disabled
$('#echo2').text($(this).prev(".roommate").prop('disabled')); // always says false
} else {
$('#echo1').text($(this).prev(".roommate").val()); // this works
$(this).prev(".roommate").disabled = false; // always stays false
$('#echo2').text($(this).prev(".roommate").prop('disabled')); // always says false
}
});
});
</script>
</code></pre>
<p>my html code</p>
<pre><code><div class="registration_housing particpant_0" data-sync="0">
<div>
<label class="particpant_0"></label>
</div>
<div>
<label>Off Campus (not included)</label>
<input type="radio" name="housing[0]" value="none" class="housing" />
</div>
<div>
<label>On Campus</label>
<input type="radio" name="housing[0]" value="dorms" class="housing" />
</div>
<div class="dorms" style="display:none;">
<div>
<label>Checkin:</label>
<input type="text" name="check_in[0]" class="date" />
</div>
<div>
<label>Checkout:</label>
<input type="text" name="check_out[0]" class="date" />
</div>
<div>
<label>Roommate:</label>
<input type="text" name="roommate[0]" class="roommate" />
<input type="checkbox" name="roommate_single[0]" value="single" class="single" />check for singe-occupancy</div>
</div>
<div class="line">
<hr size="1" />
</div>
</div>
<div>
<label id="echo1"></label>
</div>
<div>
<label id="echo2"></label>
</div>
</code></pre>
<p>you can see this at <a href="http://jsfiddle.net/78dQE/1/">http://jsfiddle.net/78dQE/1/</a></p>
<p>Any idea why I can get the value of <code>(".roommate")</code> - ie. <code>$(this).prev(".roommate").val()</code><br>
but<br>
<code>$(this).prev(".roommate").disabled = true;</code><br>
OR<br>
<code>$(this).prev(".roommate").prop('disabled', true);</code><br>
will not set <code>(".roommate")</code> to disabled?</p>
| 0 | 1,559 |
apache zeppelin is started but there is connection error in localhost:8080
|
<p>after successfully build apache zepellin on Ubuntu 14, I start zeppelin and it says successfully started but when I go to localhost:8080 Firefox shows unable to connect error like it didn't started but when I check Zeppelin status from terminal it says running and also I just copied config files templates so the config files are the default </p>
<h2>update</h2>
<p>changed the port to 8090 , here is the config file , but no change in result </p>
<pre><code><?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>zeppelin.server.addr</name>
<value>0.0.0.0</value>
<description>Server address</description>
</property>
<property>
<name>zeppelin.server.port</name>
<value>8090</value>
<description>Server port. port+1 is used for web socket.</description>
</property>
<property>
<name>zeppelin.websocket.addr</name>
<value>0.0.0.0</value>
<description>Testing websocket address</description>
</property>
<!-- If the port value is negative, then it'll default to the server
port + 1.
-->
<property>
<name>zeppelin.websocket.port</name>
<value>-1</value>
<description>Testing websocket port</description>
</property>
<property>
<name>zeppelin.notebook.dir</name>
<value>notebook</value>
<description>path or URI for notebook persist</description>
</property>
<property>
<name>zeppelin.notebook.storage</name>
<value>org.apache.zeppelin.notebook.repo.VFSNotebookRepo</value>
<description>notebook persistence layer implementation</description>
</property>
<property>
<name>zeppelin.interpreter.dir</name>
<value>interpreter</value>
<description>Interpreter implementation base directory</description>
</property>
<property>
<name>zeppelin.interpreters</name>
<value>org.apache.zeppelin.spark.SparkInterpreter,org.apache.zeppelin.spark.PySparkInterpreter,org.apache.zeppelin.spark.SparkSqlInterpreter,org.apache.zeppelin.spark.DepInterpreter,org.apache.zeppelin.markdown.Markdown,org.apache.zeppelin.angular.AngularInterpreter,org.apache.zeppelin.shell.ShellInterpreter,org.apache.zeppelin.hive.HiveInterpreter,org.apache.zeppelin.tajo.TajoInterpreter,org.apache.zeppelin.flink.FlinkInterpreter,org.apache.zeppelin.ignite.IgniteInterpreter,org.apache.zeppelin.ignite.IgniteSqlInterpreter</value>
<description>Comma separated interpreter configurations. First interpreter become a default</description>
</property>
<property>
<name>zeppelin.ssl</name>
<value>false</value>
<description>Should SSL be used by the servers?</description>
</property>
<property>
<name>zeppelin.ssl.client.auth</name>
<value>false</value>
<description>Should client authentication be used for SSL connections?</description>
</property>
<property>
<name>zeppelin.ssl.keystore.path</name>
<value>keystore</value>
<description>Path to keystore relative to Zeppelin configuration directory</description>
</property>
<property>
<name>zeppelin.ssl.keystore.type</name>
<value>JKS</value>
<description>The format of the given keystore (e.g. JKS or PKCS12)</description>
</property>
<property>
<name>zeppelin.ssl.keystore.password</name>
<value>change me</value>
<description>Keystore password. Can be obfuscated by the Jetty Password tool</description>
</property>
<!--
<property>
<name>zeppelin.ssl.key.manager.password</name>
<value>change me</value>
<description>Key Manager password. Defaults to keystore password. Can be obfuscated.</description>
</property>
-->
<property>
<name>zeppelin.ssl.truststore.path</name>
<value>truststore</value>
<description>Path to truststore relative to Zeppelin configuration directory. Defaults to the keystore path</description>
</property>
<property>
<name>zeppelin.ssl.truststore.type</name>
<value>JKS</value>
<description>The format of the given truststore (e.g. JKS or PKCS12). Defaults to the same type as the keystore type</description>
</property>
<!--
<property>
<name>zeppelin.ssl.truststore.password</name>
<value>change me</value>
<description>Truststore password. Can be obfuscated by the Jetty Password tool. Defaults to the keystore password</description>
</property>
-->
</configuration>
</code></pre>
<p>and here are the ports which are in listening state after zeppelin is started</p>
<pre><code>tcp6 0 0 :::8081 :::* LISTEN
tcp6 0 0 ::1:631 :::* LISTEN
tcp6 0 0 :::8091 :::* LISTEN
tcp6 0 0 :::9001 :::* LISTEN
</code></pre>
<p>and <code>Zeppelin is running [ OK ]
</code> is the response I get when I run command <code>bin/zeppelin-daemon.sh status</code> </p>
| 0 | 2,395 |
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
|
<p>I am getting this exception when I call a DAO method which uses <code>SessionFactory.getCurrentSession()</code>. The DAO class is annotated with <code>@Transactional</code> and I also have <code><tx:annotation-driven/></code> declared in the application context configuration file.</p>
<p>I can call my DAO methods which perform HQL queries, but whenever I call a DAO method which first gets the Hibernate session then I run into this exception:</p>
<pre><code>SEVERE: Failed to save the object.
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:622)
at gov.noaa.ncdc.cmb.persistence.dao.GenericDaoHibernateImpl.getCurrentSession(GenericDaoHibernateImpl.java:56)
at gov.noaa.ncdc.cmb.persistence.dao.GenericDaoHibernateImpl.saveOrUpdate(GenericDaoHibernateImpl.java:187)
</code></pre>
<p>I have the following application context configuration file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:flex="http://www.springframework.org/schema/flex"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/flex
http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- load values used for bean properties -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>applicationContext.properties</value>
</property>
</bean>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- DataSource where objects will be persisted -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="${datasource.username}" />
<property name="password" value="${datasource.password}" />
<property name="url" value="${datasource.url}" />
<property name="driverClassName" value="${datasource.driver}" />
</bean>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- Factory bean for Hibernate Sessions -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>gov.noaa.ncdc.cmb.esrl.domain.entity.EsrlDailyAvg</value>
<value>gov.noaa.ncdc.cmb.esrl.domain.entity.EsrlObservations</value>
<value>gov.noaa.ncdc.cmb.esrl.domain.entity.EsrlStation</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
<prop key="hibernate.query.substitutions">true 1, false 0</prop>
<prop key="hibernate.max_fetch_depth">6</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddlauto}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.use_second_level_cache}</prop>
</props>
</property>
</bean>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- Transaction Manager bean -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- enable the configuration of transactional behavior based on annotations -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- DAO for ESRL Station objects -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean id="esrlStationDao" class="gov.noaa.ncdc.cmb.esrl.domain.dao.EsrlStationDaoHibernateImpl">
<property name="sessionFactory" ref="hibernateSessionFactory" />
<property name="persistentClass" value="gov.noaa.ncdc.cmb.esrl.domain.entity.EsrlStation" />
</bean>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- DAO for ESRL Observations objects -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean id="esrlObservationsDao" class="gov.noaa.ncdc.cmb.esrl.domain.dao.EsrlObservationsDaoHibernateImpl">
<property name="sessionFactory" ref="hibernateSessionFactory" />
<property name="persistentClass" value="gov.noaa.ncdc.cmb.esrl.domain.entity.EsrlObservations" />
</bean>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- DAO for ESRL daily average objects -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean id="esrlDailyAvgDao" class="gov.noaa.ncdc.cmb.esrl.domain.dao.EsrlDailyAvgDaoHibernateImpl">
<property name="sessionFactory" ref="hibernateSessionFactory" />
<property name="persistentClass" value="gov.noaa.ncdc.cmb.esrl.domain.entity.EsrlDailyAvg" />
</bean>
</beans>
</code></pre>
<p>The generic DAO class (from which the DAO being used in my program is extended) looks like this:</p>
<pre><code>package gov.noaa.ncdc.cmb.persistence.dao;
import gov.noaa.ncdc.cmb.persistence.entity.PersistentEntity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
/**
* This class is an implementation of GenericDao<T, PK> using Hibernate.
*/
public class GenericDaoHibernateImpl<T extends PersistentEntity<PK>, PK extends Serializable>
implements GenericDao<T, PK>
{
private SessionFactory sessionFactory;
static private Log log = LogFactory.getLog(GenericDaoHibernateImpl.class);
private Class<T> persistentClass;
/**
* Can be used within subclasses as a convenience method.
*
* @param criterionList the criteria to find by
* @return the list of elements that match the specified criteria
*/
protected List<T> findByCriteria(final List<Criterion> criterionList)
{
Criteria criteria = getCurrentSession().createCriteria(persistentClass);
for (Criterion criterion : criterionList)
{
criteria.add(criterion);
}
return criteria.list();
}
protected String getCanonicalPersistentClassName()
{
return persistentClass.getCanonicalName();
}
/**
* Gets the current Hibernate Session object.
*
* @return
*/
protected Session getCurrentSession()
{
return sessionFactory.getCurrentSession();
}
/*
* This method only provided for interface compatibility. Not recommended for use with large batches
* (this is an inefficient implementation, and it's somewhat difficult to perform batch operations with Hibernate).
*
* (non-Javadoc)
* @see gov.noaa.ncdc.cmb.persistence.dao.GenericDao#batchInsert(java.util.Collection)
*/
@Override
public int[] batchInsert(final Collection<T> entityCollection)
{
int[] updateCounts = new int[entityCollection.size()];
int i = 0;
for (T entity : entityCollection)
{
try
{
saveOrUpdate(entity);
updateCounts[i] = 1;
i++;
}
catch (Exception ex)
{
clear();
throw new RuntimeException(ex);
}
}
flush();
clear();
return updateCounts;
}
/*
* This method only provided for interface compatibility. Not recommended for use with large batches
* (this is an inefficient implementation, and it's somewhat difficult to perform batch operations with Hibernate).
*
* (non-Javadoc)
* @see gov.noaa.ncdc.cmb.persistence.dao.GenericDao#batchUpdate(java.util.Collection)
*/
@Override
public int[] batchUpdate(final Collection<T> entityCollection)
{
return batchInsert(entityCollection);
}
/**
* Completely clear the session. Evict all loaded instances and cancel all pending saves, updates and deletions. Do
* not close open iterators or instances of ScrollableResults.
*/
public void clear()
{
getCurrentSession().clear();
}
/*
* (non-Javadoc)
* @see gov.noaa.ncdc.cmb.persistence.dao.GenericDao#delete(gov.noaa.ncdc.cmb.persistence.entity.PersistentEntity)
*/
@Override
public void delete(final T persistentObject)
{
getCurrentSession().delete(persistentObject);
}
/*
* (non-Javadoc)
* @see gov.noaa.ncdc.cmb.persistence.dao.GenericDao#findAll()
*/
@Override
public List<T> findAll()
{
return getCurrentSession().createQuery("from " + persistentClass.getName()).list();
}
/**
* Finds a collection of entity objects which match to the example instance, minus any specified properties which should be excluded from the matching.
*
* @param exampleInstance
* @param excludeProperty
* @return
*/
public List<T> findByExample(final T exampleInstance,
final String[] excludeProperty)
{
Criteria criteria = getCurrentSession().createCriteria(persistentClass);
Example example = Example.create(exampleInstance);
if (excludeProperty != null)
{
for (String exclude : excludeProperty)
{
example.excludeProperty(exclude);
}
}
criteria.add(example);
return criteria.list();
}
/*
* (non-Javadoc)
* @see com.sun.cloud.lifecycle.core.persistence.dao.GenericDao#findById(java.io.Serializable)
*/
@Override
public T findById(final PK id)
{
return (T) getCurrentSession().load(persistentClass, id);
}
/**
* Force this session to flush. Must be called at the end of a unit of work, before commiting the transaction and
* closing the session (depending on flush-mode, Transaction.commit() calls this method).
*
* Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.
*/
public void flush()
{
getCurrentSession().flush();
}
/*
* (non-Javadoc)
* @see gov.noaa.ncdc.cmb.persistence.dao.GenericDao#saveOrUpdate(gov.noaa.ncdc.cmb.persistence.entity.PersistentEntity)
*/
@Override
public T saveOrUpdate(final T entity)
{
try
{
entity.setUpdatedDate(new Date());
getCurrentSession().saveOrUpdate(entity);
return entity;
}
catch (Exception ex)
{
String errorMessage = "Failed to save the object.";
log.error(errorMessage, ex);
throw new RuntimeException(errorMessage, ex);
}
}
/**
* Setter for the persistentClass property.
*
* @param persistentClass
*/
public void setPersistentClass(final Class<T> persistentClass)
{
this.persistentClass = persistentClass;
}
/**
* Property setter.
*
* @param sessionFactory
*/
public void setSessionFactory(final SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
}
</code></pre>
<p>My application gets the DAO from the application context:</p>
<pre><code>// load the Spring application context, get the DAOs
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "dailyAveragingApplicationContext.xml" });
esrlDailyAvgDao = (EsrlDailyAvgDao) applicationContext.getBean("esrlDailyAvgDao");
esrlObservationsDao = (EsrlObservationsDao) applicationContext.getBean("esrlObservationsDao");
</code></pre>
<p>And the exception is encountered when I try to save an entity:</p>
<pre><code>esrlDailyAvgDao.saveOrUpdate(esrlDailyAvg);
</code></pre>
<p>The DAO class itself uses the Transactional annotation:</p>
<pre><code>@Transactional
public class EsrlDailyAvgDaoHibernateImpl
extends GenericDaoHibernateImpl<EsrlDailyAvg, Long>
implements EsrlDailyAvgDao
</code></pre>
<p>The exception stack trace looks like this:</p>
<pre><code>SEVERE: Failed to save the object.
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:622)
at gov.noaa.ncdc.cmb.persistence.dao.GenericDaoHibernateImpl.getCurrentSession(GenericDaoHibernateImpl.java:56)
at gov.noaa.ncdc.cmb.persistence.dao.GenericDaoHibernateImpl.saveOrUpdate(GenericDaoHibernateImpl.java:187)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:196)
at $Proxy19.saveOrUpdate(Unknown Source)
at gov.noaa.ncdc.cmb.esrl.ingest.EsrlDailyAvgProcessor.main(EsrlDailyAvgProcessor.java:469)
</code></pre>
| 0 | 6,341 |
yii2 how to run console controller function
|
<p>I'm stuck. I'm trying to run some function from the command shell.
I'm using the HelloController from the basic project.
When I run <code>php yii hello</code> it's working good and the index function is running but if I try to run different function like <code>php yii hello/create</code> I'm getting this error -</p>
<blockquote>
<p>Error: Unknown command.</p>
</blockquote>
<p>I added the create function to this controller.
The strange thing is that when I run <code>php yii</code> I'm seeing the create command.
My controller code </p>
<pre><code>namespace app\commands;
use yii\console\Controller;
use Yii;
class HelloController extends Controller
{
public function actionIndex($message = 'hello world')
{
echo $message . "\n";
}
public function actionCreate($message = 'hello world')
{
echo $message . "\n";
}
}
</code></pre>
<p><strong>UPDATED:</strong>
My Config file is</p>
<pre><code>Yii::setAlias('@tests', dirname(__DIR__) . '/tests');
$params = require(__DIR__ . '/params.php');
$db = require(__DIR__ . '/db.php');
return [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log', 'gii'],
'controllerNamespace' => 'app\commands',
'modules' => [
'gii' => 'yii\gii\Module',
],
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@app/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => '...',
'username' => '...',
'password' => '...',
'port' => '...',
//'encryption' => 'tls',
],
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
];
</code></pre>
<p>Does anyone know how to solve this issue?
Thanks.</p>
| 0 | 1,165 |
Angular 5 Unit testing throwing error for "components should create " test case
|
<p>I am trying Angular 5 unit testing for the first time. While I already created the app then decided to run testing in it. But I am getting these errors: </p>
<pre><code>AppComponent should create the app
AppComponent should have as title 'app'
AppComponent should render title in a h1 tag
GalleryComponent should create
UploadComponent should create
</code></pre>
<p>and error details like : </p>
<pre><code>Failed: Template parse errors:
'app-upload' is not a known element:
1. If 'app-upload' is an Angular component, then verify that it is part of this module.
2. If 'app-upload' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (" class="row">
<div class="col-md-3" style="padding:5%; box-sizing: border-box">
[ERROR ->]<app-upload></app-upload>
</div>
<div class="col-md-9">
"): ng:///DynamicTestModule/AppComponent.html@3:12
</code></pre>
<p>My package.json dev dependencies :</p>
<pre><code>devDependencies": {
"@angular/compiler-cli": "^6.0.2",
"@angular-devkit/build-angular": "~0.6.3",
"typescript": "~2.7.2",
"@angular/cli": "~6.0.3",
"@angular/language-service": "^6.0.2",
"@types/jasmine": "2.8.6",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~1.4.2",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1"
}
</code></pre>
<p>Test file app.component.spec.ts</p>
<pre><code>import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to Typito-photo-app!');
}));
});
</code></pre>
<p>I couldn't figure out how to solve these. I haven't made any changes in spec files nor did I wrote any test cases. Shouldn't all these be running as expected according to what is described in angular documentation?</p>
| 0 | 1,192 |
How to use JMS Appender?
|
<p>Inmy research about JMS Appenders I've found <a href="http://activemq.apache.org/how-do-i-use-log4j-jms-appender-with-activemq.html" rel="nofollow">turorial1</a> and <a href="http://code.google.com/p/log4j-jms-sample/wiki/ConfigurationGuide" rel="nofollow">tutorial2</a> . I've tried to follow them, but I couldn't run example program.</p>
<p>Fistly I created file log4j.properties</p>
<pre><code>log4j.rootLogger=INFO, stdout, jms
#
log4j.logger.org.apache.activemq=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %-5p %c - %m%n
#
log4j.appender.jms=org.apache.log4j.net.JMSAppender
log4j.appender.jms.InitialContextFactoryName=org.apache.activemq.jndi.ActiveMQInitialContextFactory
log4j.appender.jms.ProviderURL=tcp://localhost:61616
log4j.appender.jms.TopicBindingName=logTopic
log4j.appender.jms.TopicConnectionFactoryBindingName=ConnectionFactory
</code></pre>
<p>and jndi.properties</p>
<pre><code>topic.logTopic=logTopic
</code></pre>
<p>Then I added Receiver.java to my project</p>
<pre><code>public class Receiver implements MessageListener {
public Receiver() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection conn = factory.createConnection();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
conn.start();
MessageConsumer consumer = sess.createConsumer(sess.createTopic("logTopic"));
consumer.setMessageListener(this);
Logger log = Logger.getLogger(Receiver.class);
log.info("Test log");
Thread.sleep(1000);
consumer.close();
sess.close();
conn.close();
System.exit(1);
}
public static void main(String[] args) throws Exception {
new Receiver();
}
@Override
public void onMessage(Message message) {
try {
// receive log event in your consumer
LoggingEvent event = (LoggingEvent)((ActiveMQObjectMessage)message).getObject();
System.out.println("Received log [" + event.getLevel() + "]: "+ event.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>I need make Receiver to gather all logs from project, but I cannot even run this simple example. Probably I don't know how to configure it correctly, because I get this output:</p>
<pre><code>log4j:WARN No appenders could be found for logger (org.apache.activemq.transport.WireFormatNegotiator).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code></pre>
<p>Did I miss adding some lines in code or some files to classpath? I'm new to log4j.</p>
<p>EDIT:
I set Logger in <code>AspectJ</code> class. But I think that also in <code>Receiver</code> Logger is created and log is sent, so probably it should be done in <code>Receiver</code>, not in other class in my project.</p>
<pre><code>static final Logger logger = Logger.getLogger(ReportingAspect.class);
@Before("setLoggingFile()")
public void setProperties() {
PropertyConfigurator.configure("log4j.properties");
}
ProjectJMS
|
\_ src
| \_ packages...
\_jndi.propeties
\_log4j.properties
</code></pre>
| 0 | 1,268 |
Replace Unicode character "�" with a space
|
<p>I'm a doing an massive uploading of information from a .csv file and I need replace this character non ASCII "�" for a normal space, " ".</p>
<p>The character "�" corresponds to "\uFFFD" for C, C++, and Java, which it seems that it is called <a href="https://www.utf8-chartable.de/unicode-utf8-table.pl?start=65280" rel="nofollow noreferrer">REPLACEMENT CHARACTER</a>. There are others, such as spaces type like <a href="https://www.utf8-chartable.de/unicode-utf8-table.pl?start=65279&number=128" rel="nofollow noreferrer">U+FEFF</a>, <a href="https://www.utf8-chartable.de/unicode-utf8-table.pl?start=8287&number=128" rel="nofollow noreferrer">U+205F</a>, <a href="https://www.utf8-chartable.de/unicode-utf8-table.pl?start=8192&number=128" rel="nofollow noreferrer">U+200B</a>, <a href="https://www.utf8-chartable.de/unicode-utf8-table.pl?start=6158&number=128" rel="nofollow noreferrer">U+180E</a>, and <a href="https://www.utf8-chartable.de/unicode-utf8-table.pl?start=8239&number=128" rel="nofollow noreferrer">U+202F</a> in the C# official documentation.</p>
<p>I'm trying do the replace this way:</p>
<pre><code>public string Errors = "";
public void test(){
string textFromCsvCell = "";
string validCharacters = "^[0-9A-Za-z().:%-/ ]+$";
textFromCsvCell = "This is my text from csv file"; //All spaces aren't normal space " "
string cleaned = textFromCsvCell.Replace("\uFFFD", "\"")
if (Regex.IsMatch(cleaned, validCharacters ))
//All code for insert
else
Errors=cleaned;
//print Errors
}
</code></pre>
<p>The test method shows me this text:</p>
<p><strong>"This is my�texto from csv file"</strong></p>
<p>I try some solutions too:</p>
<p><strong>Trying solution 1: Using Trim</strong></p>
<pre><code> Regex.Replace(value.Trim(), @"[^\S\r\n]+", " ");
</code></pre>
<p><strong>Try solution 2: Using Replace</strong></p>
<pre><code> System.Text.RegularExpressions.Regex.Replace(str, @"\s+", " ");
</code></pre>
<p><strong>Try solution 3: Using Trim</strong></p>
<pre><code> String.Trim(new char[]{'\uFEFF', '\u200B'});
</code></pre>
<p><strong>Try solution 4: Add [\S\r\n] to validCharacters</strong></p>
<pre><code> string validCharacters = "^[\S\r\n0-9A-Za-z().:%-/ ]+$";
</code></pre>
<p>Nothing works.</p>
<p>How can I replace it?</p>
<p>Sources:</p>
<ul>
<li><p><em><a href="http://www.fileformat.info/info/unicode/char/0fffd/index.htm" rel="nofollow noreferrer">Unicode Character 'REPLACEMENT CHARACTER' (U+FFFD)</a></em></p>
</li>
<li><p><em><a href="https://stackoverflow.com/questions/3725444/">Trying to replace all white space with a single space</a></em></p>
</li>
<li><p><em><a href="https://stackoverflow.com/questions/1317700/">Strip the byte order mark from string in C#</a></em></p>
</li>
<li><p><em><a href="https://stackoverflow.com/questions/25954446/">Remove extra whitespaces, but keep new lines using a regular expression in C#</a></em></p>
</li>
</ul>
<h1>EDITED</h1>
<p><strong>This is the original string:</strong></p>
<p>"SYSTEM OF MONITORING CONTINUES OF GLUCOSE"</p>
<p><strong>in 0x... notation</strong></p>
<p>SYSTEM OF0xA0MONITORING CONTINUES OF GLUCOSE</p>
<h2>Solution</h2>
<p>Go to the <em><a href="https://r12a.github.io/app-conversion/" rel="nofollow noreferrer">Unicode code converter</a></em>. Look at the conversions and do the <em>replace</em>.</p>
<p>In my case, I do a simple replace:</p>
<pre><code> string value = "SYSTEM OF MONITORING CONTINUES OF GLUCOSE";
//value contains non-breaking whitespace
//value is "SYSTEM OF�MONITORING CONTINUES OF GLUCOSE"
string cleaned = "";
string pattern = @"[^\u0000-\u007F]+";
string replacement = " ";
Regex rgx = new Regex(pattern);
cleaned = rgx.Replace(value, replacement);
if (Regex.IsMatch(cleaned,"^[0-9A-Za-z().:<>%-/ ]+$"){
//all code for insert
else
//Error messages
</code></pre>
<p>This expression represents all possible spaces: space, tab, page break, line break and carriage return</p>
<pre><code>[ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]
</code></pre>
<p>References</p>
<ul>
<li><em><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions" rel="nofollow noreferrer">Regular expressions</a></em> (<a href="https://en.wikipedia.org/wiki/MDN_Web_Docs" rel="nofollow noreferrer">MDN</a>)</li>
</ul>
| 0 | 1,928 |
Active Index of tabview not getting updated automatically
|
<p>Active Index is not getting updated automatically. ReaD in a few posts that by placing the tabView on a form it works. Or by including <code><p:ajax event="tabChange"/></code> in the tabview it works. But nothing seems to work</p>
<p><strong>xhtml</strong></p>
<p><strong>Sample 1 : automatic updates</strong></p>
<p>
</p>
<pre><code> <p:tabView id="categoryTabView" var="promoArticle" value="#{promotionDetailBean.artDTOs}" activeIndex="#{promotionDetailBean.activeTabIndex}">
<p:tab id="categoriesTab" title="#{promoArticle.categoryName}">
<p:dataTable id="promotionDetail_dataTable" var="articlePromo" value="#{promoArticle.artVO}" selection="#{promotionDetailBean.selectedArt}" rowIndexVar="rowIndex">
<p:column id="select" selectionMode="multiple" />
<p:column id="barCode">
<h:inputText id="barCodeInputTxt" value="#{articlePromo.barCode}"
styleClass="inputTextStyle" onchange="onSuggestedValueChange('categoryTabView',#{promotionDetailBean.activeTabIndex}, 'promotionDetail_dataTable',#{rowIndex},'originalCostInputTxt')" />
</p:column>
</p:dataTable>
</p:tab>
</p:tabView>
</code></pre>
<p><strong>Sample 2: Updating on tabChange event</strong></p>
<pre><code> <h:form id="form">
<p:growl id="growlm" showDetail="true" />
<p:tabView id="categoryTabView" var="promoArticle" value="#{promotionDetailBean.artDTOs}" >
<p:ajax event="tabChange" listener="#{promotionDetailBean.tabChanged}" update=":growlm" />
<p:tab id="categoriesTab" title="#{promoArticle.categoryName}">
<p:dataTable id="promotionDetail_dataTable" var="articlePromo" value="#{promoArticle.artVO}" selection="#{promotionDetailBean.selectedArt}" rowIndexVar="rowIndex">
<p:column id="select" selectionMode="multiple" />
<p:column id="barCode">
<h:inputText id="barCodeInputTxt" value="#{articlePromo.barCode}"
styleClass="inputTextStyle" onchange="onSuggestedValueChange('categoryTabView',#{promotionDetailBean.activeTabIndex}, 'promotionDetail_dataTable',#{rowIndex},'originalCostInputTxt')" />
</p:column>
</p:dataTable>
</p:tab>
</p:tabView>
</code></pre>
<p>I need to identify the cell on "onChange " event. But the activeIndex is always 0, the initialized value. The event doesn't get call.</p>
<p><strong>bean</strong></p>
<pre><code>private Integer activeTabIndex = 0;
public Integer getActiveTabIndex() {
return activeTabIndex;
}
public void setActiveTabIndex(Integer activeTabIndex) {
this.activeTabIndex = activeTabIndex;
}
</code></pre>
<p><strong>bean</strong></p>
<pre><code>public void tabChanged(TabChangeEvent event){
TabView tv = (TabView) event.getComponent();
this.activeTabIndex = tv.getActiveIndex();
}
</code></pre>
<p>But the event is not getting trigerred. Nor getting updated automatically.</p>
<p>What could be the probable issues ?</p>
<p>Thanks,
Shikha</p>
| 0 | 1,527 |
missing required architecture armv7
|
<p>i use xcode with libsqlite3.dylib for sqlite , but when i compile to device the following error arise :</p>
<pre><code>Ld /Users/user1319/Library/Developer/Xcode/DerivedData/Directory-app normal armv7
cd /Users/user1319/Desktop/app/app
setenv IPHONEOS_DEPLOYMENT_TARGET 5.0
setenv PATH "/Developer/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch armv7 -isysroot /Developer/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk -L/Users/user1319/Library/Developer/Xcode/DerivedData/app_Directory-bnkhohrmxdhrusarswxeqvxlljct/Build/Products/Distribution-iphoneos -F/Users/user1319/Library/Developer/Xcode/DerivedData/app-bnkhohrmxdhrusarswxeqvxlljct/Build/Products/Distribution-iphoneos -filelist "/Users/user1319/Library/Developer/Xcode/DerivedData/app-bnkhohrmxdhrusarswxeqvxlljct/Build/Intermediates/app Directory.build/Distribution-iphoneos/app.build/Objects-normal/armv7/app.LinkFileList" -Xlinker -rpath -Xlinker / -dead_strip -miphoneos-version-min=5.0 -lsqlite3 -lsqlite3.0 -framework AddressBook -framework AddressBookUI -framework UIKit -framework Foundation -framework CoreGraphics -o /Users/user1319/Library/Developer/Xcode/DerivedData/app-bnkhohrmxdhrusarswxeqvxlljct/Build/Products/Distribution-iphoneos/app.app/app
ld: warning: ignoring file /Developer/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/usr/lib/libsqlite3.dylib, missing required architecture armv7 in file
ld: warning: ignoring file /Developer/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/usr/lib/libsqlite3.0.dylib, missing required architecture armv7 in file
Undefined symbols for architecture armv7:
"_sqlite3_reset", referenced from:
-[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:] in FMDatabase.o
-[FMStatement reset] in FMDatabase.o
-[FMResultSet next] in FMResultSet.o
"_sqlite3_bind_blob", referenced from:
-[FMDatabase bindObject:toColumn:inStatement:] in FMDatabase.o
"_sqlite3_changes", referenced from:
-[FMDatabase changes] in FMDatabase.o
"_sqlite3_prepare_v2", referenced from:
-[FMDatabase executeQuery:withArgumentsInArray:orVAList:] in FMDatabase.o
-[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:] in FMDatabase.o
-[FMDatabase(FMDatabaseAdditions) validateSQL:error:] in FMDatabaseAdditions.o
"_sqlite3_open", referenced from:
-[FMDatabase open] in FMDatabase.o
"_sqlite3_open_v2", referenced from:
-[FMDatabase openWithFlags:] in FMDatabase.o
"_sqlite3_bind_text", referenced from:
-[FMDatabase bindObject:toColumn:inStatement:] in FMDatabase.o
"_sqlite3_step", referenced from:
-[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:] in FMDatabase.o
-[FMResultSet next] in FMResultSet.o
"_sqlite3_next_stmt", referenced from:
-[FMDatabase close] in FMDatabase.o
"_sqlite3_bind_double", referenced from:
-[FMDatabase bindObject:toColumn:inStatement:] in FMDatabase.o
"_sqlite3_threadsafe", referenced from:
+[FMDatabase isThreadSafe] in FMDatabase.o
"_sqlite3_bind_int", referenced from:
-[FMDatabase bindObject:toColumn:inStatement:] in FMDatabase.o
"_sqlite3_last_insert_rowid", referenced from:
-[FMDatabase lastInsertRowId] in FMDatabase.o
"_sqlite3_column_blob", referenced from:
-[FMResultSet dataForColumnIndex:] in FMResultSet.o
-[FMResultSet dataNoCopyForColumnIndex:] in FMResultSet.o
"_sqlite3_finalize", referenced from:
-[FMDatabase close] in FMDatabase.o
-[FMDatabase executeQuery:withArgumentsInArray:orVAList:] in FMDatabase.o
-[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:] in FMDatabase.o
-[FMStatement close] in FMDatabase.o
-[FMDatabase(FMDatabaseAdditions) validateSQL:error:] in FMDatabaseAdditions.o
"_sqlite3_column_text", referenced from:
-[FMResultSet kvcMagic:] in FMResultSet.o
-[FMResultSet stringForColumnIndex:] in FMResultSet.o
-[FMResultSet UTF8StringForColumnIndex:] in FMResultSet.o
"_sqlite3_column_bytes", referenced from:
-[FMResultSet dataForColumnIndex:] in FMResultSet.o
-[FMResultSet dataNoCopyForColumnIndex:] in FMResultSet.o
"_sqlite3_column_int64", referenced from:
-[FMResultSet longForColumnIndex:] in FMResultSet.o
-[FMResultSet longLongIntForColumnIndex:] in FMResultSet.o
"_sqlite3_bind_parameter_count", referenced from:
-[FMDatabase executeQuery:withArgumentsInArray:orVAList:] in FMDatabase.o
-[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:] in FMDatabase.o
"_sqlite3_column_count", referenced from:
-[FMResultSet columnCount] in FMResultSet.o
-[FMResultSet setupColumnNames] in FMResultSet.o
-[FMResultSet kvcMagic:] in FMResultSet.o
"_sqlite3_column_name", referenced from:
-[FMResultSet setupColumnNames] in FMResultSet.o
-[FMResultSet kvcMagic:] in FMResultSet.o
-[FMResultSet columnNameForIndex:] in FMResultSet.o
"_sqlite3_errmsg", referenced from:
-[FMDatabase lastErrorMessage] in FMDatabase.o
-[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:] in FMDatabase.o
-[FMResultSet next] in FMResultSet.o
"_sqlite3_column_type", referenced from:
-[FMResultSet stringForColumnIndex:] in FMResultSet.o
-[FMResultSet dateForColumnIndex:] in FMResultSet.o
-[FMResultSet dataForColumnIndex:] in FMResultSet.o
-[FMResultSet dataNoCopyForColumnIndex:] in FMResultSet.o
-[FMResultSet columnIndexIsNull:] in FMResultSet.o
-[FMResultSet UTF8StringForColumnIndex:] in FMResultSet.o
-[FMResultSet objectForColumnIndex:] in FMResultSet.o
...
"_sqlite3_libversion", referenced from:
+[FMDatabase sqliteLibVersion] in FMDatabase.o
"_sqlite3_errcode", referenced from:
-[FMDatabase lastErrorCode] in FMDatabase.o
-[FMResultSet hasAnotherRow] in FMResultSet.o
"_sqlite3_column_int", referenced from:
-[FMResultSet intForColumnIndex:] in FMResultSet.o
"_sqlite3_close", referenced from:
-[FMDatabase close] in FMDatabase.o
"_sqlite3_column_double", referenced from:
-[FMResultSet doubleForColumnIndex:] in FMResultSet.o
"_sqlite3_data_count", referenced from:
-[FMResultSet resultDict] in FMResultSet.o
"_sqlite3_bind_int64", referenced from:
-[FMDatabase bindObject:toColumn:inStatement:] in FMDatabase.o
"_sqlite3_bind_null", referenced from:
-[FMDatabase bindObject:toColumn:inStatement:] in FMDatabase.o
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre>
<p>But the project compiled successfully to simulator , the error happen when i compiled the project to real device . </p>
| 0 | 2,647 |
Laravel custom pivot usage (Extends Model or Extends Pivot)
|
<p>I am really stuck using a custom model for my pivot, and don't understand why can we make a custom model for it if we can't use it as a model.
I've seen many answers and articles, and all chose to extend Pivot or Model, but real life usage is never taken into account and never go any further than giving it a "named" class.</p>
<p>Here is an example of what I'm trying to achieve:
My main models:
<strong>Player</strong> model, with <strong><em>players</em></strong> table.
<strong>Game</strong> model, with <strong><em>games</em></strong> table.</p>
<p><strong>Player</strong> and <strong>Game</strong> have a many-to-many relationship, that we can call "<strong>Party</strong>" with a "<strong><em>game_player</em></strong>" table.</p>
<p>Less important for now, I have also a <strong>Score</strong> model that holds the score/turns, a <strong>Party</strong> can have many scores, so <strong><em>scores</em></strong> table has a party_id entry.</p>
<p>So, here are basically my classes (Laravel 5.2):</p>
<p>Player</p>
<pre class="lang-php prettyprint-override"><code>class Player extends Model
{
// The Games this Player is participating to.
public function games() {
return $this->belongsToMany(Game::class)->withPivot('id')->withTimestamps();
}
// The Scores belonging to this Player.
public function parties() {
return $this->hasManyThrough(Score::class, Party::class);
}
// The Custom Pivot (Party) creation for this Player.
public function newPivot(Model $parent, array $attributes, $table, $exists) {
if ($parent instanceof Game) {
return new Party($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
</code></pre>
<p>Game</p>
<pre class="lang-php prettyprint-override"><code>class Game extends Model
{
// The Players participating into this Game.
public function players() {
return $this->belongsToMany(Player::class)->withPivot('id')->withTimestamps();
}
// The Scores belonging to this Party.
public function parties() {
return $this->hasManyThrough(Score::class, Party::class);
}
// The Custom Pivot (Party) creation for this Game.
public function newPivot(Model $parent, array $attributes, $table, $exists) {
if ($parent instanceof Player) {
return new Party($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
</code></pre>
<p>Party</p>
<pre class="lang-php prettyprint-override"><code>class Party extends Pivot
{
protected $table = 'game_player';
// The Player this Party belongs to.
public function player() {
return $this->belongsTo(Player::class);
}
// The Game this Party belongs to.
public function event() {
return $this->belongsTo(Game::class);
}
// The Scores belonging to this Party.
public function scores()
{
return $this->hasMany(Score::class);
}
}
</code></pre>
<p>Score</p>
<pre class="lang-php prettyprint-override"><code>class Score extends Model
{
// The Party this Score belongs to (has "party_id" column).
public function party() {
return $this->belongsTo(Party::class);
}
}
</code></pre>
<p>Now, I have two different sets of problems that appear depending on if I extend Model or Pivot on Party:</p>
<p>1) When Party extends Pivot:</p>
<ul>
<li>Can't do something like <strong>Party::count()</strong>, anything that works with models.</li>
<li>Can't do something like <strong>Party::where("player_id", $player->id)</strong> and so on ... Basically I want the party to have a scores/turns table attached to it and to do so I need to select the pivot model.</li>
<li>Can't do something like $events->player->first()->scores() nor event $events->player->first()->pivot->scores(), it breaks with the following:</li>
</ul>
<blockquote>
<p>PHP error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\Pivot::__construct() must be an instance of Illuminate\Database\Eloquent\Model</p>
</blockquote>
<p>2) When Party extends Model:</p>
<ul>
<li>Can do trivial things such as Party::count(), Party::where("Game_id", $game->id)</li>
<li>Lose all pivot functions, so can't do $game->players, not even $game->players() work: $game->players()->count() is correct, but $game->players()->first() or $game->players->first() will break with the following:</li>
</ul>
<blockquote>
<p>PHP error: Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given</p>
</blockquote>
<p>Question:</p>
<p>How to correctly use the custom pivot model when instantiating them is different?</p>
<p>I hope to achieve the following:</p>
<ul>
<li>Do the normal $events->players->attach($player)</li>
<li>Be able to attach a score like $score->party_id = $events->players->find($x)->pivot->id (or any other way via a scope for example)</li>
<li>Be able to count all parties being played, or the ones on one specific game or by a specific player (something like Party::count(), $player->parties->count() etc)</li>
</ul>
<p>Thank you.</p>
| 1 | 1,798 |
Angular2 Animation on Load and Page Transition
|
<p>Currently trying to implement some animations into my Angular2 site using ng2's built in <code>animations</code> component. So far I've been working through the Angular 2 <code>Developer Guide - Animations</code> provided in the documentation. With that though I've run into a few questions I was hoping the SO community might be able to assist in. My first question/problem I seem to be having is that the animation (from what I can tell) doesn't run on page load. It seems to run perfectly fine if I switch to a view then back to the view with the animation. This is the code I'm currently using for the animation in question (I can provide the whole component if desired):</p>
<pre><code>animations: [
trigger('kissState', [
state('in', style({opacity: 1})),
transition('void => *', [
style({opacity: 0}),
animate('250ms ease-in-out')
]),
transition('* => void', [
animate('250ms ease-in-out', style({opacity: 0}))
])
])
]
</code></pre>
<p>I was under the impression that the <code>void => *</code> would set my DOM element to <code>opacity:0</code> and once it entered <code>in</code> to the view it would be <code>opacity:1</code>. Another problem I seem to be having is that my navigations don't seem to be working on mobile. I haven't actually moved them to my server yet but developing locally and looking on my mobile device via node <code>localtunnel</code> there doesn't seem to be any animations. This could be because the strange way <code>localtunnel</code> operates so I'm not too terribly concerned about that until I can truly test it on an actual server. Here's the other animation that in particular is when I noticed it wasn't working on my mobile device: </p>
<pre><code>animations: [
trigger('offScreenMenu', [
state('inactive', style({
opacity: 0,
zIndex: -10
})),
state('active', style({
backgroundColor: 'rgba(255, 255, 255, 0.8)',
zIndex: 10
})),
transition('inactive => active', animate('250ms ease-in')),
transition('active => inactive', animate('250ms ease-out'))
])
]
</code></pre>
<p>One last problem I've been having which is a known issue by the Angular2 team is animations on router view change. There's currently a SO <a href="https://stackoverflow.com/questions/37904860/angular-2-animate-no-visible-effect-of-the-void-transition-when-changin">question</a> that addresses this and a ticket on the Angular2 repo (mentioned in the comment by Günter Zöchbauer in the SO question). With that, I was curious if there were any present workarounds? Through some brief research it looked like there may at one time have been implemented a <code>ng-enter</code> and <code>ng-leave</code> one could use within their css for this, but from what I can tell these have been phased out. Still need to do a little more research so I could be wrong about that. </p>
<p>Thanks in advance for any help!</p>
<p>UPDATE(7.7.16): Alright so I decided to come back around to it and after messing with the timing of the page load animation it does appear to be working. Though I have to do a roughly a <code>1000ms</code> animation for it to be noticed. Which brings me to the questions (or more thought) that I believe the animation starts to execute before the DOM has fully loaded. Which would seem a bit strange.
Still working on the mobile animation situation. Looking like I'll be filing an issue on the Github repo at the moment as I've messed with it a fair bit and can't seem to get it to work. Also there doesn't seem to be any mention of mobile animations not working for NG2.</p>
<p>UPDATE(7.13.16): Looks like the Angular2 team has made a few fixes slated to release with RC5 that should address my above concerns. Going to answer my own question and close.</p>
| 1 | 1,090 |
Problems using foreach parallelization
|
<p>I'm trying to compare parallelization options. Specifically, I'm comparing the standard <code>SNOW</code> and <code>mulitcore</code> implementations to those using <code>doSNOW</code> or <code>doMC</code> and <code>foreach</code>. As a sample problem, I'm illustrating the central limit theorem by computing the means of samples drawn from a standard normal distribution many times. Here's the standard code:</p>
<pre><code>CltSim <- function(nSims=1000, size=100, mu=0, sigma=1){
sapply(1:nSims, function(x){
mean(rnorm(n=size, mean=mu, sd=sigma))
})
}
</code></pre>
<p>Here's the <code>SNOW</code> implementation:</p>
<pre><code>library(snow)
cl <- makeCluster(2)
ParCltSim <- function(cluster, nSims=1000, size=100, mu=0, sigma=1){
parSapply(cluster, 1:nSims, function(x){
mean(rnorm(n=size, mean=mu, sd=sigma))
})
}
</code></pre>
<p>Next, the <code>doSNOW</code> method:</p>
<pre><code>library(foreach)
library(doSNOW)
registerDoSNOW(cl)
FECltSim <- function(nSims=1000, size=100, mu=0, sigma=1) {
x <- numeric(nSims)
foreach(i=1:nSims, .combine=cbind) %dopar% {
x[i] <- mean(rnorm(n=size, mean=mu, sd=sigma))
}
}
</code></pre>
<p>I get the following results:</p>
<pre><code>> system.time(CltSim(nSims=10000, size=100))
user system elapsed
0.476 0.008 0.484
> system.time(ParCltSim(cluster=cl, nSims=10000, size=100))
user system elapsed
0.028 0.004 0.375
> system.time(FECltSim(nSims=10000, size=100))
user system elapsed
8.865 0.408 11.309
</code></pre>
<p>The <code>SNOW</code> implementation shaves off about 23% of computing time relative to an unparallelized run (time savings get bigger as the number of simulations increase, as we would expect). The <code>foreach</code> attempt actually <strong>increases</strong> run time by a factor of 20. Additionally, if I change <code>%dopar%</code> to <code>%do%</code> and check the unparallelized version of the loop, it takes over 7 seconds.</p>
<p>Additionally, we can consider the <code>multicore</code> package. The simulation written for <code>multicore</code> is</p>
<pre><code>library(multicore)
MCCltSim <- function(nSims=1000, size=100, mu=0, sigma=1){
unlist(mclapply(1:nSims, function(x){
mean(rnorm(n=size, mean=mu, sd=sigma))
}))
}
</code></pre>
<p>We get an even better speed improvement than <code>SNOW</code>:</p>
<pre><code>> system.time(MCCltSim(nSims=10000, size=100))
user system elapsed
0.924 0.032 0.307
</code></pre>
<p>Starting a new R session, we can attempt the <code>foreach</code> implementation using <code>doMC</code> instead of <code>doSNOW</code>, calling</p>
<pre><code>library(doMC)
registerDoMC()
</code></pre>
<p>then running <code>FECltSim()</code> as above, still finding</p>
<pre><code>> system.time(FECltSim(nSims=10000, size=100))
user system elapsed
6.800 0.024 6.887
</code></pre>
<p>This is "only" a 14-fold increase over the non-parallelized runtime.</p>
<p>Conclusion: My <code>foreach</code> code is not running efficiently under either <code>doSNOW</code> or <code>doMC</code>. Any idea why?</p>
<p>Thanks,
Charlie</p>
| 1 | 1,242 |
WatiN hangs on "about:blank" for multiple concurrent IE8 instances
|
<p>I’m trying to test several web sites using the latest version of WatiN.</p>
<p>If a try to run several tests simultaneously, WatiN will eventually throw an exception “<strong>Timeout while Internet Explorer busy</strong>”. This occurs because Internet Explorer eventually gets “stuck” trying to connect to “<strong>about:blank</strong>”.</p>
<p>Runtime environment:</p>
<ul>
<li>Windows 7 Professional</li>
<li>Internet Explorer 8 (Version 8.0.7600.16385)</li>
<li>WatiN (Version 2.1.0.1196)</li>
</ul>
<p>I have distilled the problem to the following bare-bones c# console program. To recreate the problem, create a new c# .NET 3.5 console program from Visual Studio, add a reference to WatiN.Core.dll, compile, then run. After about 10 seconds on my machine, IE hangs on "about:blank", and eventually WatiN times out and generates an exception.</p>
<p>Increasing the WatiN timeouts only delays the problem.</p>
<p>Has anyone else seen this problem? Can you reproduce the problem using my example program? Any solutions?</p>
<p><strong>[Code]</strong></p>
<pre><code>namespace IEBugUsingWatiN
{
using System;
using System.Collections.Generic;
using System.Threading;
using WatiN.Core;
class Program
{
const int MAX_THREADS = 7;
volatile static bool _stopAll = false;
static void Main( string[] args )
{
Console.WriteLine( "Initializing WatiN." );
var watinSettings = WatiN.Core.Settings.Instance;
watinSettings.AutoCloseDialogs = false;
watinSettings.AutoMoveMousePointerToTopLeft = false;
watinSettings.AutoStartDialogWatcher = false;
watinSettings.HighLightElement = false;
watinSettings.SleepTime = 200;
watinSettings.WaitUntilExistsTimeOut = 15;
Console.WriteLine( "Creating threads." );
List<Thread> threads = new List<Thread>();
for ( int numThreads = 0 ; numThreads < MAX_THREADS ; ++numThreads )
{
var thread = new Thread( ThreadFunc );
thread.IsBackground = true;
thread.SetApartmentState( ApartmentState.STA );
thread.Start();
threads.Add( thread );
}
Console.WriteLine( "Press Enter key to end tests..." );
Console.ReadLine();
_stopAll = true;
Console.WriteLine( "Waiting for all threads to end..." );
foreach ( var thread in threads )
{
thread.Join();
}
Console.WriteLine( "Done." );
}
static void ThreadFunc()
{
while ( !_stopAll )
{
WatiN.Core.IE ie = null;
try
{
ie = new WatiN.Core.IE();
ie.GoTo( "http://www.hertz.com" );
}
catch ( System.Exception ex )
{
_stopAll = true;
Console.WriteLine( "EXCEPTION: {0}", ex.Message );
}
if ( null != ie )
{
ie.Close();
ie = null;
}
Thread.Sleep( TimeSpan.FromSeconds( 1 ) );
}
}
}
}
</code></pre>
<p><strong>[Update]</strong></p>
<p>Microsoft has confirmed that this is a known bug. To make a long story short, IE (specifically, <strong>wininet.dll</strong>) leaks connections under certain circumstances. The only suggested workaround is to explicitly kill all Internet Explorer process instances after running a Test. A "fix" is not likely since this has been an issue for YEARS, and they are afraid of breaking compatibility with existing applications.</p>
<p>FYI, here is what Microsoft has to say:</p>
<blockquote>
<p>The best workaround would probably to
kill and restart IE at some interval
during your test run automation. You
can restart IE at some regular
interval or have some kind of
detection logic in your code. When
you get into this situation IE won’t
be able to make any request out so I
would expect the application to
receive a <strong>BeforeNavigate</strong> event (if
you sink this event) set up a timer
and by the time the timer fires check
to see if you ever get a
<strong>DocumentComplete</strong> event for the URL (which you probably won’t). This is a
good indication that you run into the
problem so you can proceed to kill and
restart the IE process at this point.</p>
<p>...this approach is not addressing the
root cause of wininet connection loss
but at the same time there aren’t any
practical approach within your control
to do this. Just to provide some
perspective on how you get into this
situation…</p>
<p>Whenever there are ActiveX components
(such as msxml making an AJAX request)
making an HTTP request and the Tab
window hosting that component is
closed before the response is
received, there is a chance IE will
lose that wininet connection if the
ActiveX does not abort the call. This
is exactly what happened in the hertz
scenario. The page has script running
to issue an AJAX request. IE window
is then closed before the response
comes back. Upon part of tearing down
the page, IE calls into the ActiveX
(MSXML in this case) to notify the
control upon shutting down. The
control can then abort that connection
upon being destroyed. MSXML does not
abort the connection here leading to
the leak. The issue is deeply rooted
in IE’s design architecture and how it
interacts with 3rd party components.
Because of this you will most likely
encounter this issue on web sites that
have AJAX requests. Over the years
there are multiple bugs opened against
this issue but all those bugs were
rejected due to high application
compat risk. Part of the difficulty
in providing a fix is that IE does not
always know that the ActiveX is the
one making a connection.</p>
<p>Wininet does not expose any mechanism
for a 3rd party control to reset or
clean up the wininet connection loss.
By default IE6/7 has 2 connections per
server while IE8 has 6 so this
behavior is probably less visible in
IE8. There is a registry key
documented here
<a href="http://support.microsoft.com/kb/183110" rel="nofollow">http://support.microsoft.com/kb/183110</a>
you can try to increase the number of
available connections. However this
is only delaying the problem. This is
why I mentioned the only supportable
way to reset the wininet state is to
restart the IE process.</p>
</blockquote>
| 1 | 2,466 |
Typescript error when using React useContext and useReducer
|
<p>I'm new to Typescript and I'm getting the following error on my variable <code>state</code> in using <code>useContext</code> and <code>useReducer</code> hooks:</p>
<blockquote>
<p>Type '{ state: {}; dispatch: Dispatch; }' is not assignable to
type '{ latlng: null; searchTerm: null; bookingId: null; myPin: null;
selectedPin: null; selectedCard: null; selectedCardPin: null; }'.<br>
Object literal may only specify known properties, and 'state' does not
exist in type '{ latlng: null; searchTerm: null; bookingId: null;
myPin: null; selectedPin: null; selectedCard: null; selectedCardPin:
null; }'.ts(2322)</p>
</blockquote>
<p>This is my <code>app.tsx</code>:</p>
<pre><code>const App = () => {
const initialState = useContext(Context)
const [state, dispatch] = useReducer(reducer, initialState)
return(
<Context.Provider value={{ state // <-this is where the error occurs//, dispatch }}>
...
</Context.Provider>
)
</code></pre>
<p>Following is my <code>context.jsx</code>:</p>
<pre><code>const Context = createContext({
latlng: null,
searchTerm: null,
bookingId: null,
myPin: null,
selectedPin: null,
selectedCard: null,
selectedCardPin: null,
})
</code></pre>
<p>Revision:</p>
<p>according to the advise, I've changed my `context.tsx' to the following, but still getting the error message:</p>
<blockquote>
<p>Argument of type '{ latlng: null; searchTerm: null; bookingId: null;
myPin: null; selectedPin: null; selectedCard: null; selectedCardPin:
null; }' is not assignable to parameter of type 'MyContextType'.<br>
Object literal may only specify known properties, and 'latlng' does
not exist in type 'MyContextType'.ts(2345)</p>
</blockquote>
<pre><code>import { createContext } from 'react'
interface MyContextType {
dispatch: React.Dispatch<any>,
state: {
latlng?: any,
searchTerm?: any,
bookingId?: any,
myPin?: any,
selectedPin?: any,
selectedCard?: any,
selectedCardPin?: any,
}
}
const Context = createContext<MyContextType>({
latlng: null,
searchTerm: null,
bookingId: null,
myPin: null,
selectedPin: null,
selectedCard: null,
selectedCardPin: null,
})
export default Context
</code></pre>
<p>2nd revision: </p>
<p>When I change my <code>context.jsx</code> to match the contents of <code>createContext</code> as following: </p>
<pre><code>interface MyContextType {
latlng?: any,
searchTerm?: any,
bookingId?: any,
myPin?: any,
selectedPin?: any,
selectedCard?: any,
selectedCardPin?: any,
}
const Context = createContext<MyContextType>({
latlng: null,
searchTerm: null,
bookingId: null,
myPin: null,
selectedPin: null,
selectedCard: null,
selectedCardPin: null,
})
</code></pre>
<p>the error is gone in <code>context.jsx</code>, but it causes a type error in app.jsx. </p>
<blockquote>
<p>Type '{ state: {}; dispatch: Dispatch; }' is not assignable to
type 'MyContextType'. Object literal may only specify known
properties, and 'state' does not exist in type
'MyContextType'.ts(2322)</p>
</blockquote>
<pre><code> <Context.Provider value={{ state //<-- here //, dispatch }}>
</Context.Provider>
</code></pre>
| 1 | 1,256 |
IE10 css Hover not working with touch devices
|
<p>Hi i have a simple css hover menu on my page but it does not seem to work on IE10 when using a touch device.</p>
<p>Is there any solution to this problem?</p>
<p>Sample: <a href="http://jsfiddle.net/Z8Q8T/" rel="nofollow">http://jsfiddle.net/Z8Q8T/</a></p>
<p>Html:</p>
<pre><code><ul class="Menu">
<li>
<a href="javascript:void(0);">First</a>
<ul>
<li>
<a href="#1" class="Active">1</a>
</li>
<li>
<a href="#2">2</a>
</li>
<li>
<a href="#3">3</a>
</li>
<li>
<a href="#4">4</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">Second</a>
<ul>
<li>
<a href="#5">5</a>
</li>
<li>
<a href="#6">6</a>
</li>
<li>
<a href="#7">7</a>
</li>
<li>
<a href="#8">8</a>
</li>
</ul>
</li>
</ul>
</code></pre>
<p>CSS:</p>
<pre><code>.Menu, .Menu ul {
list-style: none;
display: block;
margin: 0;
}
.Menu > li {
float: left;
padding-bottom: 1px;
margin: 0 10px;
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
text-transform: uppercase;
}
.Menu > li:hover, .Menu > li:active {
position: relative;
}
.Menu li a {
display: block;
color: #000000;
text-decoration: none;
}
.Menu > li > a {
border-bottom-style: solid;
border-bottom-width: 3px;
border-bottom-color: transparent;
}
.Menu > li > a:hover, .Menu > li > a:active {
border-bottom-color: #A9A9A9;
}
.Menu li > ul {
margin-top: 0px;
/* to ensure that we dont leave the ul and the hovering effect stops */
border-radius: 0 0 3px 3px;
-o-border-radius: 0 0 3px 3px;
-ms-border-radius: 0 0 3px 3px;
box-shadow: 0px 0px 3px #888;
padding: 0px 2px 2px 2px;
background-color: White;
position: absolute;
left: -4000px;
/* Hack to fix animation */
min-width: 100%;
opacity: 0;
transition: opacity 0.2s linear;
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
}
.Menu li:hover > ul, .Menu li a:active + ul {
left: -4px;
z-index: 100;
opacity: 1;
}
.Menu li ul > li {
border-left-style: solid;
border-left-width: 3px;
border-left-color: transparent;
padding: 0 3px;
margin: 3px 0;
white-space: nowrap;
}
.Menu li ul > li:hover, .Menu li ul > li:active {
border-left-color: #A9A9A9;
}
.Menu li ul > li.Active {
border-left-color: black;
}
</code></pre>
| 1 | 1,468 |
Out parameters in stored procedures (oracle database)
|
<p>I used stored proceture in the Oracle. How can I use out parameteres of the SP in C# code?</p>
<p>I use the following code for it:</p>
<p>OracleSP</p>
<pre><code>PROCEDURE TABMPWORKREQUEST_INS(INTWORKREQUEST_ IN NUMBER, VCWORKREQUESTNUMBER_ OUT VARCHAR2,
INTREQUESTEDBY_ IN NUMBER, INTWORKTYPE_ IN NUMBER,INTACTIONTYPE_ IN NUMBER,
INTPRIORITY_ IN NUMBER, INTRECORDID_ IN NUMBER, INTPERMITREQUIRED_ IN NUMBER, VCINSPECTIONREQUIRED_ IN CHAR,
VCLASTUSERID_ IN VARCHAR2, INTCOSTCENTRECODE_ IN NUMBER, VCBUDGETHEAD_ IN VARCHAR2
, VCREFERENCEWORKORDERNUMBER_ IN VARCHAR2, VCJOBDESCRIPTION_ IN VARCHAR2,
VCSTATUS_ IN CHAR, VCHISTORYFLAG_ IN CHAR, VCREASONCODE_ IN VARCHAR2
, VCMSSNUMBER_ IN VARCHAR2, INTAUTHORIZELEVEL_ IN NUMBER, INTPRINTFLAG_ IN NUMBER,
INTINSPECTIONFLAG_ IN NUMBER, INTDAYNUMBER_ IN NUMBER, INTDURATION_ IN NUMBER, INTPROGRESS_ IN NUMBER,
INTWORKSHOPFLAG_ IN CHAR)
IS
EXISTANCE number;
UID_ VARCHAR(5);
SS varchar2(20);
BEGIN
SELECT COUNT(*) into EXISTANCE FROM TABMPWORKREQUEST WHERE INTWORKREQUEST = INTWORKREQUEST_ ;
IF VCLASTUSERID_ = '0' THEN
UID_ := 'U2';
ELSE
UID_ := VCLASTUSERID_;
END IF;
select GetWorkOrderNumber(INTREQUESTEDBY_) INTO SS from dual ;
VCWORKREQUESTNUMBER_ :=SS;
INSERT INTO TABMPWORKREQUEST
VALUES( CMMS.SEQTABMPWORKREQUEST.NEXTVAL , SS , sysdate , INTrequestedby_ ,
INTworktype_ , INTactiontype_ , INTpriority_ , Intrecordid_ , Intpermitrequired_ , Vcinspectionrequired_ ,
Vclastuserid_ , SYSDATE , sysdate , INTcostcentrecode_ , Vcbudgethead_ , sysdate ,
Vcreferenceworkordernumber_ , Vcjobdescription_ , '01' , Vchistoryflag_ , Vcreasoncode_ ,
sysdate , sysdate , Vcmssnumber_ , Intauthorizelevel_ , Intprintflag_ , Intinspectionflag_ ,
Intdaynumber_ , Intduration_ , Intprogress_ , Intworkshopflag_ );
END TABMPWORKREQUEST_INS;
</code></pre>
<p>and c# code</p>
<pre><code> public bool InsertMpWORKREQUEST(ClsFieldsMpWORKREQUEST fieldsMpWORKREQUEST)
{
string DTBDDATETIME;
if (fieldsMpWORKREQUEST.DTBDDATETIME != null)
{
DTBDDATETIME = String.Format("{0:dd/MM/yyyy HH:mm:ss}", fieldsMpWORKREQUEST.DTBDDATETIME);
DTBDDATETIME = "TO_DATE('" + DTBDDATETIME + "', 'MM/DD/YYYY HH24:MI:SS')";
}
else
{
DTBDDATETIME = "NULL";
}
string DateExpire = string.Empty;
if (fieldsMpWORKREQUEST.DTEXPIRYDATE != null)
{
DateExpire = String.Format("{0:dd/MM/yyyy HH:mm:ss}", fieldsMpWORKREQUEST.DTEXPIRYDATE);
DateExpire = "TO_DATE('" + DateExpire + "', 'MM/DD/YYYY HH24:MI:SS')";
}
else
{
DateExpire = "NULL";
}
string DtStartDate;
if (fieldsMpWORKREQUEST.DTSTARTDATE != null)
{
DtStartDate = String.Format("{0:dd/MM/yyyy HH:mm:ss}", fieldsMpWORKREQUEST.DTSTARTDATE);
DtStartDate = "TO_DATE('" + DtStartDate + "', 'MM/DD/YYYY HH24:MI:SS')";
}
else
{
DtStartDate = "NULL";
}
string DtComplementationDate;
if (fieldsMpWORKREQUEST.DTCOMPLETIONDATE != null)
{
DtComplementationDate = String.Format("{0:dd/MM/yyyy HH:mm:ss}", fieldsMpWORKREQUEST.DTCOMPLETIONDATE);
DtComplementationDate = "TO_DATE('" + DtComplementationDate + "', 'MM/DD/YYYY HH24:MI:SS')";
}
else
{
DtComplementationDate = "NULL";
}
OracleConnection cn = new OracleConnection(this.GetConnectionString());
OracleCommand cmd = new OracleCommand("CMMS_MPWORKREQUEST_PKG.TABMPWORKREQUEST_INS", cn);
cmd.CommandType = CommandType.StoredProcedure;
OracleParameter INTWORKREQUEST = new OracleParameter();
INTWORKREQUEST.ParameterName = "INTWORKREQUEST_";
INTWORKREQUEST.OracleType = OracleType.Number;
INTWORKREQUEST.Direction = ParameterDirection.Input;
INTWORKREQUEST.Value = fieldsMpWORKREQUEST.INTWORKREQUEST;
cmd.Parameters.Add(INTWORKREQUEST);
// cmd.Parameters.AddWithValue("VCWORKREQUESTNUMBER_", fieldsMpWORKREQUEST.VCWORKREQUESTNUMBER).Direction=ParameterDirection.Output;
OracleParameter requestNo = new OracleParameter();
requestNo.ParameterName = "VCWORKREQUESTNUMBER_";
requestNo.OracleType = OracleType.VarChar;
requestNo.Size = 14;
requestNo.Direction = ParameterDirection.Output;
cmd.Parameters.Add(requestNo);
OracleParameter INTREQUESTEDBY = new OracleParameter();
INTREQUESTEDBY.ParameterName = "INTREQUESTEDBY_";
INTREQUESTEDBY.OracleType = OracleType.Number;
INTREQUESTEDBY.Direction = ParameterDirection.Input;
INTREQUESTEDBY.Value = fieldsMpWORKREQUEST.INTREQUESTEDBY.INTSECTIONID;
cmd.Parameters.Add(INTREQUESTEDBY);
OracleParameter INTWORKTYPE = new OracleParameter();
INTWORKTYPE.ParameterName = "INTWORKTYPE_";
INTWORKTYPE.OracleType = OracleType.Number;
INTWORKTYPE.Direction = ParameterDirection.Input;
INTWORKTYPE.Value = fieldsMpWORKREQUEST.INTREQUESTEDBY.INTSECTIONID;
cmd.Parameters.Add(INTWORKTYPE);
OracleParameter INTACTIONTYPE = new OracleParameter();
INTACTIONTYPE.ParameterName = "INTACTIONTYPE_";
INTACTIONTYPE.OracleType = OracleType.Number;
INTACTIONTYPE.Direction = ParameterDirection.Input;
INTACTIONTYPE.Value = fieldsMpWORKREQUEST.INTACTIONTYPE.INTSECTIONID;
cmd.Parameters.Add(INTACTIONTYPE);
OracleParameter INTPRIORITY = new OracleParameter();
INTPRIORITY.ParameterName = "INTPRIORITY_";
INTPRIORITY.OracleType = OracleType.Number;
INTPRIORITY.Direction = ParameterDirection.Input;
INTPRIORITY.Value = fieldsMpWORKREQUEST.INTPRIORITY.INTGENERALCODE;
cmd.Parameters.Add(INTPRIORITY);
OracleParameter INTRECORDID = new OracleParameter();
INTRECORDID.ParameterName = "INTRECORDID_";
INTRECORDID.OracleType = OracleType.Number;
INTRECORDID.Direction = ParameterDirection.Input;
INTRECORDID.Value = fieldsMpWORKREQUEST.INTRECORDID;
cmd.Parameters.Add(INTRECORDID);
OracleParameter INTPERMITREQUIRED = new OracleParameter();
INTPERMITREQUIRED.ParameterName = "INTPERMITREQUIRED_";
INTPERMITREQUIRED.OracleType = OracleType.Number;
INTPERMITREQUIRED.Direction = ParameterDirection.Input;
INTPERMITREQUIRED.Value = fieldsMpWORKREQUEST.INTPERMITREQUIRED;
cmd.Parameters.Add(INTPERMITREQUIRED);
OracleParameter VCINSPECTIONREQUIRED = new OracleParameter();
VCINSPECTIONREQUIRED.ParameterName = "VCINSPECTIONREQUIRED_";
VCINSPECTIONREQUIRED.OracleType = OracleType.Char;
VCINSPECTIONREQUIRED.Direction = ParameterDirection.Input;
VCINSPECTIONREQUIRED.Value = fieldsMpWORKREQUEST.VCINSPECTIONREQUIRED;
cmd.Parameters.Add(VCINSPECTIONREQUIRED);
OracleParameter VCLASTUSERID = new OracleParameter();
VCLASTUSERID.ParameterName = "VCLASTUSERID_";
VCLASTUSERID.OracleType = OracleType.VarChar;
VCLASTUSERID.Direction = ParameterDirection.Input;
VCLASTUSERID.Value = fieldsMpWORKREQUEST.VCLASTUSERID;
cmd.Parameters.Add(VCLASTUSERID);
OracleParameter INTCOSTCENTRECODE = new OracleParameter();
INTCOSTCENTRECODE.ParameterName = "INTCOSTCENTRECODE_";
INTCOSTCENTRECODE.OracleType = OracleType.Number;
INTCOSTCENTRECODE.Direction = ParameterDirection.Input;
INTCOSTCENTRECODE.Value = fieldsMpWORKREQUEST.INTCOSTCENTRECODE.INTGENERALCODE;
cmd.Parameters.Add(INTCOSTCENTRECODE);
OracleParameter vCBUDGETHEAD = new OracleParameter();
vCBUDGETHEAD.ParameterName = "VCBUDGETHEAD_";
vCBUDGETHEAD.OracleType = OracleType.VarChar;
vCBUDGETHEAD.Direction = ParameterDirection.Input;
vCBUDGETHEAD.Value = fieldsMpWORKREQUEST.VCBUDGETHEAD;
cmd.Parameters.Add(vCBUDGETHEAD);
OracleParameter VCREFERENCEWORKORDERNUMBER = new OracleParameter();
VCREFERENCEWORKORDERNUMBER.ParameterName = "VCREFERENCEWORKORDERNUMBER_";
VCREFERENCEWORKORDERNUMBER.OracleType = OracleType.VarChar;
VCREFERENCEWORKORDERNUMBER.Direction = ParameterDirection.Input;
VCREFERENCEWORKORDERNUMBER.Value = fieldsMpWORKREQUEST.VCREFERENCEWORKORDERNUMBER;
cmd.Parameters.Add(VCREFERENCEWORKORDERNUMBER);
OracleParameter VCJOBDESCRIPTION = new OracleParameter();
VCJOBDESCRIPTION.ParameterName = "VCJOBDESCRIPTION_";
VCJOBDESCRIPTION.OracleType = OracleType.VarChar;
VCJOBDESCRIPTION.Direction = ParameterDirection.Input;
VCJOBDESCRIPTION.Value = fieldsMpWORKREQUEST.VCJOBDESCRIPTION;
cmd.Parameters.Add(VCJOBDESCRIPTION);
OracleParameter VCSTATUS = new OracleParameter();
VCSTATUS.ParameterName = "VCSTATUS_";
VCSTATUS.OracleType = OracleType.Char;
VCSTATUS.Direction = ParameterDirection.Input;
VCSTATUS.Value = fieldsMpWORKREQUEST.VCSTATUS;
cmd.Parameters.Add(VCSTATUS);
OracleParameter VCHISTORYFLAG = new OracleParameter();
VCHISTORYFLAG.ParameterName = "VCHISTORYFLAG_";
VCHISTORYFLAG.OracleType = OracleType.Char;
VCHISTORYFLAG.Direction = ParameterDirection.Input;
VCHISTORYFLAG.Value = fieldsMpWORKREQUEST.VCHISTORYFLAG;
cmd.Parameters.Add(VCHISTORYFLAG);
OracleParameter VCREASONCODE = new OracleParameter();
VCREASONCODE.ParameterName = "VCREASONCODE_";
VCREASONCODE.OracleType = OracleType.VarChar;
VCREASONCODE.Direction = ParameterDirection.Input;
VCREASONCODE.Value = fieldsMpWORKREQUEST.VCREASONCODE;
cmd.Parameters.Add(VCREASONCODE);
OracleParameter VCMSSNUMBER = new OracleParameter();
VCMSSNUMBER.ParameterName = "VCMSSNUMBER_";
VCMSSNUMBER.OracleType = OracleType.VarChar;
VCMSSNUMBER.Direction = ParameterDirection.Input;
VCMSSNUMBER.Value = fieldsMpWORKREQUEST.VCMSSNUMBER;
cmd.Parameters.Add(VCMSSNUMBER);
OracleParameter INTAUTHORIZELEVEL = new OracleParameter();
INTAUTHORIZELEVEL.ParameterName = "INTAUTHORIZELEVEL_";
INTAUTHORIZELEVEL.OracleType = OracleType.Number;
INTAUTHORIZELEVEL.Direction = ParameterDirection.Input;
INTAUTHORIZELEVEL.Value = fieldsMpWORKREQUEST.INTAUTHORIZELEVEL;
cmd.Parameters.Add(INTAUTHORIZELEVEL);
OracleParameter INTPRINTFLAG = new OracleParameter();
INTPRINTFLAG.ParameterName = "INTPRINTFLAG_";
INTPRINTFLAG.OracleType = OracleType.Number;
INTPRINTFLAG.Direction = ParameterDirection.Input;
INTPRINTFLAG.Value = fieldsMpWORKREQUEST.INTPRINTFLAG;
cmd.Parameters.Add(INTPRINTFLAG);
OracleParameter INTINSPECTIONFLAG = new OracleParameter();
INTINSPECTIONFLAG.ParameterName = "INTINSPECTIONFLAG_";
INTINSPECTIONFLAG.OracleType = OracleType.Number;
INTINSPECTIONFLAG.Direction = ParameterDirection.Input;
INTINSPECTIONFLAG.Value = fieldsMpWORKREQUEST.INTINSPECTIONFLAG;
cmd.Parameters.Add(INTINSPECTIONFLAG);
OracleParameter INTDAYNUMBER = new OracleParameter();
INTDAYNUMBER.ParameterName = "INTDAYNUMBER_";
INTDAYNUMBER.OracleType = OracleType.Number;
INTDAYNUMBER.Direction = ParameterDirection.Input;
INTDAYNUMBER.Value = fieldsMpWORKREQUEST.INTDAYNUMBER;
cmd.Parameters.Add(INTDAYNUMBER);
OracleParameter INTDURATION = new OracleParameter();
INTDURATION.ParameterName = "INTDURATION_";
INTDURATION.OracleType = OracleType.Number;
INTDURATION.Direction = ParameterDirection.Input;
INTDURATION.Value = fieldsMpWORKREQUEST.INTDURATION;
cmd.Parameters.Add(INTDURATION);
OracleParameter INTPROGRESS = new OracleParameter();
INTPROGRESS.ParameterName = "INTPROGRESS_";
INTPROGRESS.OracleType = OracleType.Number;
INTPROGRESS.Direction = ParameterDirection.Input;
INTPROGRESS.Value = fieldsMpWORKREQUEST.INTPROGRESS;
cmd.Parameters.Add(INTPROGRESS);
OracleParameter INTWORKSHOPFLAG = new OracleParameter();
INTWORKSHOPFLAG.ParameterName = "INTWORKSHOPFLAG_";
INTWORKSHOPFLAG.OracleType = OracleType.Char;
INTWORKSHOPFLAG.Direction = ParameterDirection.Input;
INTWORKSHOPFLAG.Value = fieldsMpWORKREQUEST.INTWORKSHOPFLAG;
cmd.Parameters.Add(INTWORKSHOPFLAG);
string requestNo2 = string.Empty;
int rowEfect = 0;
try
{
cn.Open();
rowEfect = cmd.ExecuteNonQuery();
requestNo2 = cmd.Parameters["VCWORKREQUESTNUMBER_"].Value.ToString();
}
catch (Exception)
{
throw;
}
finally
{
if (cn.State != ConnectionState.Closed) cn.Close();
}
return rowEfect > 0;
}
</code></pre>
<p>But I get the following error:</p>
<pre><code>ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'TABMPWORKREQUEST_INS'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
</code></pre>
<p>How can I fix this problem?</p>
| 1 | 5,802 |
Changes using Winspool.drv in Windows 7 64 bit from Windows XP 32 bit
|
<p>I have some C# code (VS2010;fx2) which is used to carry out printer functions. This code works fine in Windows XP environment. Changing to Windows 7, it no longer works correctly.</p>
<p>The first different behaviour is that the GetPrinterNames() method now only returns local printers. As you can see, the flags are set to include NETWORK printers also. I've tried different flags, but with no success.</p>
<p>Is there a different library I should be referencing in Windows 7 / 64 bit version?</p>
<p>Printer helper class with code shown below:</p>
<pre><code>internal class Printers
{
...
[DllImport("winspool.drv", SetLastError = true)]
static extern bool EnumPrintersW(Int32 flags, [MarshalAs(UnmanagedType.LPTStr)] string printerName,
Int32 level, IntPtr buffer, Int32 bufferSize, out Int32 requiredBufferSize,
out Int32 numPrintersReturned);
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool EnumPrinters(PrinterEnumFlags Flags, string Name, uint Level, IntPtr pPrinterEnum, uint cbBuf, ref uint pcbNeeded, ref uint pcReturned);
...
...
public static string[] GetPrinterNames()
{
List<string> returnVal = new List<string>();
foreach(PRINTER_INFO_2 info in enumPrinters(PrinterEnumFlags.PRINTER_ENUM_LOCAL | PrinterEnumFlags.PRINTER_ENUM_NETWORK))
{
returnVal.Add(info.pPrinterName);
}
return returnVal.ToArray();
}
...
private static PRINTER_INFO_2[] enumPrinters(PrinterEnumFlags Flags)
{
uint cbNeeded = 0;
uint cReturned = 0;
if (EnumPrinters(Flags, null, 2, IntPtr.Zero, 0, ref cbNeeded, ref cReturned))
{
return null;
}
int lastWin32Error = Marshal.GetLastWin32Error();
if (lastWin32Error == ERROR_INSUFFICIENT_BUFFER)
{
IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded);
if (EnumPrinters(Flags, null, 2, pAddr, cbNeeded, ref cbNeeded, ref cReturned))
{
PRINTER_INFO_2[] printerInfo2 = new PRINTER_INFO_2[cReturned];
int offset = pAddr.ToInt32();
Type type = typeof(PRINTER_INFO_2);
int increment = Marshal.SizeOf(type);
for (int i = 0; i < cReturned; i++)
{
printerInfo2[i] = (PRINTER_INFO_2)Marshal.PtrToStructure(new IntPtr(offset), type);
offset += increment;
}
Marshal.FreeHGlobal(pAddr);
return printerInfo2;
}
lastWin32Error = Marshal.GetLastWin32Error();
}
throw new System.ComponentModel.Win32Exception(lastWin32Error);
}
...
[FlagsAttribute]
enum PrinterEnumFlags
{
PRINTER_ENUM_DEFAULT = 0x00000001,
PRINTER_ENUM_LOCAL = 0x00000002,
PRINTER_ENUM_CONNECTIONS = 0x00000004,
PRINTER_ENUM_FAVORITE = 0x00000004,
PRINTER_ENUM_NAME = 0x00000008,
PRINTER_ENUM_REMOTE = 0x00000010,
PRINTER_ENUM_SHARED = 0x00000020,
PRINTER_ENUM_NETWORK = 0x00000040,
PRINTER_ENUM_EXPAND = 0x00004000,
PRINTER_ENUM_CONTAINER = 0x00008000,
PRINTER_ENUM_ICONMASK = 0x00ff0000,
PRINTER_ENUM_ICON1 = 0x00010000,
PRINTER_ENUM_ICON2 = 0x00020000,
PRINTER_ENUM_ICON3 = 0x00040000,
PRINTER_ENUM_ICON4 = 0x00080000,
PRINTER_ENUM_ICON5 = 0x00100000,
PRINTER_ENUM_ICON6 = 0x00200000,
PRINTER_ENUM_ICON7 = 0x00400000,
PRINTER_ENUM_ICON8 = 0x00800000,
PRINTER_ENUM_HIDE = 0x01000000
}
</code></pre>
<p>EDIT: Code edited to reduce size (areas of less interest removed).</p>
| 1 | 1,724 |
How to: PHP SoapClient example incorporating WSSE Header
|
<p>I have a WSDL file. Using SOAP UI, I was able to generate the SOAP request message...</p>
<p><strong>Request SOAP message:</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" SOAP-ENV:mustUnderstand="1">
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="ABCGID-123456789">
<wsse:Username>Spiderman</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">spinningtheweb</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<FooInterface_Bar_Input xmlns="http://example.com/interfaces">
<Input1>Howdy</Input1>
<Input2>Partner</Input2>
</FooInterface_Bar_Input>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p><strong>And here is the response SOAP message:</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns:FooInterface_Bar_Output xmlns:ns="http://example.com/interfaces">
<ns:Output1>Banana</ns:Output1>
<ns:Output2>Papaya</ns:Output2>
<listOfOtherOutputs>
<Output3>Apple</Output3>
</listOfOtherOutputs>
</ns:FooInterface_Bar_Output>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p><strong>QUESTION:</strong></p>
<p>Using PHP's SoapClient, how do I:</p>
<ol>
<li>init SoapClient and load the WSDL file (which sits in my server)?</li>
<li>Set the header?</li>
<li>Send the SOAP request?</li>
<li>And finally, get a SOAP response back and extract the values of <strong>Output1, Output2, and Output3</strong> into variables?</li>
</ol>
<p>I've browse previous StackOverflow questions regarding SOAP and WSSE headers, but could not find the answer.</p>
<p>Thanks very much in advance for your time and your expert help!</p>
<p>PS: I can accomplish the above using cURL. But I want to know how to do it using SoapClient. Thanks again!</p>
| 1 | 1,172 |
Overwrite csv file on s3 fails in pyspark
|
<p>When I load data into pyspark dataframe from s3 bucket then make some manipulations (join, union) and then I try to overwrite the same path <strong>('data/csv/')</strong> I read before. I'm getting this error:</p>
<pre><code>py4j.protocol.Py4JJavaError: An error occurred while calling o4635.save.
: org.apache.spark.SparkException: Job aborted.
at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:224)
at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:154)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:104)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:102)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:122)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:80)
at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:80)
at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:654)
at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:654)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:77)
at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:654)
at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:273)
at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:267)
at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:225)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:282)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.spark.SparkException: Job aborted due to stage failure: Task 200 in stage 120.0 failed 4 times, most recent failure: Lost task 200.3 in stage 120.0: java.io.FileNotFoundException: Key 'data/csv/part-00000-68ea927d-1451-4a84-acc7-b91e94d0c6a3-c000.csv' does not exist in S3
It is possible the underlying files have been updated. You can explicitly invalidate the cache in Spark by running 'REFRESH TABLE tableName' command in SQL or by recreating the Dataset/DataFrame involved.
</code></pre>
<pre><code>csv_a = spark \
.read \
.format('csv') \
.option("header", "true") \
.load('s3n://mybucket/data/csv') \
.where('some condition')
csv_b = spark \
.read \
.format('csv') \
.option("header", "true") \
.load('s3n://mybucket/data/model/csv')
.alias('csv')
# Reading glue categories data
cc = spark \
.sql("select * from mydatabase.mytable where month='06'") \
.alias('cc')
# Joining and Union
output = csv_b \
.join(cc, (csv_b.key == cc.key), 'inner') \
.select('csv.key', 'csv.created_ts', 'cc.name', 'csv.text') \
.drop_duplicates(['key']) \
.union(csv_a) \
.orderBy('name') \
.coalesce(1) \
.write \
.format('csv') \
.option('header', 'true') \
.mode('overwrite') \
.save('s3n://mybucket/data/csv')
</code></pre>
<p>I need to read data from s3 location, then, join, union with another data and finally overwrite initial path to keep only one csv file with clean joined data.</p>
<p>If I try to read (load) data from another s3 path not the same as I need to overwrite, it works and overwrites ok.</p>
<p>Any ideas why does this error happen?</p>
| 1 | 1,732 |
Is there a benefit in using old style `object` instead of `class` in Delphi?
|
<p>In Delphi <strong>sane</strong> people use a <code>class</code> to define objects.<br>
In Turbo Pascal for Windows we used <code>object</code> and today you can still use <code>object</code> to create an object. </p>
<p>The difference is that a <code>object</code> lives on the stack and a <code>class</code> lives on the heap.<br>
And of course the <code>object</code> is depreciated. </p>
<p><kbd>Putting all that aside:</kbd></p>
<p><strong>is there a benefit to be had, speed wise by using <code>object</code> instead of class?</strong></p>
<p><em>I know that <code>object</code> is broken in Delphi 2009, but I've got a special use case<sup>1)</sup> where speed matters and I'm trying to find if using <code>object</code> will make my thing faster without making it buggy</em><br>
This code base is in Delphi 7, but I may port it to Delphi 2007, haven't decided yet.</p>
<hr>
<p><sup>1)</sup> Conway's game of life</p>
<p><strong>Long comment</strong><br>
Thanks all for pointing me in the right direction.</p>
<p>Let me explain a bit more. I'm trying to do a faster implementation of <strong><a href="http://en.wikipedia.org/wiki/Hashlife" rel="noreferrer">hashlife</a></strong>, <a href="http://drdobbs.com/high-performance-computing/184406478" rel="noreferrer">see also here</a> or <a href="http://dotat.at/prog/life/hashlife.c" rel="noreferrer">here for simple sourcecode</a></p>
<p>The current record holder is <a href="http://golly.sourceforge.net/" rel="noreferrer">golly</a>, but golly uses a straight translation of Bill Gospher original lisp code (which is brilliant as an algorithm, but not optimized at the micro level at all). Hashlife enables you to calculate a generation in O(log(n)) time.</p>
<p>It does this by using a space/time trade off. And for this reason hashlife needs a lot of memory, gigabytes are not unheard of. In return you can calculate generation 2^128 (340282366920938463463374607431770000000) using generation 2^127 (170141183460469231731687303715880000000) in o(1) time. </p>
<p>Because hashlife needs to compute hashes for all sub-patterns that occur in a larger pattern, allocation of objects needs to be fast.</p>
<p>Here's the solution I've settled upon:</p>
<p><strong>Allocation optimization</strong><br>
I allocate one big block of physical memory (user settable) lets say 512MB. Inside this blob I allocate what I call <strong>cheese stacks</strong>. This is a normal stack where I push and pop, but a pop can also be from the middle of the stack. If that happens I mark it on the <code>free</code> list (this is a normal stack). When pushing I check the <code>free</code> list first if nothing is free I push as normal. I'll be using records as advised it looks like the solution with the least amount of overhead. </p>
<p>Because of the way hashlife works, very little <code>pop</code>ping takes place and a lot of <code>push</code>es. I keep separate stacks for structures of different sizes, making sure to keep memory access aligned on 4/8/16 byte boundaries. </p>
<p><strong>Other optimizations</strong> </p>
<ul>
<li>recursion removal </li>
<li>cache optimization</li>
<li>use of <code>inline</code></li>
<li>precalculation of hashes (akin to rainbow tables)</li>
<li>detection of pathological cases and use of fall-back algorithm</li>
<li>use of GPU</li>
</ul>
| 1 | 1,033 |
Digital Personna SDK Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
|
<p>i was using Digital persona SDK for this exercise when i try to close the form it throws</p>
<blockquote>
<p>Cross-thread operation not valid: Control accessed from a thread other
than the thread it was created on</p>
</blockquote>
<p>this code was used to login </p>
<pre><code>SqlConnection dataBaseConnection = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=DemoDB;Integrated Security=True");
public delegate void OnTemplateEventHandler(DPFP.Template template);
Timer closeTimer = new Timer();
DPFP.Capture.Capture Capturer = new DPFP.Capture.Capture();
public login()
{
InitializeComponent();
closeTimer.Tick+=new EventHandler(closeTimer_Tick);
}
private DPFP.Template Template;
private DPFP.Verification.Verification Verificator;
int time = 0;
protected virtual void Init()
{
Capturer = new DPFP.Capture.Capture();
Capturer.EventHandler = this;
Verificator = new DPFP.Verification.Verification(); // Create a fingerprint template verificator
}
protected void start()
{
Capturer.StartCapture();
}
protected virtual void Process(DPFP.Sample sample)
{
drawPicture(convertingToBitmap(sample));
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(sample, DPFP.Processing.DataPurpose.Verification);
// Check quality of the sample and start verification if it's good
// TODO: move to a separate task
if (features != null)
{
// Compare the feature set with our template
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
Verificator.Verify(features, Template, ref result);
if (result.Verified)
{
MessageBox.Show("Login Success.");
this.Close(); // This the place where the exception is thrown
}
else
MessageBox.Show("The fingerprint was NOT VERIFIED.");
}
}
protected void stop()
{
Capturer.StopCapture();
}
protected DPFP.FeatureSet ExtractFeatures(DPFP.Sample Sample, DPFP.Processing.DataPurpose Purpose)
{
DPFP.Processing.FeatureExtraction Extractor = new DPFP.Processing.FeatureExtraction(); // Create a feature extractor
DPFP.Capture.CaptureFeedback feedback = DPFP.Capture.CaptureFeedback.None;
DPFP.FeatureSet features = new DPFP.FeatureSet();
Extractor.CreateFeatureSet(Sample, Purpose, ref feedback, ref features); // TODO: return features as a result?
if (feedback == DPFP.Capture.CaptureFeedback.Good)
return features;
else
return null;
}
private void drawPicture(Bitmap image)
{
this.Invoke(new Function(delegate()
{
fingerprintImage.Image = new Bitmap(image, fingerprintImage.Size);
}));
}
protected Bitmap convertingToBitmap(DPFP.Sample sample)
{
DPFP.Capture.SampleConversion convertor = new DPFP.Capture.SampleConversion();
Bitmap img = null;
convertor.ConvertToPicture(sample, ref img);
return img;
}
#region EventHandler Members:
public void OnComplete(object Capture, string ReaderSerialNumber, DPFP.Sample Sample)
{
//MakeReport("The fingerprint sample was captured.");
Process(Sample);
closeTimer.Start();
}
public void OnFingerGone(object Capture, string ReaderSerialNumber)
{
// MakeReport("The finger was removed from the fingerprint reader.");
}
public void OnFingerTouch(object Capture, string ReaderSerialNumber)
{
// MakeReport("The fingerprint reader was touched.");
}
public void OnReaderConnect(object Capture, string ReaderSerialNumber)
{
//MakeReport("The fingerprint reader was connected.");
}
public void OnReaderDisconnect(object Capture, string ReaderSerialNumber)
{
MessageBox.Show("The fingerprint reader was disconnected.");
}
public void OnSampleQuality(object Capture, string ReaderSerialNumber, DPFP.Capture.CaptureFeedback CaptureFeedback)
{
//if (CaptureFeedback == DPFP.Capture.CaptureFeedback.Good)
// MakeReport("The quality of the fingerprint sample is good.");
//else
// MakeReport("The quality of the fingerprint sample is poor.");
}
#endregion
</code></pre>
| 1 | 2,169 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.