title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
org.hibernate.HibernateException: No Session found for current thread
<p>I'm getting the above exception with Spring3 and Hibernte4</p> <p>The following is my bean xml file</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"&gt; &lt;context:annotation-config/&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="com.mysql.jdbc.Driver"/&gt; &lt;property name="url" value="jdbc:mysql://localhost:3306/GHS"/&gt; &lt;property name="username" value="root"/&gt; &lt;property name="password" value="newpwd"/&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="dialect"&gt;org.hibernate.dialect.MySQL5Dialect&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="packagesToScan"&gt; &lt;list&gt; &lt;value&gt;com.example.ghs.model.timetable&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="baseDAO" class="com.example.ghs.dao.BaseDAOImpl"/&gt; &lt;/beans&gt; </code></pre> <p>My BaseDAO class looks like this</p> <pre><code>public class BaseDAOImpl implements BaseDAO{ private SessionFactory sessionFactory; @Autowired public BaseDAOImpl(SessionFactory sessionFactory){ this.sessionFactory = sessionFactory; } @Override public Session getCurrentSession(){ return sessionFactory.getCurrentSession(); } } </code></pre> <p>The following code throws the exception in the title</p> <pre><code>public class Main { public static void main(String[] args){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dao-beans.xml"); BaseDAO bd = (BaseDAO) context.getBean("baseDAO"); bd.getCurrentSession(); } } </code></pre> <p>Does anyone have an idea about how to solve this problem?</p>
0
1,088
Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries
<p>I have action in my controller which calls the following method :</p> <pre><code>public IQueryable&lt;AaaUserContactInfo&gt; getcontactinfo(long[] id) { var organizationsiteids = from accountsitemapping in entities.AccountSiteMappings where id.Any(accountid =&gt; accountsitemapping.ACCOUNTID == accountid) select accountsitemapping.SITEID; var usersdepts = from userdept in entities.UserDepartments join deptdefinition in entities.DepartmentDefinitions on userdept.DEPTID equals deptdefinition.DEPTID where organizationsiteids.Any(accountid =&gt; deptdefinition.SITEID == accountid) select userdept; var contactsinfos = from userdept in usersdepts join contactinfo in entities.AaaUserContactInfoes on userdept.USERID equals contactinfo.USER_ID select contactinfo; return contactsinfos; } </code></pre> <p>But when I run the application and I navigate to the action method the folowing error will be raised on the view level:-</p> <pre><code>System.Data.EntityCommandExecutionException was unhandled by user code HResult=-2146232004 Message=An error occurred while executing the command definition. See the inner exception for details. Source=System.Data.Entity StackTrace: at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues) at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator() at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable&lt;TResult&gt;.GetEnumerator() at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source) at ASP._Page_Views_Home_CustomersDetails_cshtml.Execute() in c:\Users\Administrator\Desktop\new app DEMO2\MvcApplication4 - LATEST -\MvcApplication4\Views\Home\CustomersDetails.cshtml:line 6 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.StartPage.RunPage() at System.Web.WebPages.StartPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.&lt;&gt;c__DisplayClass1c.&lt;InvokeActionResultWithFilters&gt;b__19() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) InnerException: System.Data.SqlClient.SqlException HResult=-2146232060 Message=Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries. Source=.Net SqlClient Data Provider ErrorCode=-2146232060 Class=15 LineNumber=105 Number=191 Procedure="" StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean&amp; dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task&amp; task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) InnerException: </code></pre> <p>So what is causing this error??</p> <p>UPDATED:- <img src="https://i.stack.imgur.com/qa0FG.jpg" alt="enter image description here"></p>
0
2,083
Angular scrollable div
<p>I want to create an Angular App which displays a JSON data structure in a design which is very similar to a chatbox. I've created a component for the "chatbox" </p> <p>Example structure (also the only content in my chatbox.component.ts):</p> <pre><code> test = [ { "date":"1","sender":"x","answer":"hello"}, { "date": "2", "sender": "y", "answer": "hello my friend" }, { "date": "3", "sender": "z", "answer": "bye" } ]; </code></pre> <p>Chatbox.component.html :</p> <pre><code>&lt;div class="inboxContainer"&gt; &lt;tr *ngFor="let msg of test"&gt; &lt;div class="wrapper"&gt; &lt;div class="sender"&gt;Sender: {{msg.sender}}&lt;/div&gt; &lt;div class="date"&gt;Date : {{msg.date}}&lt;/div&gt; &lt;/div&gt; &lt;div class="answer"&gt;Message: {{msg.answer}}&lt;br&gt;&lt;/div&gt; &lt;/tr&gt; &lt;/div&gt; &lt;div class="newMessageContainer"&gt; &lt;mat-form-field&gt; &lt;mat-label&gt;New Message&lt;/mat-label&gt; &lt;textarea matInput cdkTextareaAutosize #autosize="cdkTextareaAutosize" cdkAutosizeMinRows="1" cdkAutosizeMaxRows="3"&gt;&lt;/textarea&gt; &lt;/mat-form-field&gt; &lt;/div&gt; &lt;div class ="sendMessageContainer"&gt; &lt;button mat-button&gt; Send &lt;/button&gt; &lt;/div&gt; </code></pre> <p>Chatbox.component.css :</p> <pre><code>.inboxContainer { width: 40vw; height: 60vh; border: 1px solid black; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } .newMessageContainer { margin: auto; position: absolute; top: 80vh; left: 30vw; bottom: 0; right: 0; } .mat-form-field { width: 30vw; top:0.1vh; } .mat-button { left: 4vw; top:1.4vh; background-color: #B29B59; } .sendMessageContainer { margin: auto; position: absolute; top: 80vh; left: 60vw; bottom: 0; right: 0; } .wrapper { display:flex; } .date { border:1px solid black; width: 20vw; border-right:none; border-left:none; } .sender { border:1px solid black; width: 20vw; border-left:none; } .answer { width: 38.8vw; height: 18vh; } </code></pre> <p>The button itself can be ignored, its really just the way of displaying the structure. Right the messages get displayed like that : <a href="https://i.stack.imgur.com/mfbqV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mfbqV.png" alt="Chat"></a> Its not designed yet and its not really important right now. Im able to display 3 messages but if I try to display 4,5 or 6 messages it overflows though the border (the border is fixed and the size should stay like that).<br> My question would be : How can I add a scrollbar to the div?</p> <p>Heres also an example that shows how it looks when I try to display 4 messages : <a href="https://i.stack.imgur.com/xJVcT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xJVcT.png" alt="enter image description here"></a></p>
0
1,333
Parsing Json File using Jackson
<pre><code>{ "TestSuite":{ "TestSuiteInfo":{ "-description":"parse" }, "TestCase":[ { "TestCaseData":{ "-sequence":"sequential", "-testNumber":"2", "-testCaseFile":"testcase\\Web\\Ab.xml" } }, { "TestCaseData":{ "-sequence":"sequential", "-testNumber":"3", "-testCaseFile":"testcase\\Web\\BC.xml" } } ] } } </code></pre> <p>My Pojos are:</p> <pre><code>public class TestSuite { private TestSuiteInfo testSuiteInfo; private TestCase listOfTestCases; public TestSuiteInfo getTestSuiteInfo() { return testSuiteInfo; } public void setTestSuiteInfo(TestSuiteInfo testSuiteInfo) { this.testSuiteInfo = testSuiteInfo; } public TestCase getListOfTestCases() { return listOfTestCases; } public void setListOfTestCases(TestCase listOfTestCases) { this.listOfTestCases = listOfTestCases; } } public class TestSuiteInfo { private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } import java.util.Iterator; import java.util.List; public class TestCase { private List&lt;TestCaseData&gt; testCaseData; public List&lt;TestCaseData&gt; getTestCaseData() { return testCaseData; } public void setTestCaseData(List&lt;TestCaseData&gt; testCaseData) { this.testCaseData = testCaseData; } } public class TestCaseData { private String sequence; private int testNumber; private String testCaseFile; public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; } public int getTestNumber() { return testNumber; } public void setTestNumber(int testNumber) { this.testNumber = testNumber; } public String getTestCaseFile() { return testCaseFile; } public void setTestCaseFile(String testCaseFile) { this.testCaseFile = testCaseFile; } } </code></pre> <p>I haven't use Jackson before, will really appreciate if anyone could help me in parsing the file and getting the objects. I am trying to parse this from past two days, but didnt got any success</p>
0
1,058
Can I remove this permission? (It cause INSTALL_FAILED_DUPLICATE_PERMISSION in Android 5.0 device)
<p>My tester said that he couldn't install the app from Play Store to his Nexus 5 (Lollipop). He said he got this error</p> <pre><code>Unknown error code during application install “-505” </code></pre> <p>I took his phone and try to install the app via adb, I got this error</p> <pre><code>Failure [INSTALL_FAILED_DUPLICATE_PERMISSION perm=com.example.gcm.permission.C2D_MESSAGE pkg=com.mailchimp.alterego] </code></pre> <p>After some reading, I came across this writing from @Commonsware </p> <p><a href="http://commonsware.com/blog/2014/08/04/custom-permission-vulnerability-l-developer-preview.html" rel="nofollow noreferrer">http://commonsware.com/blog/2014/08/04/custom-permission-vulnerability-l-developer-preview.html</a></p> <p>It's clearly that both my app and Mailchimp app (which installed on my tester's phone) has duplicated permission, <strong>com.example.gcm.permission.C2D_MESSAGE</strong>. I then check my git log to see when did I add that line to my AndroidManifest and found that it was when I implement GCM. Back then, I followed this tutorial</p> <p><a href="https://developer.android.com/google/gcm/client.html" rel="nofollow noreferrer">https://developer.android.com/google/gcm/client.html</a></p> <p><img src="https://i.stack.imgur.com/0iyjF.png" alt="enter image description here"></p> <p>I guess, both I and Mailchimp developer follow the same tutorial, added same permission and now both our app has duplicate permission. </p> <p>So, I remove that permission from my AndroidManifest and now I'm able to install my app on my tester's phone. I test the GCM message by sending to package to GCM server from my php script and app still got GCM message as it was. </p> <p>So, will there be other issue raised because of that missing permission and what is the point of having that permission anyway? (since without it, my app still got GCM message)</p> <p>My concern is, if our app is using a plugin/library that required permission. We won't be able to install our app on Lollipop device if there is another installed app which using the same library, isn't it?</p> <p><strong>-- NOTE --</strong></p> <p>I already read this question, few people suggest the same thing to what I did, remove permission. But no one talking about what will happen after we do it or why do we have to add it.</p> <p><a href="https://stackoverflow.com/questions/27043933/install-failed-duplicate-permission-c2d-message">INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE</a></p> <p><strong>-- EDIT 1 --</strong></p> <p>I went back to the tutorial, the tutorial was right, it was my wrong implementation </p> <p><img src="https://i.stack.imgur.com/vYnqS.png" alt="enter image description here"></p> <p>I (and Mailchimp developer) should add permission with the name of our <strong>app package + ".permission.C2D_MESSAGE"</strong> instead of just copy and paste com.example.gcm.permission.C2D_MESSAGE</p> <pre><code>&lt;permission android:name="com.mycompany.myappname.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt; </code></pre> <p>But, this raise another question to me, tutorial said that if we don't add this permission or the name doesn't match the pattern, app won't get the message.But I got the message when I test even when I remove this pemission... weird.</p>
0
1,103
Unexpected token 'END OF FILE' at position 0 (JSON)
<p>I'm trying to retreive a name from a UUID via a website, using the API Mojang provided. </p> <p>This is the code I use (I verified that it works):</p> <pre><code>@Override public Map&lt;UUID, String&gt; call() throws Exception { Map&lt;UUID, String&gt; uuidStringMap = new HashMap&lt;UUID, String&gt;(); for (UUID uuid : uuids) { HttpURLConnection connection = (HttpURLConnection) new URL( PROFILE_URL + uuid.toString().replace("-", "")) .openConnection(); JSONObject response; System.out.println("String: " + fromStream(connection.getInputStream())); System.out.print("Line: " + uuid.toString()); String name = null; try { response = (JSONObject) jsonParser .parse(new InputStreamReader(connection.getInputStream())); name = (String) response.get("name"); if (name == null) { continue; } String cause = (String) response.get("cause"); String errorMessage = (String) response.get("errorMessage"); if (cause != null &amp;&amp; cause.length() &gt; 0) { throw new IllegalStateException(errorMessage); } } catch (Exception e) { System.out.print("Could not parse uuid '" + uuid.toString() + "' to name!"); System.out.print("Trying Bukkit.getOfflinePlayer()"); OfflinePlayer oPlayer = Bukkit.getOfflinePlayer(uuid); if (oPlayer != null &amp;&amp; oPlayer.getFirstPlayed() != 0) { name = oPlayer.getName(); System.out.print("Got player " + name); } else { System.out.print("Could not retrieve player with Bukkit.getOfflinePlayer()"); e.printStackTrace(); } //throw new Exception("Could not parse uuid '" + uuid.toString() + "' to name!"); } uuidStringMap.put(uuid, name); } return uuidStringMap; } </code></pre> <p>Don't mind all the System.out.print lines, that's just to debug things.</p> <p>It errors with this error:</p> <pre><code>[17:35:56 WARN]: Unexpected token END OF FILE at position 0. [17:35:56 WARN]: at org.json.simple.parser.JSONParser.parse(Unknown Source) [17:35:56 WARN]: at org.json.simple.parser.JSONParser.parse(Unknown Source) [17:35:56 WARN]: at me.armar.plugins.autorank.util.uuid.NameFetcher.call( NameFetcher.java:59) [17:35:56 WARN]: at me.armar.plugins.autorank.util.uuid.UUIDManager$2.run (UUIDManager.java:222) [17:35:56 WARN]: at java.lang.Thread.run(Unknown Source) </code></pre> <p>Now, I've run the returned json through a few JSON online parsers. They all tell me the JSON is correct. This is the JSON that is being returned:</p> <pre><code>{"id":"cb994e15a57a4157953ab29577229ebe","name":"tator0 1","properties":[{"name":"textures","value":"eyJ0aW1lc3RhbXAiOjE0MDQ4MzM3NTM0MTYsInByb2ZpbGVJZCI6ImNiOTk0ZTE1YTU3YTQxNTc5NTNhYjI5NTc3MjI5ZWJlIiwicHJvZmlsZU5hbWUiOiJ0YXRvcjAxIiwiaXNQdWJsaWMiOnRydWUsInRleHR1cmVzIjp7IlNLSU4iOnsidXJsIjoiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS80Nzk5MjQ4NGJmNjUyODJhMTQzOWI0MGQ1NWU2ZTRjZGQxNGRmYzAyNGE0MzA3Y2M2YTM1M2Q4MzY1OThkZDUifX19","signature":"t93OEZ3BNa4vo47diKixJA0KWXqblUtWC9yZtTImuxfbSs0khqV02p58eeDF4Qbd4gy6VBQ0zv6N9oxRqhTKBQ1BG1FJHTfhGXFlLYlhHlXmVC5FMBnK0P//0T0PqVz7hlFgzW3YK6vaEf3tz5v5H/S+aCjZbCZ9vehDRx8vrV+SzZek0vuSHjm9ojooqwD4WQjCg1ZPZPtpYD/efj1OcTmS6xEnBEXbCTqOnK/wRbwfyKtezkJutFJ4UCrVCLos85ze79mMfBr67CtotFcQrVqRE9X5zShLatCCVlefPRo6K7TcKKzQYlTM24asaySfZYpv0ujGeHX2c6s4nKvg6vnwLnHT2RwDuJucCojAeoy9pRFq8jEtPSoiPGlA37NlLjChuLXp3cSYGhKIpgDFcXXNF+YsYOlN2XuYa2OpAt8EgDj09gd8r903a2apIVUDo4Hmln9rlI9J74KdifEZc3uUyazlP2BByID2YBcKr5mq5ye+MOKWkN8j5AaPNUKPNpFBXHkOOF/uE72VoBpsjDm0X9OfEx7xtNu+bA4jBObxnQKsD2qIvyhCtlmuN4S6G+VKtsBhiqlO7JTycAn1yij3aw3XhT763gALQNcUkjzERnyp55s8J7FlIpSvObNvndOgypPu4RpsHtkL/G16a/mxRJhljiAasiKX1WsYVig="}],"legacy":true} </code></pre> <p>I saw that there also was someone else with a kind of similiar issue, <a href="https://stackoverflow.com/questions/19945832/punexpected-token-end-of-file-at-position-0-p">here</a>.</p> <p><strong>Where could that unexpected token be?</strong></p>
0
2,160
Most common way of writing a HTML table with vertical headers?
<p>Hi all it's been a while since I've asked something, this is something that has been bothering me for a while, the question itself is in the title:</p> <blockquote> <p>What's your preferred way of writing HTML tables that have vertical headers?</p> </blockquote> <p>By vertical header I mean that the table has the header (<code>&lt;th&gt;</code>) tag on the left side (generally)</p> <blockquote> <p><strong>Header 1</strong> data data data<br> <strong>Header 2</strong> data data data<br> <strong>Header 3</strong> data data data</p> </blockquote> <p>They look like this, so far I've come up with two options</p> <h2>First Option</h2> <pre> <code> &lt;table id="vertical-1"&gt; &lt;caption&gt;First Way&lt;/caption&gt; &lt;tr&gt; &lt;th&gt;Header 1&lt;/th&gt; &lt;td&gt;data&lt;/td&gt;&lt;td&gt;data&lt;/td&gt;&lt;td&gt;data&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Header 2&lt;/th&gt; &lt;td&gt;data&lt;/td&gt;&lt;td&gt;data&lt;/td&gt;&lt;td&gt;data&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Header 2&lt;/th&gt; &lt;td&gt;data&lt;/td&gt;&lt;td&gt;data&lt;/td&gt;&lt;td&gt;data&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code> </pre> <p>The main advantage of this way is that you have the headers right (actually left) next to the data it represents, what I don't like however is that the <code>&lt;thead&gt;</code>, <code>&lt;tbody&gt;</code> and <code>&lt;tfoot&gt;</code> tags are missing, and there's no way to include them without breaking the nicelly placed together elements, which lead me to the second option.</p> <h2>Second Option</h2> <pre> <code> &lt;style type="text/css"&gt; #vertical-2 thead,#vertical-2 tbody{ display:inline-block; } &lt;/style&gt; &lt;table id="vertical-2"&gt; &lt;caption&gt;Second Way&lt;/caption&gt; &lt;thead&gt; &lt;tr&gt; &lt;th colspan="3"&gt;Header 1&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th colspan="3"&gt;Header 2&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th colspan="3"&gt;Header 3&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;row 1&lt;/td&gt; &lt;td&gt;row 1&lt;/td&gt; &lt;td&gt;row 1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;data&lt;/td&gt; &lt;td&gt;data&lt;/td&gt; &lt;td&gt;data&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;data&lt;/td&gt; &lt;td&gt;data&lt;/td&gt; &lt;td&gt;data&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;tfoot&gt; &lt;tr&gt; &lt;td colspan="4"&gt;Footer&lt;/td&gt; &lt;/tr&gt; &lt;/tfoot&gt; &lt;/table&gt; </code> </pre> <p>The main advantage here is that you have a fully descriptive html table, the drawbacks are that proper representation needs a bit of CSS for the <code>tbody</code> and <code>thead</code> tags and that the relation between the headers and data isn't very clear as I had my doubts when creating the markup.</p> <hr> <p>So, both ways render the table how it should, here a pitcure:</p> <p><img src="https://i.stack.imgur.com/s0YDr.png" alt="render"><br> With the headers on the left or right side if you would prefer it, so, any suggestions, alternatives, browser issues?</p>
0
2,139
Flutter and Firebase: Execution failed for task ':firebase_auth:compileDebugJavaWithJavac'
<p>I am trying to build my flutter application to interact with firebase. I have placed my google-services.json in the right place. However whenever i try to build the Android application i get the following run log:</p> <pre><code>Running "flutter packages get" in smart_diet_flutter... 2.6s Launching lib\main.dart on ONEPLUS A6003 in debug mode... Initializing gradle... Resolving dependencies... Gradle task 'assembleDebug'... registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection) registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection) registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection) registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection) registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection) C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:9: error: cannot find symbol import androidx.annotation.NonNull; ^ symbol: class NonNull location: package androidx.annotation C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:10: error: cannot find symbol import androidx.annotation.Nullable; ^ symbol: class Nullable location: package androidx.annotation C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:638: error: cannot find symbol private void reportException(Result result, @Nullable Exception exception) { ^ symbol: class Nullable location: class FirebaseAuthPlugin C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:550: error: cannot find symbol public void onComplete(@NonNull Task&lt;AuthResult&gt; task) { ^ symbol: class NonNull location: class FirebaseAuthPlugin.SignInCompleteListener C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:569: error: cannot find symbol public void onComplete(@NonNull Task&lt;Void&gt; task) { ^ symbol: class NonNull location: class FirebaseAuthPlugin.TaskVoidCompleteListener C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:587: error: cannot find symbol public void onComplete(@NonNull Task&lt;SignInMethodQueryResult&gt; task) { ^ symbol: class NonNull location: class FirebaseAuthPlugin.GetSignInMethodsCompleteListener C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:186: error: cannot find symbol public void onComplete(@NonNull Task&lt;AuthResult&gt; task) { ^ symbol: class NonNull C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:445: error: cannot find symbol public void onComplete(@NonNull Task&lt;GetTokenResult&gt; task) { ^ symbol: class NonNull C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:499: error: cannot find symbol public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { ^ symbol: class NonNull Note: C:\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.0\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 9 errors FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':firebase_auth:compileDebugJavaWithJavac'. &gt; Compilation failed; see the compiler error output for details. * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 22s Finished with error: Gradle task assembleDebug failed with exit code 1 </code></pre> <p>From my research I found that i might need to upgrade to AndroidX. I followed this <a href="https://developer.android.com/jetpack/androidx/migrate#migrate" rel="noreferrer">link</a> to upgrade my android. However i still got the same errors when trying to build and run the app.</p> <p>I am using InteliJ as my IDE with a flutter project and my pubspec.yaml is as follows:</p> <pre><code>name: smart_diet_flutter description: A new Flutter project. # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # Read more about versioning at semver.org. version: 1.0.0+1 environment: sdk: "&gt;=2.0.0-dev.68.0 &lt;3.0.0" dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 firebase_auth: 0.8.0 firebase_database: 1.1.0+1 dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://www.dartlang.org/tools/pub/pubspec # The following section is specific to Flutter. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.io/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.io/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.io/custom-fonts/#from-packages assets: - assets/flutter-icon.png </code></pre>
0
2,677
NoClassDefFoundError and Netty
<p>First to say I'm n00b in Java. I can understand most concepts but in my situation I want somebody to help me. I'm using JBoss Netty to handle simple http request and using MemCachedClient check existence of client ip in memcached.</p> <pre><code>import org.jboss.netty.channel.ChannelHandler; import static org.jboss.netty.handler.codec.http.HttpHeaders.*; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*; import static org.jboss.netty.handler.codec.http.HttpVersion.*; import com.danga.MemCached.*; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.http.Cookie; import org.jboss.netty.handler.codec.http.CookieDecoder; import org.jboss.netty.handler.codec.http.CookieEncoder; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpChunk; import org.jboss.netty.handler.codec.http.HttpChunkTrailer; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.QueryStringDecoder; import org.jboss.netty.util.CharsetUtil; /** * @author &lt;a href="http://www.jboss.org/netty/"&gt;The Netty Project&lt;/a&gt; * @author Andy Taylor (andy.taylor@jboss.org) * @author &lt;a href="http://gleamynode.net/"&gt;Trustin Lee&lt;/a&gt; * * @version $Rev: 2368 $, $Date: 2010-10-18 17:19:03 +0900 (Mon, 18 Oct 2010) $ */ @SuppressWarnings({"ALL"}) public class HttpRequestHandler extends SimpleChannelUpstreamHandler { private HttpRequest request; private boolean readingChunks; /** Buffer that stores the response content */ private final StringBuilder buf = new StringBuilder(); protected MemCachedClient mcc = new MemCachedClient(); private static SockIOPool poolInstance = null; static { // server list and weights String[] servers = { "lcalhost:11211" }; //Integer[] weights = { 3, 3, 2 }; Integer[] weights = {1}; // grab an instance of our connection pool SockIOPool pool = SockIOPool.getInstance(); // set the servers and the weights pool.setServers(servers); pool.setWeights(weights); // set some basic pool settings // 5 initial, 5 min, and 250 max conns // and set the max idle time for a conn // to 6 hours pool.setInitConn(5); pool.setMinConn(5); pool.setMaxConn(250); pool.setMaxIdle(21600000); //1000 * 60 * 60 * 6 // set the sleep for the maint thread // it will wake up every x seconds and // maintain the pool size pool.setMaintSleep(30); // set some TCP settings // disable nagle // set the read timeout to 3 secs // and don't set a connect timeout pool.setNagle(false); pool.setSocketTO(3000); pool.setSocketConnectTO(0); // initialize the connection pool pool.initialize(); // lets set some compression on for the client // compress anything larger than 64k //mcc.setCompressEnable(true); //mcc.setCompressThreshold(64 * 1024); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = this.request = (HttpRequest) e.getMessage(); if(mcc.get(request.getHeader("X-Real-Ip")) != null) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.setHeader("X-Accel-Redirect", request.getUri()); ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } else { sendError(ctx, NOT_FOUND); } } private void writeResponse(MessageEvent e) { // Decide whether to close the connection or not. boolean keepAlive = isKeepAlive(request); // Build the response object. HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); } // Encode the cookie. String cookieString = request.getHeader(COOKIE); if (cookieString != null) { CookieDecoder cookieDecoder = new CookieDecoder(); Set&lt;Cookie&gt; cookies = cookieDecoder.decode(cookieString); if(!cookies.isEmpty()) { // Reset the cookies if necessary. CookieEncoder cookieEncoder = new CookieEncoder(true); for (Cookie cookie : cookies) { cookieEncoder.addCookie(cookie); } response.addHeader(SET_COOKIE, cookieEncoder.encode()); } } // Write the response. ChannelFuture future = e.getChannel().write(response); // Close the non-keep-alive connection after the write operation is done. if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { e.getCause().printStackTrace(); e.getChannel().close(); } private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.setContent(ChannelBuffers.copiedBuffer( "Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); // Close the connection as soon as the error message is sent. ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } } </code></pre> <p>When I try to send request like <a href="http://127.0.0.1:8090/1/2/3" rel="nofollow">http://127.0.0.1:8090/1/2/3</a> I'm getting </p> <pre><code>java.lang.NoClassDefFoundError: com/danga/MemCached/MemCachedClient at httpClientValidator.server.HttpRequestHandler.&lt;clinit&gt;(HttpRequestHandler.java:66) </code></pre> <p>I believe it's not related to classpath. May be it's related to context in which mcc doesn't exist. Any help appreciated</p> <p>EDIT: Original code <a href="http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/http/snoop/package-summary.html" rel="nofollow">http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/http/snoop/package-summary.html</a> I've modified some parts to fit my needs.</p>
0
2,846
How to install the Springframework CrudRepository?
<p>I'm following <a href="http://www.thejavageek.com/2017/06/16/crud-application-using-angular-4-spring-rest-web-services-spring-data-jpa/" rel="nofollow noreferrer">this tutorial</a> to create a CRUD application with Spring. I want to create a repository and I want it to extend the Spring CrudRepository:</p> <pre><code>package com.movieseat.repositories; import java.io.Serializable; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.movieseat.models.Movie; public interface MovieRepository extends CrudRepository&lt;Movie, Serializable&gt; {} </code></pre> <p>Visual Studio Code is saying:</p> <blockquote> <p>The import org.springframework.data cannot be resolved</p> </blockquote> <p>I've removed the repository folder in the .m2 folder and do a reinstall but still no success. </p> <p>I think I'm missing a dependency in my pom.xml file but I can't found it which one.</p> <p>//edit. Sharing the pom.xml that's in the back-end folder:</p> <pre><code> &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;artifactId&gt;backend&lt;/artifactId&gt; &lt;name&gt;backend&lt;/name&gt; &lt;description&gt;The backend project&lt;/description&gt; &lt;parent&gt; &lt;groupId&gt;com.jdriven.ng2boot&lt;/groupId&gt; &lt;artifactId&gt;parent&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;properties&gt; &lt;!-- The main class to start by executing java -jar --&gt; &lt;start-class&gt;com.movieseat.Application&lt;/start-class&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.jdriven.ng2boot&lt;/groupId&gt; &lt;artifactId&gt;frontend&lt;/artifactId&gt; &lt;version&gt;${project.version}&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt; &lt;optional&gt;true&lt;/optional&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre>
0
1,802
Android Listview show only one item
<p>I have a ListView, where i changed appearence of row, but listview have size of one row, instead of fullscreen.</p> <p>list_item.xml:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" &gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="wrap_content"/&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" &gt; &lt;TextView android:id="@+id/textView_news_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="#0082A8" /&gt; &lt;TextView android:id="@+id/textView_news_header" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>tab_news.xml:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;ListView android:id="@+id/list_news" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;/ListView&gt; &lt;/LinearLayout&gt; </code></pre> <p>Making Adapter:</p> <pre><code>public class RSSAdapter extends ArrayAdapter&lt;RSSitem&gt; { Context context; int layoutResourceId; ArrayList&lt;RSSitem&gt; data = null; SimpleDateFormat sdf = new SimpleDateFormat("kk:mm "); public RSSAdapter(Context context, int layoutResourceId, ArrayList&lt;RSSitem&gt; data) { super(context, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.context = context; this.data = data; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; NewsHolder holder = null; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new NewsHolder(); holder.txtTime = (TextView)row.findViewById(R.id.textView_news_time); holder.txtNews = (TextView)row.findViewById(R.id.textView_news_header); row.setTag(holder); } else { holder = (NewsHolder)row.getTag(); } RSSitem item = data.get(position); holder.txtTime.setText(sdf.format(item.getPubDate())); holder.txtNews.setText(item.getTitle()); return row; } static class NewsHolder { TextView txtTime; TextView txtNews; } </code></pre> <p>Items are scrolling.</p> <p>Sorry for bad English. Thanks for help</p> <p>Advice of @Varun didn't help</p> <p>I found mistake. Thanks. Answer in "answers")</p>
0
1,220
How to pre-load all deployed assemblies for an AppDomain
<p><strong>UPDATE:</strong> I now have a solution I'm much happier with that, whilst not solving all the problems I ask about, it does leave the way clear to do so. I've updated my own answer to reflect this.</p> <p><em>Original Question</em></p> <p>Given an App Domain, there are many different locations that Fusion (the .Net assembly loader) will probe for a given assembly. Obviously, we take this functionality for granted and, since the probing appears to be embedded within the .Net runtime (<code>Assembly._nLoad</code> internal method seems to be the entry-point when Reflect-Loading - and I assume that implicit loading is probably covered by the same underlying algorithm), as developers we don't seem to be able to gain access to those search paths.</p> <p>My problem is that I have a component that does a lot of dynamic type resolution, and which needs to be able to ensure that all user-deployed assemblies for a given AppDomain are pre-loaded before it starts its work. Yes, it slows down startup - but the benefits we get from this component totally outweight this.</p> <p>The basic loading algorithm I've already written is as follows. It deep-scans a set of folders for any .dll (.exes are being excluded <em>at the moment</em>), and uses Assembly.LoadFrom to load the dll if it's AssemblyName cannot be found in the set of assemblies already loaded into the AppDomain (this is implemented inefficiently, but it can be optimized later):</p> <pre><code>void PreLoad(IEnumerable&lt;string&gt; paths) { foreach(path p in paths) { PreLoad(p); } } void PreLoad(string p) { //all try/catch blocks are elided for brevity string[] files = null; files = Directory.GetFiles(p, "*.dll", SearchOption.AllDirectories); AssemblyName a = null; foreach (var s in files) { a = AssemblyName.GetAssemblyName(s); if (!AppDomain.CurrentDomain.GetAssemblies().Any( assembly =&gt; AssemblyName.ReferenceMatchesDefinition( assembly.GetName(), a))) Assembly.LoadFrom(s); } } </code></pre> <p>LoadFrom is used because I've found that using Load() can lead to duplicate assemblies being loaded by Fusion if, when it probes for it, it doesn't find one loaded from where it expects to find it.</p> <p>So, with this in place, all I now have to do is to get a list in precedence order (highest to lowest) of the search paths that Fusion is going to be using when it searches for an assembly. Then I can simply iterate through them.</p> <p>The GAC is irrelevant for this, and I'm not interested in any environment-driven fixed paths that Fusion might use - only those paths that can be gleaned from the AppDomain which contain assemblies expressly deployed for the app.</p> <p>My first iteration of this simply used AppDomain.BaseDirectory. This works for services, form apps and console apps.</p> <p>It doesn't work for an Asp.Net website, however, since there are at least two main locations - the AppDomain.DynamicDirectory (where Asp.Net places it's dynamically generated page classes and any assemblies that the Aspx page code references), and then the site's Bin folder - which can be discovered from the AppDomain.SetupInformation.PrivateBinPath property.</p> <p>So I now have working code for the most basic types of apps now (Sql Server-hosted AppDomains are another story since the filesystem is virtualised) - but I came across an interesting issue a couple of days ago where this code simply doesn't work: the nUnit test runner.</p> <p>This uses both Shadow Copying (so my algorithm would need to be discovering and loading them from the shadow-copy drop folder, not from the bin folder) and it sets up the PrivateBinPath as being relative to the base directory.</p> <p>And of course there are loads of other hosting scenarios that I probably haven't considered; but which must be valid because otherwise Fusion would choke on loading the assemblies.</p> <p>I want to stop feeling around and introducing hack upon hack to accommodate these new scenarios as they crop up - what I want is, given an AppDomain and its setup information, the ability to produce this list of Folders that I should scan in order to pick up all the DLLs that are going to be loaded; regardless of how the AppDomain is setup. If Fusion can see them as all the same, then so should my code.</p> <p>Of course, I might have to alter the algorithm if .Net changes its internals - that's just a cross I'll have to bear. Equally, I'm happy to consider SQL Server and any other similar environments as edge-cases that remain unsupported for now.</p> <p>Any ideas!?</p>
0
1,205
Pass multiple JSON objects to MVC3 action method
<p>JQuery code:</p> <pre> //This passes NULL for "CategoryID", "CategoryName", "ProductID", "ProductName" $("#btnPost").click(function () { var CategoryModel = { CategoryID: 1, CategoryName: "Beverage" }; var ProductModel = { ProductID: 1, ProductName: "Chai" }; var data1 = {}; data1["cat"] = CategoryModel; data1["prd"] = ProductModel; var jsonData = JSON.stringify(data1); $.ajax({ url: url + '/Complex/ModelTwo', //This works but property values are null type: 'post', dataType: 'json', data: { "cat": CategoryModel, "prd": ProductModel }, //jsonData, cache: false, success: function (result) { alert(result); }, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } }); }); </pre> <p>MVC Code (C#):</p> <pre><code> public class ComplexController : Controller { public string ModelOne(Category cat) { return "this took single model..."; } public string ModelTwo(Category cat, Product prd) { return "this took multiple model..."; } } public class Category { public int CategoryID { get; set; } public string CategoryName { get; set; } } public class Product { public int ProductID { get; set; } public string ProductName { get; set; } } </code></pre> <p>Now the issue is, I couldn't get it working by passing "CategoryMode", "ProductModel" into "ModelTwo" action method. The JQuery post correctly identifies the action method "ModelTwo" but "cat", "prd" property values are null. "CategoryID", "CategoryName", "ProductID", "ProductName" all are null despite hitting that method. </p> <pre> //THIS ONE WORKS FINE... $("#btnPost").click(function () { var CategoryModel = { CategoryID: 1, CategoryName: "Beverage" }; var ProductModel = { ProductID: 1, ProductName: "Chai" }; var data1 = {}; data1["cat"] = CategoryModel; data1["prd"] = ProductModel; var jsonData = JSON.stringify(data1); $.ajax({ url: url + '/Complex/ModelOne', //This works type: 'post', dataType: 'json', data: CategoryModel, cache: false, success: function (result) { alert(result); }, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } }); }); </pre> <p>So what's wrong with my first JQuery call to "ModelTwo" action method?</p> <p>I spent lots of time figuring this out, but not sure what's going on. There is no issue with routing here because I can land on the right action method...</p> <p>Any help will be greatly appreciated.</p> <p>Thanks!</p>
0
1,649
Spring Security/Spring Boot - How to set ROLES for users
<p>When I logged in using security, I cannot use the <code>request.isUserInRole()</code> method. I think the roles of the users was not set.</p> <p>This is my Security Configuration:</p> <pre><code>@Configuration @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled=true) @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Autowired private UserDetailsServiceImplementation userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/signup").permitAll() .antMatchers("/").permitAll() //.antMatchers("/first").hasAuthority("Service_Center") .antMatchers("/login").permitAll() .anyRequest().fullyAuthenticated() .and().formLogin() .loginPage("/login") .usernameParameter("email") .passwordParameter("password") .defaultSuccessUrl("/default") .failureUrl("/login?error").permitAll() .and().logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .deleteCookies("JSESSIONID") .invalidateHttpSession(true).permitAll(); } @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } } </code></pre> <p>This is my <code>User</code> entity:</p> <pre><code> @Entity @Table(name="user") public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="user_id") private Long userID; @Column(name="email_address", nullable = false, unique = true) private String emailAddress; @Column(name="password") private String password; @Column(name = "role", nullable = false) @Enumerated(EnumType.STRING) private Role role; public User() { super(); } public User(String emailAddress, String password) { this.emailAddress = emailAddress; this.password = password; } public Long getUserID() { return userID; } public void setUserID(Long userID) { this.userID = userID; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } @Override public String toString() { return "User [userID=" + userID + ", emailAddress=" + emailAddress + ", password=" + password + ", role=" + role + "]"; } public UserDetails toCurrentUserDetails() { return CurrentUserDetails.create(this); } } </code></pre> <p>This is my enum <code>Role</code>:</p> <pre><code>public enum Role { Fleet_Company, Service_Center, Admin } </code></pre> <p>This is my <code>UserDetailsServiceImplementation</code>:</p> <pre><code>@Component public class UserDetailsServiceImplementation implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if ( username == null || username.isEmpty() ){ throw new UsernameNotFoundException("username is empty"); } User foundUser = userRepository.findByEmailAddress(username); if( foundUser != null ){ System.out.println("FOUND"); return foundUser.toCurrentUserDetails(); } throw new UsernameNotFoundException( username + "is not found"); } } </code></pre> <p>This is the class that implements <code>UserDetails</code>:</p> <pre><code>public class CurrentUserDetails implements UserDetails { private Long userID; private String emailAddress; private String password; private Role role; public CurrentUserDetails(Long userID, String emailAddress, String password, Role role) { super(); this.userID = userID; this.emailAddress = emailAddress; this.password = password; this.role = role; } /* public static UserDetails create(Users entity) { List&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;GrantedAuthority&gt;(); for(Authorities auth: entity.getAuthorities()){ authorities.add(new SimpleGrantedAuthority(auth.getId().getAuthority())); } return new MyUserDetail(entity.getUserId(), entity.getLoginId(), entity.getPassword(), entity.getDisplayName(), authorities); }*/ public Long getUserID(){ return this.userID; } public Role getRole(){ return this.role; } @Override public String getPassword() { return this.password; } public String getEmailAddress() { return this.emailAddress; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } public static UserDetails create(User entity) { System.out.println(entity.getUserID()+ entity.getEmailAddress()+ entity.getPassword()+ entity.getRole()); return new CurrentUserDetails(entity.getUserID(), entity.getEmailAddress(), entity.getPassword(), entity.getRole()); } @Override public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() { // TODO Auto-generated method stub return null; } @Override public String getUsername() { // TODO Auto-generated method stub return null; } } </code></pre> <p>So basically, we can see that I only have one table on my MySQL database, it has four columns and one of them is 'role'.</p> <p>But like what I said, when I use <code>request.isUserInRole("Service_Center")</code>, it returns FALSE. And <code>.antMatchers("/first").hasAuthority("Service_Center")</code> doesn't work either.</p>
0
2,082
How do I retrieve Google Finance Historical data in Google Sheets using the API?
<p>To reproduce this problem, create a new sheet. In cell A1, insert this formula:</p> <pre><code>=GoogleFinance("AMZN", "all", "1/1/2018", "2/1/2018") </code></pre> <p>The output (Formatting doesn't matter for this problem):</p> <pre><code>Date Open High Low Close Volume 1/2/2018 16:00:00 1172 1190 1170.51 1189.01 2694494 1/3/2018 16:00:00 1188.3 1205.49 1188.3 1204.2 3108793 1/4/2018 16:00:00 1205 1215.8699 1204.66 1209.59 3022089 1/5/2018 16:00:00 1217.51 1229.14 1210 1229.14 3544743 1/8/2018 16:00:00 1236 1253.079 1232.03 1246.87 4279475 1/9/2018 16:00:00 1256.9 1259.33 1241.76 1252.7 3661316 1/10/2018 16:00:00 1245.15 1254.33 1237.23 1254.33 2686017 1/11/2018 16:00:00 1259.74 1276.77 1256.46 1276.68 3125048 1/12/2018 16:00:00 1273.3925 1305.76 1273.3925 1305.2 5443730 1/16/2018 16:00:00 1323 1339.94 1292.3 1304.86 7220701 1/17/2018 16:00:00 1312.24 1314 1280.88 1295 5253754 1/18/2018 16:00:00 1293.95 1304.6 1284.02 1293.32 4026915 1/19/2018 16:00:00 1312 1313 1292.99 1294.58 4578536 1/22/2018 16:00:00 1297.17 1327.45 1296.6636 1327.31 4140061 1/23/2018 16:00:00 1338.09 1364.9 1337.34 1362.54 5169306 1/24/2018 16:00:00 1374.82 1388.16 1338 1357.51 6807457 1/25/2018 16:00:00 1368 1378.34 1357.62 1377.95 4753012 1/26/2018 16:00:00 1392.01 1402.53 1380.91 1402.05 4857310 1/29/2018 16:00:00 1409.18 1431.39 1400.44 1417.68 5701898 1/30/2018 16:00:00 1403.17 1439.25 1392 1437.82 5871942 1/31/2018 16:00:00 1451.3 1472.58 1450.04 1450.89 6424693 </code></pre> <p>All is well so far. BUT, when I try to retrieve this data via the API (And I want to point out that all OTHER data is retrieved just fine), I get simple a "#N/A" for cell A1, and no values for all the other cells. It's like they're empty. I've tried retrieving just the values, but also all the gridinfo, both cases, it's like these values were never there.</p> <p>Things I've tried:</p> <ul> <li>Setting a cell to "=TODAY()" before reading (some comments say that triggers a refresh of the data).</li> <li>Looping with a delay trying to read the data, but that runs forever.</li> <li>All this works flawlessly in the browser, but not over API calls</li> <li>Other cells referencing this data fails with "#N/A"</li> <li>If I add the add-on CryptoFinance, and insert this function "=CRYPTOFINANCE("COINMARKETCAP")", a range of cells are populated, similar to GoogleFinance. However, these cells CAN be retrieved via API calls. Works like a charm.</li> <li><p>Any 'single' cell using googlefinance works fine, so if I add cell I1 shown below, THAT value is retrieved just fine</p> <pre><code>=GoogleFinance("AMZN", "price") </code></pre></li> </ul> <p>It just simply seems like the data is not there when using the HISTORICAL data from google finance (as per the API call).</p> <p>I have not posted my code, since it seems this is more a case of googlefinance not working than anything else, and specifically when returning a 'range' of data instead of single cell values.</p> <p>Thoughts?</p>
0
1,266
select2, ng-model and angular
<p>Using <a href="https://select2.github.io/" rel="nofollow">jquery-select2</a> (<strong>not</strong> ui-select) and angular, I'm trying to set the value to the ng-model.</p> <p>I've tried using <code>$watch</code> and <code>ng-change</code>, but none seem to fire after selecting an item with select2.</p> <p>Unfortunately, I am using a purchased template and cannot use angular-ui.</p> <p><strong>HTML:</strong></p> <pre><code>&lt;input type="hidden" class="form-control select2remote input-medium" ng-model="contact.person.id" value="{{ contact.person.id }}" data-display-value="{{ contact.person.name }}" data-remote-search-url="api_post_person_search" data-remote-load-url="api_get_person" ng-change="updatePerson(contact, contact.person)"&gt; </code></pre> <p><strong>ClientController:</strong></p> <pre><code>$scope.updatePerson = function (contact, person) { console.log('ng change'); console.log(contact); console.log(person); } // not firing $scope.$watch("client", function () { console.log($scope.client); }, true); // not firing either </code></pre> <p><strong>JQuery integration:</strong></p> <pre><code>var handleSelect2RemoteSelection = function () { if ($().select2) { var $elements = $('input[type=hidden].select2remote'); $elements.each(function(){ var $this = $(this); if ($this.data('remote-search-url') &amp;&amp; $this.data('remote-load-url')) { $this.select2({ placeholder: "Select", allowClear: true, minimumInputLength: 1, ajax: { // instead of writing the function to execute the request we use Select2's convenient helper url: Routing.generate($this.data('remote-search-url'), {'_format': 'json'}), type: 'post', dataType: 'json', delay: 250, data: function (term, page) { return { query: term, // search term }; }, results: function (data, page) { // parse the results into the format expected by Select2. return { results: $.map(data, function (datum) { var result = { 'id': datum.id, 'text': datum.name }; for (var prop in datum) { if (datum.hasOwnProperty(prop)) { result['data-' + prop] = datum[prop]; } } return result; }) } } }, initSelection: function (element, callback) { // the input tag has a value attribute preloaded that points to a preselected movie's id // this function resolves that id attribute to an object that select2 can render // using its formatResult renderer - that way the movie name is shown preselected var id = $(element).val(), displayValue = $(element).data('display-value'); if (id &amp;&amp; id !== "") { if (displayValue &amp;&amp; displayValue !== "") { callback({'id': $(element).val(), 'text': $(element).data('display-value')}); } else { $.ajax(Routing.generate($this.data('remote-load-url'), {'id': id, '_format': 'json'}), { dataType: "json" }).done(function (data) { callback({'id': data.id, 'text': data.name}); }); } } }, }); } }); } }; </code></pre> <p>Any advice would be greatly appreciated! :)</p> <p><strong>UPDATE</strong></p> <p>I've managed to put together <a href="http://plnkr.co/edit/Ca0fCKFPHjZCPh3OUMYg" rel="nofollow">a plunk</a> which seems to similarly reproduce the problem - it now appears as if the ng-watch and the $watch events are fired only when first changing the value. Nevertheless, in my code (and when adding further complexity like dynamically adding and removing from the collection), it doesn't even seem to fire once.</p> <p>Again, pointers in the right direction (or in any direction really) would be greatly appreciated!</p>
0
2,580
Save data to CSV file in ruby on rails
<p>I want to add some data which I get from user using html form to CSV file in ruby on rails. How can I do this? Here is my code for this</p> <pre><code>&lt;p&gt; &lt;h2&gt;Register using form below&lt;/h2&gt; &lt;p class="error"&gt;&lt;/p&gt; &lt;form action="" method="post" class="scrum-form"&gt; &lt;p&gt;&lt;h3&gt;Participant information&lt;/h3&gt;&lt;/p&gt; &lt;div&gt; &lt;label&gt;Full name&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="full_name" class="full_name" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Email&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="email" class="email" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Phone number&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="phone" class="phone" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Organization name&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="organization" class="organization" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Job title&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="job" class="job" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Special diet&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="diet" class="diet" /&gt; &lt;/div&gt; &lt;p&gt;&lt;h3&gt;Billing information&lt;/h3&gt;&lt;/p&gt; &lt;div&gt; &lt;label&gt;Address&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;textarea cols="40" rows="5" name="address" name="address" class="address"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Postal code&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="code" class="code" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;City&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="city" class="city" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Cost pool or reference&lt;span class="mandatory"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" name="cost_pool" class="cost_pool" /&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="button" name="register" value="Register" onclick="registration();" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/p&gt; </code></pre> <p>here is my action code</p> <pre><code>full_name = params["full_name"] email = params["email"] phone = params["phone"] organization = params["organization"] job = params["job"] diet = params["diet"] address = params["address"] code = params["code"] city = params["city"] cost_pool = params["cost_pool"] </code></pre>
0
1,179
HTTP error 400 Bad Request when POSTing JSON data over HttpURLConnection
<p>I have this code below that trying to post JSON data after successfully authenticate through Oauth2.0, the code is like this:</p> <pre><code>try { URL url = new URL ("https://test.api.neteller.com/v1/oauth2/token?grant_type=client_credentials"); String test = "QUFBQlNhVlFoUjhlTVhPQjowLm9aV3g2Rkhwd1dIQUZnXzRaMDZwOUoyRWtzaXVHMHEzd2xrVFF4MkRVM28uN0FzUDE4cmZXU0dxVDdqWE1NUGhzSFY4cHU0"; HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty ("Authorization", "Basic " + test); String accessToken = ""; [... get the access token ...] String urlnew = "https://test.api.neteller.com/v1/transferIn"; URL obj = new URL(urlnew); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add request header con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty ("Authorization", "Bearer " + accessToken); con.setRequestProperty("Content-Type", "application/json"); // Send post request JSONObject obj2 = new JSONObject(); obj2.put("paymentMethod", ""); obj2.put("type", "neteller"); obj2.put("value", "netellertest_GBP@neteller.com"); obj2.put("transaction", ""); obj2.put("merchantRefId", "20140203122501"); obj2.put("amount", (5000)); obj2.put("currency", "USD"); obj2.put("verificationCode", "411392"); System.out.print(obj2); int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); [... parse response ...] } catch(Exception e) { e.printStackTrace(); } </code></pre> <p>I get this error when I run the code above:</p> <pre><code>java.io.IOException: Server returned HTTP response code: 400 for URL: https://test.api.neteller.com/v1/transferIn at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source) at example.demo.main(demo.java:71) Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://test.api.neteller.com/v1/transferIn at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source) at example.demo.main(demo.java:65) </code></pre> <p>From the error status 400 I know that the post JSON data is invalid. I suspect maybe in the structure because according to the documentation it should be like this:</p> <pre><code>{ "paymentMethod": { "type": "neteller", "value": "gb_gbp@neteller.com" }, "transaction": { "merchantRefId": "20140203122501", "amount": 5000, "currency": "USD" }, "verificationCode": "234124" } </code></pre> <p>So how do I change the JSON parameter so that it could follow the structure in the documentation? </p>
0
1,354
Change title when drilldown in Highcharts
<p>I'm looking for a way to show a info text in Highcharts when using drilldowns. I want a text that tells my visitors that another chart has been showed up. A title for example: "New chart - more about Animals"</p> <p><a href="http://jsfiddle.net/6zYmJ/">http://jsfiddle.net/6zYmJ/</a></p> <p>Do you have any ideas how to do that?</p> <pre><code>$(function () { // Create the chart $('#container').highcharts({ chart: { type: 'column' }, title: { text: 'Basic drilldown' }, xAxis: { type: 'category' }, legend: { enabled: false }, plotOptions: { series: { borderWidth: 0, dataLabels: { enabled: true, } } }, series: [{ name: 'Things', colorByPoint: true, data: [{ name: 'Animals', y: 5, drilldown: 'animals' }, { name: 'Fruits', y: 2, drilldown: 'fruits' }, { name: 'Cars', y: 4, drilldown: 'cars' }] }, { name: 'Things', colorByPoint: true, data: [{ name: 'Animals2', y: 5, drilldown: 'animals2' }, { name: 'Fruits2', y: 2, drilldown: 'fruits2' }, { name: 'Cars2', y: 4, drilldown: 'cars2' }] }], drilldown: { series: [{ id: 'animals', data: [ ['Cats', 4], ['Dogs', 2], ['Cows', 1], ['Sheep', 2], ['Pigs', 1] ] }, { id: 'fruits', data: [ ['Apples', 4], ['Oranges', 2] ] }, { id: 'cars', data: [ ['Toyota', 4], ['Opel', 2], ['Volkswagen', 2] ] },{ id: 'animals2', data: [ ['Cats', 4], ['Dogs', 2], ['Cows', 1], ['Sheep', 2], ['Pigs', 1] ] }, { id: 'fruits2', data: [ ['Apples', 4], ['Oranges', 2] ] }, { id: 'cars2', data: [ ['Toyota', 4], ['Opel', 2], ['Volkswagen', 2] ] }] } }) }); </code></pre>
0
1,653
Conversion from nested json to csv with pandas
<p>I am trying to convert a nested json into a csv file, but I am struggling with the logic needed for the structure of my file: it's a json with 2 objects and I would like to convert into csv only one of them, which is a list with nesting.</p> <p>I've found very helpful "flattening" json info in <a href="https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10" rel="nofollow noreferrer">this blog post</a>. I have been basically adapting it to my problem, but it is still not working for me.</p> <p>My json file looks like this:</p> <pre><code>{ "tickets":[ { "Name": "Liam", "Location": { "City": "Los Angeles", "State": "CA" }, "hobbies": [ "Piano", "Sports" ], "year" : 1985, "teamId" : "ATL", "playerId" : "barkele01", "salary" : 870000 }, { "Name": "John", "Location": { "City": "Los Angeles", "State": "CA" }, "hobbies": [ "Music", "Running" ], "year" : 1985, "teamId" : "ATL", "playerId" : "bedrost01", "salary" : 550000 } ], "count": 2 } </code></pre> <p>my code, so far, looks like this:</p> <pre class="lang-py prettyprint-override"><code>import json from pandas.io.json import json_normalize import argparse def flatten_json(y): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return out if __name__ == '__main__': parser = argparse.ArgumentParser(description='Converting json files into csv for Tableau processing') parser.add_argument( "-j", "--json", dest="json_file", help="PATH/TO/json file to convert", metavar="FILE", required=True) args = parser.parse_args() with open(args.json_file, "r") as inputFile: # open json file json_data = json.loads(inputFile.read()) # load json content flat_json = flatten_json(json_data) # normalizing flat json final_data = json_normalize(flat_json) with open(args.json_file.replace(".json", ".csv"), "w") as outputFile: # open csv file # saving DataFrame to csv final_data.to_csv(outputFile, encoding='utf8', index=False) </code></pre> <p>What I would like to obtain is 1 line per ticket in the csv, with headings:</p> <p><code>Name,Location_City,Location_State,Hobbies_0,Hobbies_1,Year,TeamId,PlayerId,Salary</code>.</p> <p>I would really appreciate anything that can do the click! Thank you!</p>
0
1,210
Arithmetic calculation for BODMAS in Java
<p>I have written this code for Bodmas, but getting some error in this. If I do 3-5+9, it will result in 3.04.0.</p> <p>It just start concatenating, though it works for all other operations like *, / and -, please help.</p> <pre><code>public static String calculation(BODMASCalculation bodmas, String result) { while (bodmas.hasMatch()) { double value, leftOfOperator = bodmas.getLeft(); char op = bodmas.getOperator(); double rightOfOprator = bodmas.getRight(); switch (op) { case '/': if(rightOfOprator == 0) //Divide by 0 generates Infinity value = 0; else value = leftOfOperator / rightOfOprator; break; case '*': value = leftOfOperator * rightOfOprator; break; case '+': value = leftOfOperator + rightOfOprator; break; case '-': value = leftOfOperator - rightOfOprator; break; default: throw new IllegalArgumentException("Unknown operator."); } result = result.substring(0, bodmas.getStart()) + value + result.substring(bodmas.getEnd()); bodmas = new BODMASCalculation(result); } return result; } </code></pre> <p>Another function is:-</p> <pre><code>public boolean getMatchFor(String text, char operator) { String regex = "(-?[\\d\\.]+)(\\x)(-?[\\d\\.]+)"; java.util.regex.Matcher matcher = java.util.regex.Pattern.compile(regex.replace('x', operator)).matcher(text); if (matcher.find()) { this.leftOfOperator = Double.parseDouble(matcher.group(1)); this.op = matcher.group(2).charAt(0); this.rightOfOprator = Double.parseDouble(matcher.group(3)); this.start = matcher.start(); this.end = matcher.end(); return true; } return false; } </code></pre> <p>I have a solution by adding</p> <pre><code>String sss = null; if(op == '+' &amp;&amp; !Str.isBlank(result.substring(0, bodmas.getStart())) &amp;&amp; value &gt;= 0) sss = "+"; else sss = ""; result = result.substring(0, bodmas.getStart()) + sss + value + result.substring(bodmas.getEnd()); </code></pre> <p>But don't want to do that, I want this to work for all the operators.</p>
0
1,050
Add button in android action bar
<p>I trying to add a button beside HealthyApp, but no luck .</p> <p>This is my initial code and image</p> <pre><code> final ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); </code></pre> <p><a href="https://i.stack.imgur.com/mMcgL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mMcgL.png" alt="enter image description here"></a></p> <p>I want to add a delete button beside HealthyApp but the HealthyApp title gone. </p> <pre><code> final ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); LayoutInflater mInflater = LayoutInflater.from(this); View mCustomView = mInflater.inflate(R.layout.header_button, null); Button mTitleTextView = (Button) mCustomView.findViewById(R.id.title_text); mTitleTextView.setText("Delete"); actionBar.setCustomView(mCustomView); actionBar.setDisplayShowCustomEnabled(true); </code></pre> <p><a href="https://i.stack.imgur.com/FDFYl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FDFYl.png" alt="enter image description here"></a></p> <p><strong>delete_task</strong></p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#d9d9d9" android:minHeight="?attr/actionBarSize"&gt; &lt;LinearLayout android:layout_width="match_parent" android:gravity="right" android:layout_height="wrap_content"&gt; &lt;Button android:text="Delete" android:layout_width="wrap_content" android:background="#000" android:textColor="#fff" android:layout_height="wrap_content" android:textSize="16dp" /&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.Toolbar&gt; &lt;ImageView android:src="@mipmap/to_do" android:layout_marginTop="50dp" android:layout_width="130dp" android:layout_height="210dp" android:id="@+id/imageView" android:gravity="center" android:layout_centerHorizontal="true"/&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:text="No List Found" android:textSize="15dp" android:textColor="@color/btn_login" android:gravity="center" android:id="@+id/NoData" android:layout_centerHorizontal="true" android:layout_below="@+id/imageView"/&gt; &lt;RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/list_todo" android:layout_weight="1" android:layout_alignParentLeft="true" /&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p><a href="https://i.stack.imgur.com/mdcUq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mdcUq.png" alt="enter image description here"></a></p>
0
1,602
Keypress To Simulate A Button Click in C#
<p>Ok, so I'm in the process of making a Tic-Tac-Toe game to help me learn C#. I'm attempting to add a bit of functionality to it, so I want people to be able to use the NumPad on a computer to simulate clicking the buttons.</p> <p>Here is what I have but when I use the NumPad the buttons don't click. Can any of you see a reason as to why?</p> <pre><code> //=============================== // start NumPad Simulate Clicks // NumPad MyButtons // 7 8 9 1 2 3 // 4 5 6 4 5 6 // 1 2 3 7 8 9 //=============================== public void myControl_NumPad7(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad7) { button1_Click(null, null); } } public void myControl_NumPad8(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad8) { button2_Click(null, null); } } public void myControl_NumPad9(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad9) { button3_Click(null, null); } } public void myControl_NumPad4(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad4) { button4_Click(null, null); } } public void myControl_NumPad5(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad5) { button5_Click(null, null); } } public void myControl_NumPad6(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad6) { button6_Click(null, null); } } public void myControl_NumPad1(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad1) { button7_Click(null, null); } } public void myControl_NumPad2(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad2) { button8_Click(null, null); } } public void myControl_NumPad3(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.NumPad3) { button9_Click(null, null); } } </code></pre>
0
1,070
Angular 5: Returning an Observable from a function
<p>In the old days, I would define a new <code>Promise</code>, defer it, then resolve it when my function completed. Now I find myself in a situation where I need to return an <code>Observable</code> from a function, and I want to be sure I'm setting it up properly in an <code>Angular 5</code> context.</p> <p>Test function, working fine:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>getTreeViewChildren(currNode: any, nodeType: string, nodeTypeEnum: number = 0, nested: boolean = true) : Observable&lt;any&gt; { let treeObs: Observable&lt;any&gt;; treeObs = new Observable(obs =&gt; { this.siteConfigService.getHostAccessPoints().subscribe(data =&gt; { let hostAccessPoints = JSON.parse(data); let accPointTree = this.findChildNodes(currNode, hostAccessPoints, nested); obs.next(accPointTree); obs.complete(); }); }); return treeObs; }</code></pre> </div> </div> </p> <p>and from my NG component I successfully subscribe:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>this.configService.getTreeViewChildren(this.selectedTreeViewItem, type, nodetype, true).subscribe(tree =&gt;{ let theTree = tree; }); </code></pre> </div> </div> </p> <p>However the real function has much more retrieval logic. What is the correct way to setup the <code>Observable</code> as per my test function above? Same exact pattern, just wrapping all the code within <code>treeObs = new Observable(..)</code> ?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>getTreeViewChildNodes(currNode: any, nodeType: string, nodeTypeEnum: number = 0, nested: boolean = true): Observable&lt;any&gt; { let hosts; let locations; let hostAccessPoints; let treeResult: Observable&lt;any&gt;; if (nodeTypeEnum === NodeType.Location) { // more code.. let someTree = getStuff(); return someTree; } if (nodeTypeEnum === NodeType.Host) { // more code.. let someTree = getStuff(); return someTree; } if (nodeTypeEnum === NodeType.HostAccessPoint) { let accPointTree; if (sessionStorage["hostAccessPoints"]) { // more code.. let someTree = getStuff(); return someTree; } else { this.siteConfigService.getHostAccessPoints().subscribe(data =&gt; { // more code.. let someTree = getStuff(); return someTree; }); } } if (nodeTypeEnum === NodeType.HostStorage) { // TO DO } }</code></pre> </div> </div> </p> <p>**** UPDATED (Based <code>Observable.of()</code> suggested answer below):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Builds hierarchical treeview data getTreeViewChildNodes(currNode: any, nodeType: string, nodeTypeEnum: number = 0, nested: boolean = true): Observable&lt;any&gt; { let hosts; let locations; let hostAccessPoints; if (nodeTypeEnum === NodeType.Location) { if (sessionStorage["locations"] != null &amp;&amp; sessionStorage["locations"] != "undefined") { locations = JSON.parse( sessionStorage.getItem('locations') ); } // find child nodes let locationTree = this.findChildren(currNode, locations, nested); return Observable.of(locationTree); } if (nodeTypeEnum === NodeType.Host) { if (sessionStorage["hosts"] != null &amp;&amp; sessionStorage["hosts"] != "undefined") { hosts = JSON.parse( sessionStorage.getItem('hosts') ); } // find child hosts for current node let hostTree = this.findChildHosts(currNode, hosts, nested); return Observable.of(hostTree); } if (nodeTypeEnum === NodeType.HostAccessPoint) { let accPointTree; if (sessionStorage["hostAccessPoints"]) { hostAccessPoints = sessionStorage.getItem("hostAccessPoints"); accPointTree = this.findChildHostAccessPoints(currNode, hostAccessPoints, nested); return Observable.of(accPointTree); } else { // **** THREW ERROR FROM CALLER 'Cannot read property 'subscribe' of undefined****` /*this.siteConfigService.getHostAccessPoints().subscribe(data =&gt; { hostAccessPoints = JSON.parse(data); accPointTree = this.findChildHostAccessPoints(currNode, hostAccessPoints, nested); return Observable.of(accPointTree); });*/ // ** CORRECTED CODE ** return this.siteConfigService.getHostAccessPoints().map(data =&gt; { hostAccessPoints = JSON.parse(data); accPointTree = this.findChildHostAccessPoints(currNode, hostAccessPoints, nested); return accPointTree; }); } } }</code></pre> </div> </div> </p> <p>and from my component code, it throws an error <code>TypeError: Cannot read property 'subscribe' of undefined</code> only where I call my service which in turn calls http.get():</p> <pre><code> this.configService.getTreeViewChildNodes(this.selectedTreeViewItem, type, nodetype, true).subscribe(data =&gt; { this.rebuildNetworkTree(data); }); </code></pre>
0
1,876
scikit-learn TfidfVectorizer meaning?
<p>I was reading about TfidfVectorizer <a href="http://stanford.edu/~rjweiss/public_html/IRiSS2013/text2/notebooks/tfidf.html" rel="noreferrer">implementation</a> of scikit-learn, i don´t understand what´s the output of the method, for example:</p> <pre><code>new_docs = ['He watches basketball and baseball', 'Julie likes to play basketball', 'Jane loves to play baseball'] new_term_freq_matrix = tfidf_vectorizer.transform(new_docs) print tfidf_vectorizer.vocabulary_ print new_term_freq_matrix.todense() </code></pre> <p>output:</p> <pre><code>{u'me': 8, u'basketball': 1, u'julie': 4, u'baseball': 0, u'likes': 5, u'loves': 7, u'jane': 3, u'linda': 6, u'more': 9, u'than': 10, u'he': 2} [[ 0.57735027 0.57735027 0.57735027 0. 0. 0. 0. 0. 0. 0. 0. ] [ 0. 0.68091856 0. 0. 0.51785612 0.51785612 0. 0. 0. 0. 0. ] [ 0.62276601 0. 0. 0.62276601 0. 0. 0. 0.4736296 0. 0. 0. ]] </code></pre> <p>What is?(e.g.: u'me': 8 ):</p> <pre><code>{u'me': 8, u'basketball': 1, u'julie': 4, u'baseball': 0, u'likes': 5, u'loves': 7, u'jane': 3, u'linda': 6, u'more': 9, u'than': 10, u'he': 2} </code></pre> <p>is this a matrix or just a vector?, i can´t understand what´s telling me the output:</p> <pre><code>[[ 0.57735027 0.57735027 0.57735027 0. 0. 0. 0. 0. 0. 0. 0. ] [ 0. 0.68091856 0. 0. 0.51785612 0.51785612 0. 0. 0. 0. 0. ] [ 0.62276601 0. 0. 0.62276601 0. 0. 0. 0.4736296 0. 0. 0. ]] </code></pre> <p>Could anybody explain me in more detail these outputs?</p> <p>Thanks!</p>
0
1,105
How do you add additional files to a wheel?
<p>How do control what files are included in a wheel? It appears <code>MANIFEST.in</code> isn't used by <code>python setup.py bdist_wheel</code>.</p> <p><strong>UPDATE</strong>:</p> <p>I was wrong about the difference between installing from a source tarball vs a wheel. The source distribution includes files specified in <code>MANIFEST.in</code>, but the installed package only has python files. Steps are needed to identify additional files that should be installed, whether the install is via source distribution, egg, or wheel. Namely, <a href="https://docs.python.org/2/distutils/setupscript.html#installing-package-data">package_data</a> is needed for additional package files, and <a href="https://docs.python.org/2/distutils/setupscript.html#installing-additional-files">data_files</a> for files outside your package like command line scripts or system config files.</p> <h2>Original Question</h2> <p>I have <a href="https://github.com/tulsawebdevs/django-multi-gtfs">a project</a> where I've been using <code>python setup.py sdist</code> to build my package, <code>MANIFEST.in</code> to control the files included and excluded, and <a href="https://pypi.python.org/pypi/pyroma">pyroma</a> and <a href="https://pypi.python.org/pypi/check-manifest">check-manifest</a> to confirm my settings.</p> <p>I recently converted it to dual Python 2 / 3 code, and added a setup.cfg with</p> <pre><code>[bdist_wheel] universal = 1 </code></pre> <p>I can build a wheel with <code>python setup.py bdist_wheel</code>, and it appears to be a universal wheel as desired. However, it doesn't include all of the files specified in <code>MANIFEST.in</code>. </p> <h2>What gets installed?</h2> <p>I dug deeper, and now know more about packaging and wheel. Here's what I learned:</p> <p>I upload two package files to the <a href="https://pypi.python.org/pypi/multigtfs/0.4.2">multigtfs project on PyPi</a>:</p> <ul> <li><code>multigtfs-0.4.2.tar.gz</code> - the source tar ball, which includes all the files in <code>MANIFEST.in</code>.</li> <li><code>multigtfs-0.4.2-py2.py3-none-any.whl</code> - The binary distribution in question.</li> </ul> <p>I created two new virtual environments, both with Python 2.7.5, and installed each package (<code>pip install multigtfs-0.4.2.tar.gz</code>). The two environments are almost identical. They have different <code>.pyc</code> files, which are the "compiled" Python files. There are log files which record the different paths on disk. The install from the source tar ball includes a folder <code>multigtfs-0.4.2-py27.egg-info</code>, detailing the installation, and the wheel install has a <code>multigtfs-0.4.2.dist-info</code> folder, with the details of that process. However, from the point of view of code using the multigtfs project, there is no difference between the two installation methods.</p> <p>Explicitly, neither has the .zip files used by my test, so the test suite will fail:</p> <pre><code>$ django-admin startproject demo $ cd demo $ pip install psycopg2 # DB driver for PostGIS project $ createdb demo # Create PostgreSQL database $ psql -d demo -c "CREATE EXTENSION postgis" # Make it a PostGIS database $ vi demo/settings.py # Add multigtfs to INSTALLED_APPS, # Update DATABASE to set ENGINE to django.contrib.gis.db.backends.postgis # Update DATABASE to set NAME to test $ ./manage.py test multigtfs.tests # Run the tests ... IOError: [Errno 2] No such file or directory: u'/Users/john/.virtualenvs/test/lib/python2.7/site-packages/multigtfs/tests/fixtures/test3.zip' </code></pre> <h2>Specifying additional files</h2> <p>Using the suggestions from the answers, I added some additional directives to <code>setup.py</code>:</p> <pre><code>from __future__ import unicode_literals # setup.py now requires some funky binary strings ... setup( name='multigtfs', packages=find_packages(), package_data={b'multigtfs': ['test/fixtures/*.zip']}, include_package_data=True, ... ) </code></pre> <p>This installs the zip files (as well as the README) to the folder, and tests now run correctly. Thanks for the suggestions!</p>
0
1,400
AES string encryption in Objective-C
<p>My Objective-C App requires text / string encryption (specifically <a href="/questions/tagged/nsstring" class="post-tag" title="show questions tagged 'nsstring'" rel="tag">nsstring</a>). </p> <p>I know AES is the most secure encryption method available for consumer use. I also understand how to convert strings to data and back... (just a beginner). </p> <p>Many webpages and Q/As about encryption with AES are unclear, and none of them state how to use the code given. For example, a webpage might say: "here is the code... here is what it does..." but no explanation for how to use it. </p> <p>I've found this code through lots of research:</p> <pre><code>#import "&lt;CommonCrypto/CommonCryptor.h&gt;" @implementation NSMutableData(AES) </code></pre> <p>For encryption:</p> <pre><code>- (NSMutableData*) EncryptAES:(NSString *)key { char keyPtr[kCCKeySizeAES256+1]; bzero( keyPtr, sizeof(keyPtr) ); [key getCString: keyPtr maxLength: sizeof(keyPtr) encoding: NSUTF16StringEncoding]; size_t numBytesEncrypted = 0; NSUInteger dataLength = [self length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); NSMutableData *output = [[NSData alloc] init]; CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256, NULL, [self mutableBytes], [self length], buffer, bufferSize, &amp;numBytesEncrypted); output = [NSMutableData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; if(result == kCCSuccess) { return output; } return NULL; } </code></pre> <p>For Decryption:</p> <pre><code>- (NSMutableData*)DecryptAES: (NSString*)key andForData:(NSMutableData*)objEncryptedData { char keyPtr[kCCKeySizeAES256+1]; bzero( keyPtr, sizeof(keyPtr) ); [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF16StringEncoding]; size_t numBytesEncrypted = 0; NSUInteger dataLength = [self length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer_decrypt = malloc(bufferSize); NSMutableData *output_decrypt = [[NSData alloc] init]; CCCryptorStatus result = CCCrypt(kCCDecrypt , kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256, NULL, [self mutableBytes], [self length], buffer_decrypt, bufferSize, &amp;numBytesEncrypted); output_decrypt = [NSMutableData dataWithBytesNoCopy:buffer_decrypt length:numBytesEncrypted]; if(result == kCCSuccess) { return output_decrypt; } return NULL; } } </code></pre> <p>This is the code I made that I would like to correspond with the above code:</p> <pre><code>- (void)Encrypt { //Convert NSString to NSData so that it can be used to encrypt the Input NSString *Input = [Inputbox text]; NSData *InputData = [Input dataUsingEncoding:NSUTF8StringEncoding]; //What to do here } </code></pre> <p>How do I use this code, these methods? Where does it go in my Implementation file?</p>
0
1,070
Use retrofit to download image file
<p>I use Retrofit 1.6.0 on my Android project,</p> <p>the request url:</p> <p><a href="https://example.com/image/thumbs/filename/sample.png" rel="noreferrer">https://example.com/image/thumbs/filename/sample.png</a></p> <p>My interface like this:</p> <pre><code>public interface ImageService { @GET("/image/thumbs/filename/{filename}") @Streaming void getThumbs( @Path("filename") String filename, Callback&lt;Response&gt; callback ); } </code></pre> <p>HTTP request was success, but there some error occur</p> <pre><code>D/Retrofit(27613): ---&gt; HTTP GET https://example.com/image/thumbs/filename/sample.png D/Retrofit(27613): ---&gt; END HTTP (no body) D/Retrofit(27613): &lt;--- HTTP 200 https://example.com/image/thumbs/filename/sample.png (451ms) D/Retrofit(27613): : HTTP/1.1 200 OK D/Retrofit(27613): Connection: Keep-Alive D/Retrofit(27613): Content-Disposition: inline; filename="sample.png" D/Retrofit(27613): Content-Type: image/png; charset=binary D/Retrofit(27613): Date: Wed, 11 Jun 2014 06:02:31 GMT D/Retrofit(27613): Keep-Alive: timeout=5, max=100 D/Retrofit(27613): OkHttp-Received-Millis: 1402466577134 D/Retrofit(27613): OkHttp-Response-Source: NETWORK 200 D/Retrofit(27613): OkHttp-Sent-Millis: 1402466577027 D/Retrofit(27613): Server: Apache/2.2.22 (Ubuntu) D/Retrofit(27613): Transfer-Encoding: chunked D/Retrofit(27613): X-Powered-By: PHP/5.4.28-1+deb.sury.org~precise+1 D/Retrofit(27613): ---- ERROR https://example.com/image/thumbs/filename/sample.png D/Retrofit(27613): java.io.UnsupportedEncodingException: binary D/Retrofit(27613): at java.nio.charset.Charset.forNameUEE(Charset.java:322) D/Retrofit(27613): at java.lang.String.&lt;init&gt;(String.java:228) D/Retrofit(27613): at retrofit.RestAdapter.logAndReplaceResponse(RestAdapter.java:478) D/Retrofit(27613): at retrofit.RestAdapter.access$500(RestAdapter.java:109) D/Retrofit(27613): at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:333) D/Retrofit(27613): at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220) D/Retrofit(27613): at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278) D/Retrofit(27613): at retrofit.CallbackRunnable.run(CallbackRunnable.java:42) D/Retrofit(27613): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) D/Retrofit(27613): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) D/Retrofit(27613): at retrofit.Platform$Android$2$1.run(Platform.java:142) D/Retrofit(27613): at java.lang.Thread.run(Thread.java:841) D/Retrofit(27613): Caused by: java.nio.charset.UnsupportedCharsetException: binary D/Retrofit(27613): at java.nio.charset.Charset.forName(Charset.java:309) D/Retrofit(27613): at java.nio.charset.Charset.forNameUEE(Charset.java:320) D/Retrofit(27613): ... 11 more D/Retrofit(27613): ---- END ERROR </code></pre> <p>How do I solve this problem?</p>
0
1,234
Hibernate - ClassNotFoundException: com.mysql.jdbc.Driver
<p>I'm trying to retrieve data from a MySQL database through Hibernate, but I'm stuck with this error:</p> <pre><code>Failed to create sessionFactory object.org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver [...] </code></pre> <p>I use a class called DAOFactory to get the hibernate session:</p> <pre><code>public class DAOFactory { private static boolean isInstance = false; private static SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; private static Session session; private DAOFactory() throws ExceptionInInitializerError{ if( !isInstance ) { try { Configuration cfg = new Configuration().configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()) .buildServiceRegistry(); sessionFactory = cfg.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Failed to create sessionFactory object."+ ex); throw new ExceptionInInitializerError(ex); } session = sessionFactory.openSession(); isInstance = true ; } } public static DAOFactory getInstance() { return new DAOFactory() ; } public Session getSession() { return session ; } } </code></pre> <p>hibernate.cfg.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt; &lt;hibernate-configuration&gt; &lt;session-factory name=""&gt; &lt;property name="connection.driver_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt; &lt;property name="connection.url"&gt;jdbc:mysql://localhost:3306/enigma&lt;/property&gt; &lt;property name="connection.username"&gt;root&lt;/property&gt; &lt;property name="connection.password"&gt;&lt;/property&gt; &lt;property name="dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt; &lt;property name="connection.pool_size"&gt;1&lt;/property&gt; &lt;property name="current_session_context_class"&gt;thread&lt;/property&gt; &lt;property name="cache.provider_class"&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p>And <code>mysql-connector-java-5.1.26-bin.jar</code> is already in the classpath:</p> <p><img src="https://i.stack.imgur.com/yx8rP.png" alt="classpath"></p> <p>Does anyone see what I'm missing ?</p>
0
1,370
C# Input string was not in a correct format. Conversion issue on server not in local machine
<p>I am croppping the image and save. On btnsave_click I am converting the hiddenfield value to decimal. There is no error on local machine but when published to server it gives below error.</p> <p><strong>Detailed exception on server</strong>:</p> <h2><em>Input string was not in a correct format.</em></h2> <p>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.</p> <p>Exception Details: System.FormatException: Input string was not in a correct format.</p> <p>Source Error:</p> <p>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.</p> <p>Stack Trace:</p> <blockquote> <p>[FormatException: Input string was not in a correct format.]<br> System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer&amp; number, NumberFormatInfo info, Boolean parseDecimal) +10726387 System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) +172<br> System.Convert.ToDecimal(String value) +68<br> IngredientMatcher.Pages.ImageCropPopup.btnsave_Click(Object sender, EventArgs e) +104<br> System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9552602<br> System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103<br> System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10<br> System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13<br> System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724</p> </blockquote> <p><strong>Code :</strong>:</p> <pre><code>protected void btnsave_Click(object sender, EventArgs e) { string ImageName = ViewState["ImageName"].ToString(); int www = Convert.ToInt32(Math.Round(Convert.ToDecimal(W.Value))); int hhh = Convert.ToInt32(Math.Round(Convert.ToDecimal(H.Value))); int xxx = Convert.ToInt32(Math.Round(Convert.ToDecimal(X.Value))); int yyy = Convert.ToInt32(Math.Round(Convert.ToDecimal(Y.Value))); int w = (www == 0) ? 0 : www; int h = (hhh == 0) ? 0 : hhh; int x = (xxx == 0) ? 0 : xxx; int y = (yyy == 0) ? 0 : yyy; byte[] CropImage = Crop(Server.MapPath(" ") + "\\" + upPath + ImageName, w, h, x, y); using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length)) { ms.Write(CropImage, 0, CropImage.Length); using (SD.Image CroppedImage = SD.Image.FromStream(ms, true)) { string SaveTo = Server.MapPath("") + "\\" + CropPath + "crop" + ImageName; CroppedImage.Save(SaveTo, CroppedImage.RawFormat); imgCropped.BorderWidth = 1; imgCropped.ImageUrl = CropPath + "crop" + ImageName; } } string CroppedImg = "crop" + ViewState["ImageName"].ToString(); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "OpenPopUp", "javascript:SaveAndClose('" + CroppedImg + "');", true); } </code></pre> <p>Thanks in advance.</p>
0
1,201
The format of the URI could not be determined
<p>I'm working on application that take attendance records from attendance system and put it inside access file and upload to my web site. it's working successfully but but when i focus on other screen in my desktop and go back to the application give this error ! "Invalid URI: The format of the URI could not be determined"</p> <p>This is the code:</p> <pre><code>public void BatchTransfert(zkemkeeper.CZKEMClass axCZKEM1, int index, BackgroundWorker worker, DoWorkEventArgs e) { string sdwEnrollNumber =""; int idwEnrollNumber = 0; int idwTMachineNumber = 0; int idwEMachineNumber = 0; int idwVerifyMode = 0; int idwInOutMode = 0; int idwYear = 0; int idwMonth = 0; int idwDay = 0; int idwHour = 0; int idwMinute = 0; int idwSecond = 0; int idwWorkcode = 0; int idwWorkCode = 0; int idwReserved = 0; int idwErrorCode = 0; int iGLCount = 0; int iIndex = 0; string time; string pcTime = DateTime.Now.Year.ToString() + "-" + GetMonthName(DateTime.Now.Month).ToString() + "-" + DateTime.Now.Day.ToString() + " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(); string userID; int AttStat; DataSet ds = new DataSet(); DataTable AttendanceLogs = new DataTable(); DataColumn USERID = new DataColumn(); USERID.DataType = System.Type.GetType("System.String"); USERID.ColumnName = "USERID"; DataColumn CHECKTIME = new DataColumn(); CHECKTIME.DataType = System.Type.GetType("System.String"); CHECKTIME.ColumnName = "CHECKTIME"; DataColumn CHECKTYPE = new DataColumn(); CHECKTYPE.DataType = System.Type.GetType("System.Int32"); CHECKTYPE.ColumnName = "CHECKTYPE"; AttendanceLogs.Columns.Add(USERID); AttendanceLogs.Columns.Add(CHECKTIME); AttendanceLogs.Columns.Add(CHECKTYPE); ds.Tables.Add(AttendanceLogs); string sqlOnlineUpdate = ""; string deviceIPAdress = ""; try { Cursor = Cursors.WaitCursor; axCZKEM1.EnableDevice(iMachineNumber[index], false);//disable the device if (axCZKEM1.ReadGeneralLogData(iMachineNumber[index]))//read all the attendance records to the memory { while (axCZKEM1.IsTFTMachine(iMachineNumber[index]) ? axCZKEM1.SSR_GetGeneralLogData(iMachineNumber[index], out sdwEnrollNumber, out idwVerifyMode, out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkCode) //TFt machine : axCZKEM1.GetGeneralLogData(iMachineNumber[index], ref idwTMachineNumber, ref idwEnrollNumber, ref idwEMachineNumber, ref idwVerifyMode, ref idwInOutMode, ref idwYear, ref idwMonth, ref idwDay, ref idwHour, ref idwMinute)) //ref idwSecond ref idwWorkCode)) { iGLCount++; time = idwYear.ToString() + "-" + GetMonthName(idwMonth).ToString() + "-" + idwDay.ToString() + " " + idwHour.ToString() + ":" + idwMinute.ToString() + ":" + idwSecond.ToString(); pcTime = DateTime.Now.Year.ToString() + "-" + GetMonthName(DateTime.Now.Month).ToString() + "-" + DateTime.Now.Day.ToString() + " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(); userID = axCZKEM1.IsTFTMachine(iMachineNumber[index]) ? sdwEnrollNumber : idwEnrollNumber.ToString(); AttStat = idwInOutMode; DataRow newRow = AttendanceLogs.NewRow(); newRow["USERID"] = userID; newRow["CHECKTIME"] = time; newRow["CHECKTYPE"] = idwInOutMode; AttendanceLogs.Rows.Add(newRow); } string filename = Application.StartupPath + "\\config.txt"; Serializer serializeFromFile = new Serializer(); settings = serializeFromFile.DeSerializeObject(filename); //axCZKEM1.Disconnect(); axCZKEM1.EnableDevice(iMachineNumber[index], true);//enable the device if (AttendanceLogs.Rows.Count &gt; 0) { int i = 0; progressBar1.Enabled = true; progressBar1.Maximum = AttendanceLogs.Rows.Count; progressBar1.Visible = true; labelProgress.Visible = true; String connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + settings.localDBPath; OleDbConnection conn = new OleDbConnection(connString); conn.Open(); axCZKEM1.GetDeviceIP(iMachineNumber[index], ref deviceIPAdress); string sqlSelect; string queryString; string onlineApp; string urlAdress; #region UploadData foreach (DataRow row in AttendanceLogs.Rows) { try { if (worker.CancellationPending == true) { e.Cancel = true; break; } else { i++; progressBar1.Value = i; //Connection Info for Local DB sqlSelect = "Select * from CHECKINOUT WHERE USERID = " + row["USERID"] + " and CHECKTIME = #" + row["CHECKTIME"] + "# and CHECKTYPE = '" + row["CHECKTYPE"] + "'"; OleDbCommand cmd = new OleDbCommand(sqlSelect, conn); OleDbDataReader dataReader = cmd.ExecuteReader(); //Saving in local Db if (!dataReader.HasRows) { queryString = "userID=" + row["USERID"] + "&amp;time=" + row["CHECKTIME"] + "&amp;AttStat=" + row["CHECKTYPE"] + "&amp;pcTime=" + pcTime + "&amp;schoolID=" + schoolID + "&amp;schoolName=" + schoolName + "&amp;machineName=" + machineName; onlineApp = settings.onlinURL + @"/Admin/HR/Attendance_UpdateData.ashx?" + queryString; urlAdress = onlineApp; Uri url = new Uri(urlAdress); HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Method = "Get"; HttpWebResponse myWebResponse = (HttpWebResponse)webReq.GetResponse(); if (myWebResponse.ContentLength == 7) { dataReader.Close(); string sqlUpdate = "INSERT INTO CHECKINOUT ( USERID, CHECKTIME, CHECKTYPE )" + "VALUES (" + row["USERID"] + ", #" + row["CHECKTIME"] + "#, " + row["CHECKTYPE"] + ")"; cmd.CommandText = sqlUpdate; dataReader = cmd.ExecuteReader(); } myWebResponse.Close(); } labelProgress.Text = "Transfering data from device IP : " + deviceIPAdress + ".... " + progressBar1.Value.ToString() + " / " + progressBar1.Maximum.ToString(); //row["USERID"]; labelProgress.Refresh(); dataReader.Close(); dataReader.Dispose(); } } catch (SqlException sqlExp) { MessageBox.Show(sqlExp.Message); EventLog.WriteEntry("User ID", sqlExp.Message, EventLogEntryType.Information, 15); SendMail("School : " + machineName + " / 'Method Batch Down' Error in Online database Conn : " + sqlExp.Message + "\n" + "Sql Query : " + sqlOnlineUpdate); } catch (Exception exp) { MessageBox.Show("Herre Apear the Error!!!!!!!!" + exp.Message + " +" + exp.HelpLink); EventLog.WriteEntry("RFID finger Print", exp.Message, EventLogEntryType.Information, 15); SendMail("School : " + machineName + " / 'Method Batch Down' Error in Transfert Data : " + exp.Message + "\n" + "Sql Query : " + sqlOnlineUpdate); } } #endregion //conn.Close(); //conn.Dispose(); } //objConn.Close(); } else { Cursor = Cursors.Default; axCZKEM1.GetLastError(ref idwErrorCode); if (idwErrorCode != 0 &amp;&amp; idwErrorCode != -2) { //MessageBox.Show("Reading data from terminal failed,ErrorCode: " + idwErrorCode.ToString(), "Error"); SendMail("Reading data from terminal failed, ErrorCode: " + idwErrorCode.ToString()); } else { //SendMail("No data from terminal returns!, ErrorCode: " + idwErrorCode.ToString()); } } axCZKEM1.EnableDevice(iMachineNumber[index], true); labelProgress.Visible = false; progressBar1.Visible = false; Cursor = Cursors.Default; } catch (SqlException sqlEx) { EventLog.WriteEntry("User ID", sqlEx.Message, EventLogEntryType.Information, 15); SendMail("School : " + machineName + " / 'Method Batch Down' Error in Online database Conn : " + sqlEx.Message + "\n" + "Sql Query : " + sqlOnlineUpdate); } catch (Exception ex) { EventLog.WriteEntry("RFID finger Print", ex.Message, EventLogEntryType.Information, 15); //SendMail("School : " + machineName + " / 'Method Batch Down' Error in Transfert Data : " + ex.Message + "\n" + "Sql Query : " + sqlOnlineUpdate); } } </code></pre>
0
5,822
Reading JSON Tiled map editor file and displaying to canvas
<p>Im following this <a href="http://blog.hashrocket.com/posts/using-tiled-and-canvas-to-render-game-screens" rel="noreferrer">this</a> tutorial to be able to load json map files created by tiled map editor in my javascript/canvas game.</p> <p>ive got to the point where i have implemented my own kind of version, and am getting no errors in firebug in console or net etc.</p> <p>And as far as i can see, by putting in console.logs and alerts, the script is running absolutely fine!</p> <p>The problem is the canvas stays blank! when it should have a tilemap now on it.</p> <p>Here is my version of the tutorial implemented in my game:</p> <pre><code>function Level() { var c; var data; var layers = []; this.get_map = function(name,ctx){ c = ctx; $.getJSON('maps/'+ name + '.json', function(json){ get_tileset(json); }); }; function get_tileset(json) { data = json; this.tileset = $("&lt;img /&gt;", { src: json.tilesets[0].image })[0]; this.tileset.onload = renderLayers(this); } function renderLayers(layers){ layers = $.isArray(layers) ? layers : data.layers; layers.forEach(renderLayer); } function renderLayer (layer){ if (layer.type !== "tilelayer" || !layer.opacity) { alert("Not a tileLayer"); } var s = c.canvas.cloneNode(), size = data.tileWidth; s = s.getContext("2d"); if (layers.length &lt; data.layers.length) { layer.data.forEach(function(tile_idx, i) { if (!tile_idx) { return; } var img_x, img_y, s_x, s_y, tile = data.tilesets[0]; tile_idx--; img_x = (tile_idx % (tile.imagewidth / size)) * size; img_y = ~~(tile_idx / (tile.imagewidth / size)) * size; s_x = (i % layer.width) * size; s_y = ~~(i / layer.width) * size; s.drawImage(this.tileset, img_x, img_y, size, size, s_x, s_y, size, size); }); layers.push(s.canvas.toDataURL()); c.drawImage(s.canvas, 0, 0); } else { layers.forEach(function(src) { var i = $("&lt;img /&gt;", { src: src })[0]; c.drawImage(i, 0, 0); }); } } } </code></pre> <p>and it is called from my main javascript file which is this:</p> <pre><code>$(document).ready(function(){ var canvas = document.getElementById("TBG"); var ctx = canvas.getContext("2d"); var ui = new Gui(); var level = new Level(); //----------Login/Register Gui -------------- $('#TBG').hide(); $('#load-new').hide(); $('#reg').hide(); $('#login').hide(); //if login_but is clicked do ui.login function $('#login_but').click(ui.login); //if reg_but is clicked do ui.register function $('#reg_but').click(ui.register); $('#new_but').click(function(){ game_settings("new"); }); $('#load_but').click(function(){ game_settings("load"); }); //if login_sumbit button is clicked do ui.login_ajax function $("#login_submit").click(ui.login_ajax); $("#reg_submit").click(ui.register_ajax); $("#welcome").on("click", "#logout_but", ui.logout); //________________________ //Initialisation of game function game_settings(state){ if(state == "load"){ ui.load_game(); //do ajax call to load user last save level.get_map("level_01",ctx); } else{ //set beginning params //Change screens ui.new_game(); alert("new game"); } } // End Loop ------------------------------------------------------ }); </code></pre> <p>I don't suppose you lovely people could spot why the tile-map isn't being printed to my canvas?</p> <p>Thanks for any help Tom</p>
0
1,537
Identifier expected? visual basic
<p>im almost done with this and then that... hopefully someone will be able to help me (Really hope so atleast, cus i need to be done with this:P) (need more text cus there is to much code):</p> <pre><code>|error is there|&gt; Private Sub FlatButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FlatButton1_Click. &lt;|error is there| Dim Conn As New MySqlConnection("Not going to publish this") If FlatTextBox1.Text = "" Then MsgBox("No username specified") FlatTextBox2.Text = "" Else If FlatTextBox2.Text = "" Then MsgBox("No password specified") FlatTextBox1.Text = "" Else Try Me.Text = "Logging in..." Conn.Open() Dim sqlquery As String = "SELECT * FROM Testing WHERE Username = '" &amp; FlatTextBox1.Text &amp; "';" Dim data As MySqlDataReader Dim adapter As New MySqlDataAdapter Dim command As New MySqlCommand command.CommandText = sqlquery command.Connection = Conn adapter.SelectCommand = command data = command.ExecuteReader While data.Read() If data.HasRows() = True Then If data(2).ToString = FlatTextBox2.Text Then Me.Text = "Logged in!" My.Settings.Username = FlatTextBox1.Text MsgBox("Welcome " + data(1).ToString) Home.Show() Me.Close() If data(3).ToString = "1" Then My.Settings.Admin = "Yes" Else My.Settings.Admin = "No" End If End If Else MsgBox("Failed Login") End If End While Catch ex As Exception End Try End If End If End Sub End Class </code></pre>
0
1,336
MySQLi export table to CSV
<p>I've been trying for many days to export from a query some values in <code>.csv</code> with MySQLi, but I have a problem when the export is made, everything is exporting to a single column, instead I need that the export should make like SQL code (I have 3 selected columns and I need 3 exported columns in <code>.cvs</code>). Bellow you can find two codes:</p> <p>1) This code creates a data base, table and insert the values:</p> <pre><code>&lt;?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } // Create database $sql = "CREATE DATABASE myDB"; if ($conn-&gt;query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn-&gt;error; } // Create connection pt a crea tabela $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } // sql to create table $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )"; if ($conn-&gt;query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . $conn-&gt;error; } // Create connection pt a insera valori $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } // Insert value in db $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe, Mark', 'john@example.com'), ('Mary', 'Moe-Johny', 'mary@example.com'), ('Julie', 'Dooley', 'julie@example.com')"; if ($conn-&gt;query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "&lt;br&gt;" . $conn-&gt;error; } $conn-&gt;close(); ?&gt; </code></pre> <p>2) This code is for the export in <code>.csv</code>:</p> <pre><code>&lt;?php //header to give the order to the browser header('Content-Type: text/csv'); header('Content-Disposition: attachment;filename=export.csv'); $servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn-&gt;query($sql); if ($result-&gt;num_rows &gt; 0) { // output data of each row while($row = $result-&gt;fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "&lt;br&gt;"; } } else { echo "0 results"; } $conn-&gt;close(); ?&gt; </code></pre> <p>I'm using this XAMP version:</p> <blockquote> <p>Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.1</p> <p>Database client version: libmysql - mysqlnd 5.0.12-dev - 20150407 - $Id: 7e72f9690b1498a1bead7a637c33a831c0d2f655 $</p> <p>PHP extension: mysqli Documentation</p> <p>PHP version: 7.0.1</p> </blockquote> <p>This version creates some problems for the MySQL code, that's why I prefer the code in MySQLi. Thank you very much!</p>
0
1,315
SQL Error 1406 Data too long for column
<p>I am trying to execute the query below in MySQL but get the SQL error 1406 Data too long for column error every time. The column data type is longtext. Any ideas?</p> <pre><code>UPDATE `my_db`.`my_table` SET `content` = '&lt;div id="primaryContent"&gt;&lt;div id="offices_map"&gt;&lt;/div&gt;&lt;!-- #offices_map --&gt;&lt;div id="offices_mapControlPanel" class="cf"&gt;&lt;ul id="offices_continentLinkList"&gt;&lt;li&gt;&lt;a href="#" rel="Africa"&gt;AFRIQUE&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" rel="Asia"&gt;ASIE&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" rel="Australasia"&gt;AUSTRALASIE&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" rel="Europe" id="offices_europeLink" class="current"&gt;EUROPE&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" rel="NorthAmerica"&gt;AMERIQUE DU NORD&lt;/a&gt;&lt;/li&gt;&lt;li class="last"&gt;&lt;a href="#" rel="SouthAmerica"&gt;AMERIQUE DU SUD&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;ul id="offices_mapLegend"&gt;&lt;li id="offices_mapLegendRedPointer"&gt;Bureaux Panavision&lt;/li&gt;&lt;li id="offices_mapLegendYellowPointer"&gt;Agents Panavision&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;!-- #offices_mapLegend --&gt;&lt;div id="offices_ownedOfficesContactDetails" class="cf"&gt;&lt;h2&gt;Bureaux Panavision&lt;/h2&gt;&lt;ul class="cf"&gt;&lt;li class="first"&gt;&lt;strong&gt;Panavision Greenford&lt;/strong&gt; - pour l''Europe et l''Afrique - &lt;a href="#" id="offices_linkPanavisionGreenford"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Panavision Prague - &lt;a href="#" id="offices_linkPanavisionPrague"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Panavision Manchester - &lt;a href="#" id="offices_linkPanavisionManchester"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Panavision Alga &amp;amp; Cinecam - &lt;a href="#" id="offices_linkPanavisionAlga"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Panavision Rh&amp;ocirc;ne-Alpes - &lt;a href="#" id="offices_linkPanavisionRhoneAlpes"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Panavision Marseille - &lt;a href="#" id="offices_linkPanavisionMarseille"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Panavision Pologne - &lt;a href="#" id="offices_linkPanavisionPoland"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Panavision Dublin - &lt;a href="#" id="offices_linkPanavisionDublin"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Panavision Belgique - &lt;a href="#" id="offices_linkPanavisionBelgium"&gt;D&amp;#233;tails&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;!-- #offices_ownedOfficesContactDetails --&gt;&lt;/div&gt;&lt;!-- #offices_mapControlPanel --&gt;&lt;div class="cf"&gt;&lt;/div&gt;' WHERE `my_table`.`id` = 27; </code></pre> <p>Thanks, here's the result from SHOW CREATE TABLE</p> <pre><code> CREATE TABLE `my_table` ( `content` longtext NOT NULL, `cat` text NOT NULL, `starter` int(1) NOT NULL, `at` int(11) DEFAULT '0', `table` varchar(60) DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=84 DEFAULT CHARSET=latin1 | </code></pre> <p>Just tried this shorter query which contains no special/escaped chars but I still get the error.</p> <pre><code>UPDATE `my_db`.`my_table` SET `contenu` = '&lt;div id="primaryContent"&gt;&lt;div id="offices_map"&gt;&lt;/div&gt;&lt;!-- #offices_map --&gt;&lt;div id="offices_mapControlPanel" class="cf"&gt;&lt;ul id="offices_continentLinkList"&gt;&lt;li&gt;&lt;a href="#" rel="Africa"&gt;AFRIQUE&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" rel="Asia"&gt;ASIE&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" rel="Australasia"&gt;AUSTRALASIE&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" rel="Europe" id="offices_europeLink" class="current"&gt;EUROPE&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" rel="NorthAmerica"&gt;AMERIQUE DU NORD&lt;/a&gt;&lt;/li&gt;&lt;li class="last"&gt;&lt;a href="#" rel="SouthAmerica"&gt;AMERIQUE DU SUD&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;ul id="offices_mapLegend"&gt;&lt;li id="offices_mapLegendRedPointer"&gt;Bureaux Panavision&lt;/li&gt;&lt;li id="offices_mapLegendYellowPointer"&gt;Agents Panavision&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;!-- #offices_mapLegend --&gt;' WHERE `my_table`.`id` = 27; </code></pre> <p>[SOLVED] Thanks for your help everyone, I deleted the HTML comments and it worked.</p>
0
2,021
getApplicationContext() error Android
<p>I have a fragment that allows a user to enter in a message and a phone number to which the message will be delivered. I am getting an error "cannot resolve method getApplicationContext()" I have looked at the answer here <a href="https://stackoverflow.com/questions/16678763/the-method-getapplicationcontext-is-undefined">the method getApplicationContext() is undefined</a> but it didn't help me, maybe I am implementing it wrong but I am not sure! This code works fine as an activity but not as a fragment.</p> <p><strong>FragmentTab1 class</strong></p> <pre><code>package com.androidbegin.absfragtabhost; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.app.Fragment; import android.app.Activity; import android.telephony.SmsManager; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class FragmentTab3 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragmenttab3, container, false); super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); sendBtn = (Button) rootView.findViewById(R.id.btnSendSMS); txtphoneNo = (EditText) rootView.findViewById(R.id.editTextPhoneNo); txtMessage = (EditText) rootView.findViewById(R.id.editTextSMS); sendBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { sendSMSMessage(); } }); return rootView; } Button sendBtn; EditText txtphoneNo; EditText txtMessage; protected void sendSMSMessage() { Log.i("Send SMS", ""); String phoneNo = txtphoneNo.getText().toString(); String message = txtMessage.getText().toString(); try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null, message, null, null); Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "SMS failed, please try again.", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } } </code></pre>
0
1,038
How do I get a reference to an IHostedService via Dependency Injection in ASP.NET Core?
<h1>Details</h1> <p>I have attempted to create a background processing structure using the recommended <code>IHostedService</code> interface in ASP.NET 2.1. I register the services as follows:</p> <pre><code>services.AddSingleton&lt;AbstractProcessQueue&lt;AbstractImportProcess&gt;&gt;(); services.AddHostedService&lt;AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;&gt;(); services.AddSignalR(); </code></pre> <p>The <code>AbstractProcessQueue</code> is just a wrapper around a <code>BlockingCollection</code> of processes that can be enqueued and dequeued. The <code>AbstractBackgroundProcessService</code> implements the <code>IHostedService</code> interface and looks at the queue for new processes it can start.</p> <p>Now, the trouble starts when, inside a <code>SignalR</code> hub, I attempt to get a reference to the background processing service via the <code>Dependency Injection</code> mechanisms. I have tried the following solutions, but none seem to be working as intended:</p> <h3>Option 1:</h3> <pre><code>public HubImportClient(IServiceProvider provider) { //This returns null. var service = provider.GetService&lt;AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;&gt;(); } </code></pre> <h3>Option 2:</h3> <pre><code>public HubImportClient(IServiceProvider provider) { //This returns null. var service = (AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;) provider.GetService(typeof(AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;&gt;)); } </code></pre> <h3>Option 3:</h3> <pre><code>public HubImportClient(IServiceProvider provider) { //This throws an exception, because the service is missing. var service = provider.GetRequiredService&lt;AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;&gt;(); } </code></pre> <h3>Option 4:</h3> <pre><code>public HubImportClient(IServiceProvider provider) { //This throws an exception, because the service is missing. var service = (AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;) provider.GetRequiredService(typeof(AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;); } </code></pre> <h3>Option 5:</h3> <pre><code>public HubImportClient(IServiceProvider provider) { //This returns a correct service, but prevents me from adding additional AbstractBackgroundProcessService implementations with different type parameters. //Additionally, it seems like this reference was newly created, and not the instance that was created on application startup (i.e. the hash codes are different, and the constructor is called an additional time). var service = provider.GetService&lt;IHostedService&gt;(); if(service is AbstractBackgroundProcessService&lt;AbstractProcessService&gt;) { this.Service = (AbstractBackgroundProcessService&lt;AbstractProcessService&gt;) service;} } </code></pre> <h3>Option 6:</h3> <pre><code>public HubImportClient(IServiceProvider provider) { //This works similarly to the previous option, and allows multiple implementations, but the constructor is still called twice and the instances thus differ. AbstractBackgroundProcessService&lt;AbstractImportProcess&gt; service = null; foreach(IHostedService service in provider.GetServices&lt;IHostedService&gt;()) { if(service is AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;) { service = (AbstractBackgroundProcessService&lt;AbstractImportProcess&gt;) service; break; } } } </code></pre> <h3>Option 7:</h3> <pre><code>public HubImportClient(IServiceProvider provider) { //This just skips the for each loop all together, because no such services could be found. AbstractBackgroundProcessService&lt;AbstractImportProcess&gt; service = null; foreach(AbstractBackgroundProcessService&lt;AbstractImportProcess&gt; current in provider.GetServices&lt;AbstractBackgroundProcessService&lt;AbstractImportProcess&gt; &gt;()) { service = current; break; } } </code></pre> <h3>Option 8:</h3> <pre><code>//This works, but prevents multiple implementations again. public HubImportClient(IHostedService service) { this.Service = service; } </code></pre> <h3>Option 9:</h3> <pre><code>//This does not work again. public HubImportClient(AbstractBackgroundProcessService&lt;AbstractImportProcess&gt; service) { this.Service = service; } </code></pre> <h1>Question</h1> <p>So then my question remains: how am I supposed to get a reference to an <code>IHostedService</code> implementation so that:</p> <p>(a): I can inject multiple instances of the service that differ only by their type parameter (e.g. a hosted service for <code>AbstractImportProcess</code>es as well as one for <code>AbstractExportProcess</code>es)</p> <p>(b): there is only ever one instance of the <code>IHostedService</code> for that specific type parameter.</p> <p>Thanks in advance for any help!</p>
0
1,540
Fails to load Spring application context in tests with SpringJUnit4ClassRunner
<p>I can't figure out why Spring can't load the application context in a test class defined as follows:</p> <pre><code> @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/springMVC-config/mainController-servlet.xml"}) public class DiagnosticsControllerTest { @Mock DiagnosticsService diagnosticsService; private DiagnosticsController diagnosticsController; private MockMvc mockMvc; @Before public void setUp() { MockitoAnnotations.initMocks(this); diagnosticsController = new DiagnosticsController(); diagnosticsController.setService(diagnosticsService); this.mockMvc = MockMvcBuilders.standaloneSetup(diagnosticsController).build(); } @Test public void shouldRun() { assertTrue(1 == 1); } } </code></pre> <p>The file 'mainController-servlet.xml' is in "myproject\src\main\webapp\WEB-INF\springMVC-config\mainController-servlet.xml"</p> <p>The error I get is:</p> <pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [springMVC-config/mainController-servlet.xml]; nested exception is java.io.FileNotFoundException: class path resource [springMVC-config/mainController-servlet.xml] cannot be opened because it does not exist </code></pre> <p>I tried to change the locations for the context configuration as follows:</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:src/main/webapp/WEB-INF/springMVC-config/mainController-servlet.xml") public class DiagnosticsControllerTest { ... } </code></pre>
0
1,489
How to implement the classic "sticky footer" with angular-material?
<p>I recognize that the <a href="https://github.com/angular/material">Angular Material</a> implementation is a work in progress, but I've spent some time this morning trying to get familiar with it. However, I'm really struggling to get the concepts shown in the demos to work in a stand alone site.</p> <p>It seems that when the directives like <code>&lt;md-toolbar&gt;</code> and <code>&lt;md-content&gt;</code> are used in containers with fixed heights, then they work great. I'm struggling with how to throw them inside a <code>&lt;body</code> tag and be able to have a sticky footer layout <a href="https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/">like in this example</a>.</p> <p>I've tried many variations, but here's one example that doesn't work when the content is removed from the DOM. When the content is there it grows beyond the viewport and the footer is placed afterwards like you'd expect. In the latest versions of Chrome and Firefox this example keeps the footer at the bottom when the content is removed, but in IE this just doesn't work at all. In IE the footer floats just below the header regardless of whether the main content is shown or not.</p> <p><strong>DEMO:</strong> <a href="http://codepen.io/sstorie/pen/xbGgqb">http://codepen.io/sstorie/pen/xbGgqb</a></p> <pre><code>&lt;body ng-app="materialApp" layou-fill layout='column'&gt; &lt;div ng-controller="AppCtrl" layout='column' flex&gt; &lt;md-toolbar class='md-medium-tall'&gt; &lt;div class="md-toolbar-tools"&gt; &lt;span&gt;Fixed to Top&lt;/span&gt; &lt;span flex&gt;&lt;/span&gt; &lt;md-button class="md-raised" ng-click="toggleContent(!displayContent)"&gt;toggle content&lt;/md-button&gt; &lt;/div&gt; &lt;/md-toolbar&gt; &lt;main class='md-padding' layout="row" flex&gt; &lt;div flex&gt; &lt;md-card ng-if="displayContent" ng-repeat = "card in cards"&gt; {{$index}} {{card.title}} {{card.text}} &lt;/md-card&gt; &lt;/div&gt; &lt;div flex&gt; &lt;md-card ng-if="displayContent" ng-repeat = "card in cards"&gt; {{$index}} {{card.title}} {{card.text}} &lt;/md-card&gt; &lt;/div&gt; &lt;/main&gt; &lt;md-toolbar class="md-medium-tall"&gt; &lt;div layout="row" layout-align="center center" flex&gt; &lt;span&gt;FOOTER&lt;/span&gt; &lt;/div&gt; &lt;/md-toolbar&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>Javascript:</p> <pre><code>angular.module('materialApp', ['ngMaterial']) .controller('AppCtrl', function($scope) { $scope.cards = [ {text: 'Bla bla bla bla bla bla bla ', title: 'Bla' }, ...repeat 10 times... ]; $scope.displayContent = true; $scope.toggleContent = function(showContent) { $scope.displayContent = showContent; }; }); </code></pre> <p>CSS:</p> <pre><code>body { min-height: 100%; height: auto !important; height: 100%; } </code></pre> <p>I'm definitely not a CSS guru, but it feels like this should be easy to do with the layout options in angular-material, so I'm hoping I'm really missing something obvious here.</p>
0
1,311
The model item passed into the dictionary is of type ‘mvc.Models.ModelA’ but this dictionary requires a model item of type ‘mvc.Models.ModelB‘
<p>I have this annoying mistake in some of my builds.</p> <p>There is no error in the project, because if I build again, then the problem disappears. The message only appears, when the site is deployed to a Windows 2008 Server.</p> <p>I first thought that it might be an issue with temporary files, but thats not the case. I deployed the build to a different web and the error still appears.</p> <p>The error appears on random actions of the site. Most of the time builds are ok, but each 3rd or 4th build produces runtime errors.</p> <p>I build using a WebdeploymentProject in release mode. Views are precompiled.</p> <p>It's not <a href="https://stackoverflow.com/questions/178194/in-asp-net-mvc-i-encounter-an-incorrect-type-error-when-rendering-a-page-with-the">In ASP.NET MVC I encounter an incorrect type error when rendering a page with the correct typed object</a>, because views have totally different names.</p> <p>How I can debug this problem or how I can get help for this?</p> <p>Here is my WebDeploymentProject</p> <pre><code> &lt;!-- Microsoft Visual Studio 2008 Web Deployment Project http://go.microsoft.com/fwlink/?LinkID=104956 --&gt; &lt;Project ToolsVersion=&quot;3.5&quot; DefaultTargets=&quot;Build&quot; xmlns=&quot;http://schemas.microsoft.com/developer/msbuild/2003&quot;&gt; &lt;PropertyGroup&gt; &lt;Configuration Condition=&quot; '$(Configuration)' == '' &quot;&gt;Debug&lt;/Configuration&gt; &lt;Platform Condition=&quot; '$(Platform)' == '' &quot;&gt;AnyCPU&lt;/Platform&gt; &lt;ProductVersion&gt;9.0.21022&lt;/ProductVersion&gt; &lt;SchemaVersion&gt;2.0&lt;/SchemaVersion&gt; &lt;ProjectGuid&gt;{E5E14CEB-0BCD-4203-9A5A-34ABA9C717EA}&lt;/ProjectGuid&gt; &lt;SourceWebPhysicalPath&gt;..\B2CWeb&lt;/SourceWebPhysicalPath&gt; &lt;SourceWebProject&gt;{3E632DB6-6DB3-4BD0-8CCA-12DE67165B48}|B2CWeb\B2CWeb.csproj&lt;/SourceWebProject&gt; &lt;SourceWebVirtualPath&gt;/B2CWeb.csproj&lt;/SourceWebVirtualPath&gt; &lt;TargetFrameworkVersion&gt;v3.5&lt;/TargetFrameworkVersion&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup Condition=&quot; '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' &quot;&gt; &lt;DebugSymbols&gt;true&lt;/DebugSymbols&gt; &lt;OutputPath&gt;.\Debug&lt;/OutputPath&gt; &lt;EnableUpdateable&gt;false&lt;/EnableUpdateable&gt; &lt;UseMerge&gt;true&lt;/UseMerge&gt; &lt;SingleAssemblyName&gt;B2CWeb_Build&lt;/SingleAssemblyName&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup Condition=&quot; '$(Configuration)|$(Platform)' == 'Release|AnyCPU' &quot;&gt; &lt;DebugSymbols&gt;false&lt;/DebugSymbols&gt; &lt;OutputPath&gt;..\B2CWeb_Deploy\&lt;/OutputPath&gt; &lt;EnableUpdateable&gt;false&lt;/EnableUpdateable&gt; &lt;UseMerge&gt;true&lt;/UseMerge&gt; &lt;SingleAssemblyName&gt;B2C_Web&lt;/SingleAssemblyName&gt; &lt;ContentAssemblyName&gt; &lt;/ContentAssemblyName&gt; &lt;DeleteAppCodeCompiledFiles&gt;false&lt;/DeleteAppCodeCompiledFiles&gt; &lt;/PropertyGroup&gt; &lt;ItemGroup&gt; &lt;/ItemGroup&gt; &lt;Import Project=&quot;$(MSBuildExtensionsPath)\Microsoft\WebDeployment\v9.0\Microsoft.WebDeployment.targets&quot; /&gt; &lt;!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.WebDeployment.targets. &lt;Target Name=&quot;BeforeBuild&quot;&gt; &lt;/Target&gt; &lt;Target Name=&quot;BeforeMerge&quot;&gt; &lt;/Target&gt; &lt;Target Name=&quot;AfterMerge&quot;&gt; &lt;/Target&gt; &lt;Target Name=&quot;AfterBuild&quot;&gt; &lt;/Target&gt; --&gt; &lt;/Project&gt; </code></pre> <p><strong>EDIT</strong></p> <p>After some months this problem disapeared. I haven't had problems for over 1 year now. I guess the issue will strike again when nobody expects it.</p> <p><strong>EDIT 2</strong></p> <p>… for over 2 years now. I am such a lucky dude!</p> <p><strong>EDIT 3</strong></p> <p>I just read <a href="https://devblogs.microsoft.com/aspnet/enabling-the-net-compiler-platform-roslyn-in-asp-net-applications/" rel="nofollow noreferrer">an article on MSDN</a>, and it sounds like the problem I had. I have debugging disabled, but still the compilation was &quot;sometimes wrong&quot;. The behaviour of the old provider could be the issue. But this is just guessing.</p> <blockquote> <p>Very large pages containing long spans of HTML with no server blocks (e.g. &lt;%= %&gt;) can cause a stack overflow when debug compilation is enabled that will crash the application. Note that in our testing it’s taken a page that’s ~4x as large one that would’ve produced a similar issue in the old provider, but in this case it crashes the entire application, whereas with the old provider it just fails the offending page</p> </blockquote>
0
1,994
Spring could not autowire field error
<p>I am getting below error for my spring based dynamic web project.I am new to spring and I am no sure why the below error is there -</p> <pre><code>org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.persistent.eap.dao.UserRegistrationDetailsDao com.persistent.eap.service.impl.UserRegistrationServiceImpl.userRegistrationDetailsDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationDetailsDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0 </code></pre> <p>below is the trace -</p> <pre><code>HTTP Status 500 - -------------------------------------------------------------------------------- type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619) root cause org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userRegistrationController' defined in file [D:\javawp\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\eapPortal\WEB-INF\classes\com\persistent\eap\controllers\UserRegistrationController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.persistent.eap.service.intfc.UserRegistrationService]: : Error creating bean with name 'userRegistrationService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.persistent.eap.dao.UserRegistrationDetailsDao com.persistent.eap.service.impl.UserRegistrationServiceImpl.userRegistrationDetailsDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationDetailsDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.persistent.eap.dao.UserRegistrationDetailsDao com.persistent.eap.service.impl.UserRegistrationServiceImpl.userRegistrationDetailsDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationDetailsDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127) javax.servlet.GenericServlet.init(GenericServlet.java:212) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619) root cause org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userRegistrationController' defined in file [D:\javawp\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\eapPortal\WEB-INF\classes\com\persistent\eap\controllers\UserRegistrationController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.persistent.eap.service.intfc.UserRegistrationService]: : Error creating bean with name 'userRegistrationService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.persistent.eap.dao.UserRegistrationDetailsDao com.persistent.eap.service.impl.UserRegistrationServiceImpl.userRegistrationDetailsDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationDetailsDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.persistent.eap.dao.UserRegistrationDetailsDao com.persistent.eap.service.impl.UserRegistrationServiceImpl.userRegistrationDetailsDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationDetailsDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0 org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:730) org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075) org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:383) org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:362) org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82) org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58) org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119) org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72) org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73) org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:106) org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:85) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127) javax.servlet.GenericServlet.init(GenericServlet.java:212) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619) root cause org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.persistent.eap.dao.UserRegistrationDetailsDao com.persistent.eap.service.impl.UserRegistrationServiceImpl.userRegistrationDetailsDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationDetailsDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844) org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786) org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703) org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:795) org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723) org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075) org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:383) org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:362) org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82) org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58) org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119) org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72) org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73) org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:106) org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:85) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127) javax.servlet.GenericServlet.init(GenericServlet.java:212) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619) root cause org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.persistent.eap.dao.UserRegistrationDetailsDao com.persistent.eap.service.impl.UserRegistrationServiceImpl.userRegistrationDetailsDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRegistrationDetailsDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84) </code></pre> <p>My dispatcher-servlet.xml looks like this</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"&gt; &lt;context:annotation-config /&gt; &lt;context:spring-configured /&gt; &lt;tx:annotation-driven mode="aspectj"/&gt; &lt;context:load-time-weaver aspectj-weaving="on"/&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&gt; &lt;bean class="com.persistent.eap.validators.UserRegistrationValidator" /&gt; &lt;bean id="userRegistrationService" class="com.persistent.eap.service.impl.UserRegistrationServiceImpl" /&gt; &lt;bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"&gt; &lt;property name="basename" value="messages"/&gt; &lt;/bean&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="viewClass" value="org.springframework.web.servlet.view.JstlView"&gt;&lt;/property&gt; &lt;property name="prefix" value="/WEB-INF/jsps/"&gt;&lt;/property&gt; &lt;property name="suffix" value=".jsp"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;context:component-scan base-package="com.persistent.eap.controllers" /&gt; &lt;context:component-scan base-package="com.persistent.eap.service" /&gt; &lt;context:component-scan base-package="com.persistent.eap.dao" /&gt; &lt;/beans&gt; ..... </code></pre> <p>Thanks in advance!</p>
0
6,869
Swagger declaration schema = @Schema(implementation = Map.class) represents Schema as String in swagger-ui
<p>I am trying to create <code>springdoc</code> swagger documentation, and I would like to represent a request body having data type <code>Map&lt;String, Object&gt;</code> in a better readable way for clients. But when I declare <code>@io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(schema = @Schema(implementation = Map.class)</code> the Schema is coming as <code>String</code>(attached the screenshot below)</p> <p><a href="https://i.stack.imgur.com/8BY0G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8BY0G.png" alt="enter image description here" /></a></p> <p><strong>Method declaration</strong></p> <pre><code> @Operation(security = {@SecurityRequirement(name = &quot;bearer-key&quot;)}, summary = &quot;Create Data&quot;, operationId = &quot;createData&quot;, description = &quot;Create createData for the **`type`**. &quot;) @ApiResponses(value = { @ApiResponse(responseCode = &quot;201&quot;, description = &quot;Data created&quot;, content = @Content(schema = @Schema(implementation = Map.class), examples = {@ExampleObject(value = &quot;{\n&quot; + &quot; \&quot;id\&quot;: \&quot;927d810c-3ac5-4584-ba58-7c11befabf54\&quot;,\n&quot; + &quot;}&quot;)})), @ApiResponse(responseCode = &quot;400&quot;, description = &quot;BAD Request&quot;)}) @PostMapping(value = &quot;/data/type&quot;, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(schema = @Schema(implementation = Map.class), examples = {@ExampleObject(value = &quot;{\n&quot; + &quot; \&quot;label\&quot;:\&quot;tourism\&quot;,\n&quot; + &quot; \&quot;location\&quot;:\&quot;France\&quot;\n&quot; + &quot; }&quot;)})) ResponseEntity&lt;Map&lt;String, Object&gt;&gt; createData(@Parameter(name = &quot;type&quot;, required = true) @PathVariable(&quot;type&quot;) String type, @Parameter(name = &quot;request payload&quot;) @Valid @RequestBody Map&lt;String, Object&gt; body); </code></pre> <p>Though the Spring boot automatically infers the type based on the method signature, it is not clear for the data type <code>Map</code>. For instance, by default, the type Map&lt;String, Object&gt; will be inferred as below <a href="https://i.stack.imgur.com/4MJf1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4MJf1.png" alt="enter image description here" /></a></p> <p>But I would like to show the Schema in a more understandable way for the client who refers to my API. I could see there is a closed ticket without a proper solution in <a href="https://github.com/swagger-api/swagger-core/issues/3439" rel="nofollow noreferrer">Github</a>. As per my requirement, the request body should be a type agnostic and dynamic key-value pairs, so there is no other way apart from receiving the request as <code>Map&lt;String, Object&gt;</code>. has anyone implemented a better way with type <code>Map</code> rather than creating a custom request/response model?</p>
0
1,277
Bootstrap columns not aligning correctly
<p>I've built a layout using Bootstrap 3, and I have the following problem: I have a news section that is set to display a total of 9 news items, 3 on each row, summing 3 rows. However, they don't seem to align properly. Please see the picture below.</p> <p><img src="https://i.stack.imgur.com/stwx4.png" alt="Columns not aligning correctly"></p> <p>The html:</p> <pre><code> &lt;div class="row"&gt; &lt;div class="col-md-12 small-article-container"&gt;&lt;!-- Small articles container --&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;asdasds: CELE MAI AŞTEPTATE TITLURI ALE LUI 2014&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;AMENINŢĂRI CU MOARTEA ee df PENTRU PREŞEDI as HOLLANDE&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;AMENINŢĂRI CU MOARTEA PENTRU PREŞEDINTELE HOLLANDE&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;asdasds: CELE MAI AŞTEPTATE TITLURI ALE LUI 2014&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;AMENINŢĂRI CU MOARTEA ee df PENTRU PREŞEDI as HOLLANDE&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;AMENINŢĂRI CU MOARTEA PENTRU PREŞEDINTELE HOLLANDE&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;asdasds: CELE MAI AŞTEPTATE TITLURI ALE LUI 2014&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;AMENINŢĂRI CU MOARTEA ee df PENTRU PREŞEDI as HOLLANDE&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 small-article"&gt;&lt;!-- Start small article --&gt; &lt;div class="col-md-12 small-category"&gt; &lt;strong&gt;&lt;a href="#"&gt;Stil de viata&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-img"&gt; &lt;a href="#"&gt;&lt;img src="images/MH-370-200x130.jpg" width="253" height="164" alt="Small article picture" class="img-responsive"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-article-date"&gt; astăzi, 14:08 &lt;/div&gt; &lt;div class="col-md-12 small-title"&gt; &lt;a href="#"&gt;&lt;strong&gt;AMENINŢĂRI CU MOARTEA PENTRU PREŞEDINTELE HOLLANDE&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-12 small-excerpt"&gt; În articolul publicat luni în Financial Times, liderul spiritual turc Fethullah Gülen arată care este... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-12 more-news"&gt; &lt;a href="#"&gt;MAI MULTE stiri&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The css:</p> <pre><code>.small-article-container { margin-top: 1em; } .small-article { /* padding: 0; */ margin-bottom: 1em; padding-right: 0.5em; padding-left: 0.5em; /* float: right; */} .small-category { padding: 0; font-size: 0.9em; } .small-article-img { padding: 0; width: 100%; } .small-article-date { padding: 0; padding-top: 0.5em; font-size: 0.9em; color: #545454; } .small-title { padding: 0; line-height: 1.3em; font-size: 1em; text-transform: uppercase; } .small-excerpt { padding: 0; font-size: 0.9em; } </code></pre> <p>Could anyone please hep me out on this ? I'm having nightmares about it. Thanks.</p>
0
6,463
Angular mat-paginator page size not working correctly
<p>I have created a mat-paginator element for a mat-table. My issue is that the paginator is not correctly displaying the page size. It will display all the results on one page, despite the page size being 5.Here I am making a request to an API to get a list of transactions, then adding them to a list to be displayed in the table. I have tried all the possible solutions I have found with no success.</p> <pre><code>export class txns implements OnInit { ELEMENT_DATA: ISalesOrders[] = []; displayedColumns = ['type', 'source', 'amount']; panelOpenState: boolean = false; expandedElement: any; dataSource = new MatExpandTableDataSource(this.ELEMENT_DATA); config:any; //App Configuration errorLoading:boolean = false; doneLoading:boolean = false; @ViewChild('paginator') paginator: MatPaginator;//Creates horizontal link with paginator isExpansionDetailRow = (i: number, row: Object) =&gt; row.hasOwnProperty('detailRow');//Determines whether the the row is expandable. /** * Similar to constructor, NgINIT will wait until components dependencies are loaded. */ ngOnInit() { this.getMonthlySalesTransactions(3).subscribe(data =&gt; { console.log(data); data.forEach((data) =&gt; { if(data.result === 0) { let results = data.objs as ISalesOrders[]; results.forEach(elem =&gt; { this.ELEMENT_DATA.push(elem); }); } else { this.errorLoading = false; } this.doneLoading = true; }); this.dataSource = new MatExpandTableDataSource(this.ELEMENT_DATA); this.dataSource.paginator = this.paginator; }); } </code></pre> <p>And the html template:</p> <pre><code>&lt;div class="example-container mat-elevation-z8"&gt; &lt;p&gt;{{ 'desc.recent-txns' | translate }}&lt;/p&gt; &lt;mat-progress-bar mode="indeterminate" *ngIf="!doneLoading"&gt;&lt;/mat-progress-bar&gt; &lt;h1 *ngIf="doneLoading &amp;&amp; ELEMENT_DATA.length == 0"&gt;{{ 'no-transactions' }}&lt;/h1&gt; &lt;mat-table #table [dataSource]="dataSource" *ngIf="ELEMENT_DATA.length != 0"&gt; &lt;!-- Position Column --&gt; &lt;ng-container matColumnDef="type"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; {{ 'transaction-type' | translate }} &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{ element.Brand_Group }} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;!-- Name Column --&gt; &lt;ng-container matColumnDef="source"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; {{ 'source' | translate }} &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{ element.Source_Account_Name }} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;!-- Weight Column --&gt; &lt;ng-container matColumnDef="amount"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; {{ 'amount' | translate }} &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{ element.Original_Amount | currency:config.currencyCode}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;ng-container matColumnDef="expandedDetail"&gt; &lt;mat-cell *matCellDef="let detail"&gt; {{ 'transaction-id' | translate }}: {{ detail.element.Transaction_ID }} &lt;br&gt; {{ 'timestamp' | translate }}: {{ detail.element.Transaction_Time | date }} &lt;br&gt; {{ 'status' | translate }}: {{ detail.element.Status }} &lt;br&gt; {{ 'source-fees' | translate }}: {{ detail.element.Source_Fees_1 | currency:config.currencyCode }} &lt;br&gt; &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;mat-header-row *matHeaderRowDef="displayedColumns"&gt;&lt;/mat-header-row&gt; &lt;mat-row *matRowDef="let row; columns: displayedColumns;" matRipple class="element-row" [class.expanded]="expandedElement == row" (click)="expandedElement = row"&gt;&lt;/mat-row&gt; &lt;mat-row *matRowDef="let row; columns: ['expandedDetail']; when: isExpansionDetailRow" [@detailExpand]="row.element == expandedElement ? 'expanded' : 'collapsed'" style="overflow: hidden"&gt; &lt;/mat-row&gt; &lt;/mat-table&gt; &lt;mat-paginator #paginator [pageSize]="10" [pageSizeOptions]="[5, 10, 20]" [showFirstLastButtons]="true"&gt; &lt;/mat-paginator&gt; </code></pre> <p></p> <p>Result:</p> <p><a href="https://imgur.com/a/5WS0i4m" rel="noreferrer">https://imgur.com/a/5WS0i4m</a></p> <p>but I only want 5 elements per page. any help is appreciated</p> <p>i also want to have the ability to expand rows on click, so I created MatExpandTableDataSource class to let me do this. I believe this is were the problem is happening. If I switch to use MatTableDataSource it works, but it does not work properly when using this class.</p> <p>`</p> <pre><code>export class MatExpandTableDataSource extends MatTableDataSource&lt;any&gt; { /** Connect function called by the table to retrieve one stream containing the data to render. */ ELEMENT_DATA: ISalesOrders[]; /** * Constructor for ExpandableTableDataSource * @param ELEMENT_DATA */ constructor(ELEMENT_DATA: ISalesOrders[]) { super(); this.ELEMENT_DATA = ELEMENT_DATA; } /** * Returns list of details listed inside expandable item * @returns {any} Observable&lt;Element[]&gt; */ connect(): any { const rows:any = []; this.ELEMENT_DATA.forEach(element =&gt; rows.push(element, { detailRow: true, element })); return of(rows); } disconnect() { } </code></pre> <p>}</p>
0
2,427
Javascript Sockets (failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET)
<p>I am trying to create a simple program to send a message to a socket in plain text. The sender is a webpage in javascript using websocket and the server is a C program. I don't have any control over the C code but I have been assured by the codes owners that I can use simple javascript to send the message. My code is as follows:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; //initialize the websocket ws var ws; //Open the socket connection function openSock() { //test for Websocket compatibility in the browser if ("WebSocket" in window) { // log socket attempt console.log("Attempting to open socket!"); //open web socket ws ws = new WebSocket("ws://192.168.6.222:11000/echo"); } else { // else the browser doesn't support WebSocket //Websocket is not supported alert("APS NOT supported by your Browser!"); } } //send the command to socket ws function sendCommand() { console.log("Attempting to Send Message"); ws.send("your message here"); } //close the socket ws function closeSock() { console.log("Closing Socket"); // close socket ws ws.close(); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="sse"&gt; &lt;a href="javascript:openSock()"&gt;&lt;input type=submit value="open"&gt;&lt;/a&gt; &lt;a href="javascript:sendCommand()"&gt;&lt;input type=submit value="send"&gt;&lt;/a&gt; &lt;a href="javascript:closeSock()"&gt;&lt;input type=submit value="close"&gt;&lt;/a&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When I click the connect button I get this error:</p> <blockquote> <p>WebSocket connection to 'ws://192.168.6.222:11000/echo' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET</p> </blockquote> <p>I have checked the firewall and the port seems to be open. After spending a fair amount of time troubleshooting the server (making sure it is running and on the network, etc.) I am wondering if I did something wrong with this client side code. </p> <p>From my limited knowledge and the reading I have done this looks correct but any help is welcome.</p>
0
1,158
Vagrant: PHP7.0-fpm.service failed because the control process exited with error code
<p>I have a new ubuntu/xenial64 box based Vagrant installation. Unfortunately the PHP7.0 service does not running</p> <p>If I running the following <code>systemctl status php7.0-fpm.service</code> command this will be the result:</p> <pre><code>ubuntu@Project-Yii-Shop:~$ systemctl status php7.0-fpm.service * php7.0-fpm.service - The PHP 7.0 FastCGI Process Manager Loaded: loaded (/lib/systemd/system/php7.0-fpm.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2017-01-29 14:37:05 UTC; 16min ago Process: 2213 ExecStart=/usr/sbin/php-fpm7.0 --nodaemonize --fpm-config /etc/php/7.0/fpm/php-fpm.conf (code=exited, s Process: 2203 ExecStartPre=/usr/lib/php/php7.0-fpm-checkconf (code=exited, status=0/SUCCESS) Main PID: 2213 (code=exited, status=78) Jan 29 14:37:04 Project-Yii-Shop systemd[1]: Stopped The PHP 7.0 FastCGI Process Manager. Jan 29 14:37:04 Project-Yii-Shop systemd[1]: Starting The PHP 7.0 FastCGI Process Manager... Jan 29 14:37:05 Project-Yii-Shop php-fpm7.0[2213]: [29-Jan-2017 14:37:05] ERROR: [pool www] cannot get uid for user 'va Jan 29 14:37:05 Project-Yii-Shop php-fpm7.0[2213]: [29-Jan-2017 14:37:05] ERROR: FPM initialization failed Jan 29 14:37:05 Project-Yii-Shop systemd[1]: php7.0-fpm.service: Main process exited, code=exited, status=78/n/a Jan 29 14:37:05 Project-Yii-Shop systemd[1]: Failed to start The PHP 7.0 FastCGI Process Manager. Jan 29 14:37:05 Project-Yii-Shop systemd[1]: php7.0-fpm.service: Unit entered failed state. Jan 29 14:37:05 Project-Yii-Shop systemd[1]: php7.0-fpm.service: Failed with result 'exit-code'. </code></pre> <p>The main problem that I tried to enable this service but the Vagrant Ubuntu ask for password and well, this Ubuntu in the Vagrant does not have any password. I googled on this problem but I saw this solution only and the above one.</p> <pre><code>ubuntu@Project-Yii-Shop:~$ systemctl enable php-fpm.service ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-unit-files === Authentication is required to manage system service or unit files. Authenticating as: Ubuntu (ubuntu) Password: polkit-agent-helper-1: pam_authenticate failed: Authentication failure ==== AUTHENTICATION FAILED === Failed to execute operation: Access denied </code></pre> <p>So I do not know what I should do, because if I install PHP7.0 on a real Ubuntu server (not in Vagrant) I do not get this error.</p> <p>I use NGINX server with the following config:</p> <pre><code>location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #fastcgi_pass 127.0.0.1:9000; fastcgi_pass unix:/var/run/php7.0-fpm.sock; try_files $uri =404; } </code></pre> <p>I use this command in the Vagrant file to install PHP7.0</p> <pre><code>apt-get install -y git nginx php7.0-curl php7.0-cli php7.0-intl php7.0-mbstring php7.0-gd php-imagick php7.0-fpm php7.0-mysql php7.0-pgsql php7.0-xml php7.0-zip </code></pre> <p>And this command run after the Vagrant is up in order to run php7.0 srevice.</p> <pre><code>service php7.0-fpm restart </code></pre> <p>Does anybody see any mistake?</p>
0
1,184
java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
<p>I am having an issue with arrays. The full stack trace is: </p> <pre><code>java.lang.IndexOutOfBoundsException: Index: 5, Size: 5 at java.util.ArrayList.rangeCheck(Unknown Source) ~[?:1.7.0_79] at java.util.ArrayList.get(Unknown Source) ~[?:1.7.0_79] at xyz.lexium.brocubes.drops.DropDB.getRandomDrop(DropDB.java:17) ~[DropDB.class:?] at xyz.lexium.brocubes.blocks.BroBlock.onBlockDestroyedByPlayer(BroBlock.java:33) ~[BroBlock.class:?] at net.minecraft.client.multiplayer.PlayerControllerMP.onPlayerDestroyBlock(PlayerControllerMP.java:187) ~[PlayerControllerMP.class:?] at net.minecraft.client.multiplayer.PlayerControllerMP.func_178891_a(PlayerControllerMP.java:68) ~[PlayerControllerMP.class:?] at net.minecraft.client.multiplayer.PlayerControllerMP.func_180511_b(PlayerControllerMP.java:232) ~[PlayerControllerMP.class:?] at net.minecraft.client.Minecraft.clickMouse(Minecraft.java:1519) ~[Minecraft.class:?] at net.minecraft.client.Minecraft.runTick(Minecraft.java:2126) ~[Minecraft.class:?] at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:1087) ~[Minecraft.class:?] at net.minecraft.client.Minecraft.run(Minecraft.java:376) [Minecraft.class:?] at net.minecraft.client.main.Main.main(Main.java:117) [Main.class:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_79] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79] at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.7.0_79] at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) [launchwrapper-1.12.jar:?] at net.minecraft.launchwrapper.Launch.main(Launch.java:28) [launchwrapper-1.12.jar:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_79] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79] at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.7.0_79] at net.minecraftforge.gradle.GradleStartCommon.launch(Unknown Source) [start/:?] at GradleStart.main(Unknown Source) [start/:?] </code></pre> <p>The code I use for this is:</p> <pre><code>DropBase drop = DropDB.getRandomDrop(); for (int i = 1; i &lt; drop.getDrops().size() -1; i++) { EntityItem item = new EntityItem(worldIn, pos.getX(), pos.getY() + 1, pos.getZ(), drop.getDrops().get(i)); System.out.println(i); worldIn.spawnEntityInWorld(item); </code></pre> <p>This code calls DropDB and selects a random drop from a registered list. The list is perfectly fine. Here is the code for getDrop is:</p> <pre><code> public static DropBase getRandomDrop() { Random rand = new Random(); int n = rand.nextInt(drops.size()) + 1; System.out.println(n); System.out.println(drops.size()); return drops.get(n); } </code></pre> <p>This code causes this error. I have tired to look at the other questions around here. They <em>have not</em> worked. </p>
0
1,162
JMeter distributed server not sending results back to master server
<p>Issue: Remote Jmeter server is not reporting back the results to the master server.</p> <p>Description: Using a VMware server I have added several Ubuntu servers hosting various JMeter client/servers. I have setup a very simple distributed Jmeter environment using one master and one remote slave. I have a very simple test plan that uses FTP to transfer a single file to a third FTP server.</p> <p>Jmeter Master: 192.168.19.219, Ubuntu 12.04, Java 1.7.0.51, Jmeter 2.11 Jmeter Slave: 192.168.19.201, Ubuntu 12.04, Java 1.7.0.51, Jmeter 2.11 FTP Server 192.168.19.211, Win2008 R2</p> <p>Upon execution the test plan works correctly and the file gets uploaded and downloaded successfully to and from the FTP server. Whats not working are the results. Using wireshark I determined that no results were being sent back to the master server. I then checked the jmeter-server.log and noticed some errors complaining about java.rmi.ConnectException. Its trying to use 127.0.0.1 which is obviously not the correct address. I read up and found to correct this you must set the param "java.rmi.server.hostname". </p> <p>So on the slave server I edited the jmeter-server config file to the IP address of the slave server: RMI_HOST_DEF=-Djava.rmi.server.hostname=192.168.19.201 </p> <p>The jmeter-server.log (attached) shows the java.rmi.server.hostname being picked up so I cannot figure out why further down in the jmeter-server.log its complaining about 127.0.0.1? Where is 127.0.0.1 coming from? Why is RMI not using 192.168.19.201?</p> <p>Jmeter-server.log:</p> <pre><code>2014/04/24 14:22:02 INFO - jmeter.util.JMeterUtils: Setting Locale to en_US 2014/04/24 14:22:02 INFO - jmeter.JMeter: Loading user properties from: /home/tester/apache-jmeter-2.11/bin/user.properties 2014/04/24 14:22:02 INFO - jmeter.JMeter: Loading system properties from: /home/tester/apache-jmeter-2.11/bin/system.properties 2014/04/24 14:22:02 INFO - jmeter.JMeter: Setting System property: java.rmi.server.hostname=192.168.19.201 2014/04/24 14:22:02 INFO - jmeter.JMeter: Setting System property: server_port=1099 2014/04/24 14:22:02 INFO - jmeter.JMeter: Copyright (c) 1998-2014 The Apache Software Foundation 2014/04/24 14:22:02 INFO - jmeter.JMeter: Version 2.11 r1554548 2014/04/24 14:22:02 INFO - jmeter.JMeter: java.version=1.7.0_51 2014/04/24 14:22:02 INFO - jmeter.JMeter: java.vm.name=OpenJDK Server VM 2014/04/24 14:22:02 INFO - jmeter.JMeter: os.name=Linux 2014/04/24 14:22:02 INFO - jmeter.JMeter: os.arch=i386 2014/04/24 14:22:02 INFO - jmeter.JMeter: os.version=3.2.0-60-generic 2014/04/24 14:22:02 INFO - jmeter.JMeter: file.encoding=UTF-8 2014/04/24 14:22:02 INFO - jmeter.JMeter: Default Locale=English (United States) 2014/04/24 14:22:02 INFO - jmeter.JMeter: JMeter Locale=English (United States) 2014/04/24 14:22:02 INFO - jmeter.JMeter: JMeterHome=/home/tester/apache-jmeter-2.11 2014/04/24 14:22:02 INFO - jmeter.JMeter: user.dir =/home/tester/apache-jmeter-2.11/bin 2014/04/24 14:22:02 INFO - jmeter.JMeter: PWD =/home/tester/apache-jmeter-2.11/bin 2014/04/24 14:22:02 INFO - jmeter.JMeter: IP: 127.0.0.1 Name: LoadRunner2 FullName: localhost 2014/04/24 14:22:02 INFO - jmeter.engine.RemoteJMeterEngineImpl: Starting backing engine on 1099 2014/04/24 14:22:02 INFO - jmeter.engine.RemoteJMeterEngineImpl: Local IP address=192.168.19.201 2014/04/24 14:22:02 INFO - jmeter.engine.RemoteJMeterEngineImpl: IP address is a site-local address; this may cause problems with remote access. Can be overridden by defining the system property 'java.rmi.server.hostname' - see jmeter-server script file 2014/04/24 14:22:02 INFO - jmeter.engine.RemoteJMeterEngineImpl: Creating RMI registry (server.rmi.create=true) 2014/04/24 14:22:02 INFO - jmeter.engine.RemoteJMeterEngineImpl: Bound to registry on port 1099 2014/04/24 14:25:15 WARN - jmeter.engine.RemoteJMeterEngineImpl: Backing engine is null, ignoring reset 2014/04/24 14:25:15 INFO - jmeter.samplers.SampleEvent: List of sample_variables: [] 2014/04/24 14:25:15 INFO - jmeter.samplers.BatchSampleSender: Using batching for this run. Thresholds: num=100, time=60000 2014/04/24 14:25:15 INFO - jmeter.samplers.DataStrippingSampleSender: Using DataStrippingSampleSender for this run 2014/04/24 14:25:15 INFO - jmeter.samplers.BatchSampleSender: Using batching for this run. Thresholds: num=100, time=60000 2014/04/24 14:25:15 INFO - jmeter.samplers.DataStrippingSampleSender: Using DataStrippingSampleSender for this run 2014/04/24 14:25:15 INFO - jmeter.samplers.BatchSampleSender: Using batching for this run. Thresholds: num=100, time=60000 2014/04/24 14:25:15 INFO - jmeter.samplers.DataStrippingSampleSender: Using DataStrippingSampleSender for this run 2014/04/24 14:25:15 INFO - jmeter.engine.RemoteJMeterEngineImpl: Creating JMeter engine on host 192.168.19.201 base '.' 2014/04/24 14:25:15 INFO - jmeter.engine.RemoteJMeterEngineImpl: Remote client host: 192.168.19.219 2014/04/24 14:25:15 INFO - jmeter.engine.StandardJMeterEngine: Listeners will be started after enabling running version 2014/04/24 14:25:15 INFO - jmeter.engine.StandardJMeterEngine: To revert to the earlier behaviour, define jmeterengine.startlistenerslater=false 2014/04/24 14:25:15 INFO - jmeter.services.FileServer: Default base='/home/tester/apache-jmeter-2.11/bin' 2014/04/24 14:25:15 INFO - jmeter.services.FileServer: Set new base='.' 2014/04/24 14:25:15 INFO - jmeter.engine.StandardJMeterEngine: Applying properties {} 2014/04/24 14:25:15 INFO - jmeter.engine.RemoteJMeterEngineImpl: Running test 2014/04/24 14:25:15 INFO - jmeter.engine.StandardJMeterEngine: Running the test! 2014/04/24 14:25:15 INFO - jmeter.samplers.SampleEvent: List of sample_variables: [] 2014/04/24 14:25:15 INFO - jmeter.engine.util.CompoundVariable: Note: Function class names must contain the string: '.functions.' 2014/04/24 14:25:15 INFO - jmeter.engine.util.CompoundVariable: Note: Function class names must not contain the string: '.gui.' 2014/04/24 14:25:16 ERROR - jmeter.samplers.RemoteListenerWrapper: testStarted(host) java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129) at org.apache.jmeter.samplers.RemoteSampleListenerImpl_Stub.testStarted(Unknown Source) at org.apache.jmeter.samplers.RemoteListenerWrapper.testStarted(RemoteListenerWrapper.java:85) at org.apache.jmeter.engine.StandardJMeterEngine.notifyTestListenersOfStart(StandardJMeterEngine.java:216) at org.apache.jmeter.engine.StandardJMeterEngine.run(StandardJMeterEngine.java:336) at java.lang.Thread.run(Thread.java:744) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.&lt;init&gt;(Socket.java:425) at java.net.Socket.&lt;init&gt;(Socket.java:208) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) ... 8 more 2014/04/24 14:25:16 ERROR - jmeter.samplers.RemoteListenerWrapper: testStarted(host) java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129) at org.apache.jmeter.samplers.RemoteSampleListenerImpl_Stub.testStarted(Unknown Source) at org.apache.jmeter.samplers.RemoteListenerWrapper.testStarted(RemoteListenerWrapper.java:85) at org.apache.jmeter.engine.StandardJMeterEngine.notifyTestListenersOfStart(StandardJMeterEngine.java:216) at org.apache.jmeter.engine.StandardJMeterEngine.run(StandardJMeterEngine.java:336) at java.lang.Thread.run(Thread.java:744) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.&lt;init&gt;(Socket.java:425) at java.net.Socket.&lt;init&gt;(Socket.java:208) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) ... 8 more 2014/04/24 14:25:16 ERROR - jmeter.samplers.RemoteListenerWrapper: testStarted(host) java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129) at org.apache.jmeter.samplers.RemoteSampleListenerImpl_Stub.testStarted(Unknown Source) at org.apache.jmeter.samplers.RemoteListenerWrapper.testStarted(RemoteListenerWrapper.java:85) at org.apache.jmeter.engine.StandardJMeterEngine.notifyTestListenersOfStart(StandardJMeterEngine.java:216) at org.apache.jmeter.engine.StandardJMeterEngine.run(StandardJMeterEngine.java:336) at java.lang.Thread.run(Thread.java:744) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.&lt;init&gt;(Socket.java:425) at java.net.Socket.&lt;init&gt;(Socket.java:208) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) ... 8 more 2014/04/24 14:25:16 ERROR - jmeter.samplers.RemoteTestListenerWrapper: java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129) at org.apache.jmeter.samplers.RemoteSampleListenerImpl_Stub.testStarted(Unknown Source) at org.apache.jmeter.samplers.RemoteTestListenerWrapper.testStarted(RemoteTestListenerWrapper.java:70) at org.apache.jmeter.engine.StandardJMeterEngine.notifyTestListenersOfStart(StandardJMeterEngine.java:216) at org.apache.jmeter.engine.StandardJMeterEngine.run(StandardJMeterEngine.java:336) at java.lang.Thread.run(Thread.java:744) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.&lt;init&gt;(Socket.java:425) at java.net.Socket.&lt;init&gt;(Socket.java:208) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) ... 8 more 2014/04/24 14:25:16 INFO - jmeter.engine.StandardJMeterEngine: Starting ThreadGroup: 1 : FTP Thread Group 2014/04/24 14:25:16 INFO - jmeter.engine.StandardJMeterEngine: Starting 1 threads for group FTP Thread Group. 2014/04/24 14:25:16 INFO - jmeter.engine.StandardJMeterEngine: Thread will continue on error 2014/04/24 14:25:16 INFO - jmeter.threads.ThreadGroup: Starting thread group number 1 threads 1 ramp-up 0 perThread 0.0 delayedStart=false 2014/04/24 14:25:16 INFO - jmeter.threads.JMeterThread: jmeterthread.startearlier=true (see jmeter.properties) 2014/04/24 14:25:16 INFO - jmeter.threads.JMeterThread: Running PostProcessors in forward order 2014/04/24 14:25:16 INFO - jmeter.threads.ThreadGroup: Started thread group number 1 2014/04/24 14:25:16 INFO - jmeter.engine.StandardJMeterEngine: All thread groups have been started 2014/04/24 14:25:16 INFO - jmeter.threads.JMeterThread: Thread started: FTP Thread Group 1-1 2014/04/24 14:25:16 ERROR - jmeter.threads.RemoteThreadsListenerWrapper: java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129) at org.apache.jmeter.threads.RemoteThreadsListenerImpl_Stub.threadStarted(Unknown Source) at org.apache.jmeter.threads.RemoteThreadsListenerWrapper.threadStarted(RemoteThreadsListenerWrapper.java:52) at org.apache.jmeter.threads.JMeterThread$ThreadListenerTraverser.addNode(JMeterThread.java:597) at org.apache.jorphan.collections.HashTree.traverseInto(HashTree.java:961) at org.apache.jorphan.collections.HashTree.traverse(HashTree.java:946) at org.apache.jmeter.threads.JMeterThread.threadStarted(JMeterThread.java:566) at org.apache.jmeter.threads.JMeterThread.initRun(JMeterThread.java:554) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:253) at java.lang.Thread.run(Thread.java:744) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.&lt;init&gt;(Socket.java:425) at java.net.Socket.&lt;init&gt;(Socket.java:208) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) ... 12 more 2014/04/24 14:25:16 INFO - jmeter.samplers.SampleResult: Note: Sample TimeStamps are START times 2014/04/24 14:25:16 INFO - jmeter.samplers.SampleResult: sampleresult.default.encoding is set to ISO-8859-1 2014/04/24 14:25:16 INFO - jmeter.samplers.SampleResult: sampleresult.useNanoTime=true 2014/04/24 14:25:16 INFO - jmeter.samplers.SampleResult: sampleresult.nanoThreadSleep=5000 2014/04/24 14:25:17 ERROR - jmeter.samplers.BatchSampleSender: sampleOccurred java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129) at org.apache.jmeter.samplers.RemoteSampleListenerImpl_Stub.processBatch(Unknown Source) at org.apache.jmeter.samplers.BatchSampleSender.sampleOccurred(BatchSampleSender.java:184) at org.apache.jmeter.samplers.DataStrippingSampleSender.sampleOccurred(DataStrippingSampleSender.java:92) at org.apache.jmeter.samplers.RemoteListenerWrapper.sampleOccurred(RemoteListenerWrapper.java:104) at org.apache.jmeter.threads.ListenerNotifier.notifyListeners(ListenerNotifier.java:84) at org.apache.jmeter.threads.JMeterThread.notifyListeners(JMeterThread.java:783) at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:443) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:257) at java.lang.Thread.run(Thread.java:744) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.&lt;init&gt;(Socket.java:425) at java.net.Socket.&lt;init&gt;(Socket.java:208) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) ... 12 more 2014/04/24 14:25:17 ERROR - jmeter.samplers.BatchSampleSender: sampleOccurred java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129) at org.apache.jmeter.samplers.RemoteSampleListenerImpl_Stub.processBatch(Unknown Source) at org.apache.jmeter.samplers.BatchSampleSender.sampleOccurred(BatchSampleSender.java:184) at org.apache.jmeter.samplers.DataStrippingSampleSender.sampleOccurred(DataStrippingSampleSender.java:92) at org.apache.jmeter.samplers.RemoteListenerWrapper.sampleOccurred(RemoteListenerWrapper.java:104) at org.apache.jmeter.threads.ListenerNotifier.notifyListeners(ListenerNotifier.java:84) at org.apache.jmeter.threads.JMeterThread.notifyListeners(JMeterThread.java:783) at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:443) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:257) at java.lang.Thread.run(Thread.java:744) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.&lt;init&gt;(Socket.java:425) at java.net.Socket.&lt;init&gt;(Socket.java:208) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) ... 12 more </code></pre>
0
7,246
Why I received an Error 403 with MockMvc and JUnit?
<p>I have a spring mvc (3.2.5) application with spring security (3.2). </p> <p>I configured my SecurityConfig.class with this method : </p> <pre><code>@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/*").permitAll().and() .formLogin().successHandler(successHandler) .defaultSuccessUrl("/") .failureHandler(failureHandler).failureUrl("/login?error=true") .permitAll().and().logout() .permitAll(); http.authorizeRequests().antMatchers("/resources/**").permitAll(); http.authorizeRequests().antMatchers("/welcome").permitAll(); http.authorizeRequests().antMatchers("/secure/*").authenticated(); http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated(); } </code></pre> <p>With Spring security (3.2) I have CSRF enabled. I think it is a good idea to let it enabled.</p> <p>My controller SignInController contains 2 methods with params :</p> <p><em>EDIT</em> : adding <code>action=</code> in params </p> <pre><code>@RequestMapping(value = "/signup") public ModelAndView signup() { boolean auth = SecurityContextHolder.getContext().getAuthentication() == null ? false : SecurityContextHolder.getContext().getAuthentication() .isAuthenticated() &amp;&amp; (SecurityContextHolder.getContext() .getAuthentication().getPrincipal() instanceof User); ModelAndView result = null; if (auth) { result = new ModelAndView("redirect:" + "/"); } else { UserForm user = new UserForm(); result = new ModelAndView("registration", "userForm", user); } return result; } @RequestMapping(value = "/register", params = "action=signup") public ModelAndView registration( @ModelAttribute(value = "userForm") @Valid UserForm userForm, BindingResult result, HttpServletRequest request) { if (result.hasErrors()) { return new ModelAndView("registration"); } Member member = profileFacade.registerNewUser(userForm); return new ModelAndView("registration", "member", member); } @RequestMapping(value = "/register", params = "action=cancel") public ModelAndView cancelRegistration() { return new ModelAndView("redirect:" + "/"); } </code></pre> <p>and finally, I have JUnit test :</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebConfiguration.class, JpaConfiguration.class, LoggingConfiguration.class, SecurityConfig.class, DataSourceEmbeddedConfiguration.class, DataSourceMySqlConfig.class, BaseValidatorConfiguration.class }) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) @ActiveProfiles("dev") public class SignInControllerTest { @Autowired private WebApplicationContext webApplicationContext; @Autowired private MockHttpSession session; @Autowired private MockHttpServletRequest request; @Autowired private FilterChainProxy springSecurityFilterChain; private MockMvc mockMvc; @Before public void setUp() throws ServletException { SecurityContextHolderAwareRequestFilter scharf = new SecurityContextHolderAwareRequestFilter(); scharf.afterPropertiesSet(); this.mockMvc = MockMvcBuilders .webAppContextSetup(this.webApplicationContext) .addFilters(springSecurityFilterChain).dispatchOptions(true).build(); SecurityContextHolder.getContext().setAuthentication(null); } @Test public void signup() throws Exception { mockMvc.perform(get("/signup")).andExpect(status().isOk()) .andExpect(model().attributeExists("userForm")); } @Test @Transactional @Rollback(true) public void register() throws Exception { UserForm form = new UserForm(); form.setEmail("email@email.com"); form.setUsername("aokije"); form.setPassword("klo,ksff"); form.setConfirmedPassword("klo,ksff"); mockMvc.perform(post("/register").param("action", "signup")).andExpect(status().isOk()); } } </code></pre> <p><em>EDIT</em> : update mockMvc.perform because it is working fine with <code>http.csrf().disable()</code> in SecurityConfig.class</p> <p>Test <strong><em>signup</em></strong> run perfectly but <strong><em>register</em></strong> return an error 403. I tried a lot of things but I received always this error.</p> <p>When I try <code>http://localhost:8080/register?signup</code> in a browser, it is working fine.</p> <p>_<em>EDIT</em>_</p> <p>Logs : </p> <pre><code>2014-02-13 22:00:14,695 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'permitAll', for org.springframework.security.config.annotation.web.configurers.PermitAllSupport$ExactUrlRequestMatcher@52ee705c 2014-02-13 22:00:14,696 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'permitAll', for org.springframework.security.config.annotation.web.configurers.PermitAllSupport$ExactUrlRequestMatcher@2412d28d 2014-02-13 22:00:14,697 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'permitAll', for org.springframework.security.config.annotation.web.configurers.PermitAllSupport$ExactUrlRequestMatcher@4fbd397b 2014-02-13 22:00:14,697 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'permitAll', for Ant [pattern='/logout'] 2014-02-13 22:00:14,698 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'permitAll', for org.springframework.security.config.annotation.web.configurers.PermitAllSupport$ExactUrlRequestMatcher@1008e323 2014-02-13 22:00:14,699 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'permitAll', for Ant [pattern='/*'] 2014-02-13 22:00:14,700 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'permitAll', for Ant [pattern='/resources/**'] 2014-02-13 22:00:14,700 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'permitAll', for Ant [pattern='/welcome'] 2014-02-13 22:00:14,700 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'authenticated', for Ant [pattern='/secure/*'] 2014-02-13 22:00:14,701 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'hasRole('ROLE_ADMIN')', for Ant [pattern='/admin/**'] 2014-02-13 22:00:14,701 [ExpressionBasedFilterInvocationSecurityMetadataSource] processMap Adding web access control expression 'authenticated', for org.springframework.security.web.util.matcher.AnyRequestMatcher@1 2014-02-13 22:00:14,703 [FilterSecurityInterceptor] afterPropertiesSet Validated configuration attributes 2014-02-13 22:00:14,704 [FilterSecurityInterceptor] afterPropertiesSet Validated configuration attributes 2014-02-13 22:00:14,734 [DefaultSecurityFilterChain] &lt;init&gt; Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@10174779, org.springframework.security.web.context.SecurityContextPersistenceFilter@68736a7e, org.springframework.security.web.header.HeaderWriterFilter@728e5d0d, org.springframework.security.web.csrf.CsrfFilter@6e7a918b, org.springframework.security.web.authentication.logout.LogoutFilter@430e85e7, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@55eda087, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@290c7ca, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@6dd90afc, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@12eb6a0f, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6855612f, org.springframework.security.web.session.SessionManagementFilter@410a11a2, org.springframework.security.web.access.ExceptionTranslationFilter@59e15580, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@2257a0] 2014-02-13 22:00:14,859 [FilterChainProxy] doFilter /register at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' 2014-02-13 22:00:14,863 [FilterChainProxy] doFilter /register at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 2014-02-13 22:00:14,863 [HttpSessionSecurityContextRepository] readSecurityContextFromSession HttpSession returned null object for SPRING_SECURITY_CONTEXT 2014-02-13 22:00:14,863 [HttpSessionSecurityContextRepository] loadContext No SecurityContext was available from the HttpSession: org.springframework.mock.web.MockHttpSession@4c4b529f. A new one will be created. 2014-02-13 22:00:14,864 [FilterChainProxy] doFilter /register at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter' 2014-02-13 22:00:14,865 [HstsHeaderWriter] writeHeaders Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5ab39e58 2014-02-13 22:00:14,865 [FilterChainProxy] doFilter /register at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter' 2014-02-13 22:00:14,866 [CsrfFilter] doFilterInternal Invalid CSRF token found for http://localhost/register 2014-02-13 22:00:14,866 [HttpSessionSecurityContextRepository] saveContext SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 2014-02-13 22:00:14,866 [SecurityContextPersistenceFilter] doFilter SecurityContextHolder now cleared, as request processing completed </code></pre> <p>Could you help me ? </p> <p>Thanks a lot</p> <p><em><strong>EDIT</em></strong></p> <p>Finally, I had a bug in another class (annotation). I fix with this : </p> <pre><code>HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository(); CsrfToken csrfToken = httpSessionCsrfTokenRepository .generateToken(request); Map map = new HashMap(); map.put("userForm", form); map.put("org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN", csrfToken); this.mockMvc .perform( post("/register") .param("signup", "") .param("_csrf", csrfToken.getToken()) .sessionAttrs(map)).andExpect(status().isOk()); </code></pre> <p>Params csrf and sessionAttrs are mandatory. </p>
0
3,982
BootStrap Table text ellipsis can not be with responsive web?
<p>I am trying to implement String ellipsis in the Table tag.</p> <p>The source code is below.</p> <pre><code>&lt;div&gt; &lt;div class="widget-body no-padding" style="min-height:0px;"&gt; &lt;table class="table" style="table-layout: fixed;"&gt; &lt;tbody&gt; &lt;c:forEach var="item" items="${result.stuffList}" varStatus="idx"&gt; &lt;c:if test="${idx.index &lt; 5}"&gt; &lt;tr&gt; &lt;td class='text-center' style="width: 80%; text-overflow:ellipsis; -o-text-overow: ellipsis; word-wrap:normal; overflow: hidden;"&gt; &lt;nobr&gt; &lt;a href="#" onclick="javascript:location.href='/view?nid=${item.id}'"&gt;${item.name}&lt;/a&gt; &lt;/nobr&gt; &lt;/td&gt; &lt;td class='text-center' style="width: 20%;"&gt; ${item.regDate} &lt;/td&gt; &lt;/tr&gt; &lt;/c:if&gt; &lt;/c:forEach&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This code works and if String is too long it shows <code>...</code> what I expected.</p> <p>However, when I test responsive it becomes ugly.</p> <p>I wrote following part to express item registration date.</p> <p>But when browser shrinks, its back part does not showed up in screen. </p> <pre><code>&lt;td class='text-center' style="width: 20%;"&gt; ${item.regDate} &lt;/td&gt; </code></pre> <p>How can I use ellipsis in Bootstrap in all browser?</p> <hr> <p>So it appears like this way</p> <p>What I expected(when shrink browser) >></p> <p>column 1 / column 2</p> <p>AAAA.... / 2014-09-24</p> <p>What now looks like >></p> <p>column 1 / column 2</p> <p>AAAA.... / 2014-09</p> <p>The problem is >> </p> <p>Before I add String ellipsis function it works responsive.</p> <p>My guess >></p> <p>Maybe <code>table-layout: fixed;</code> style is the cause. but do not know how to implements String ellipsis function without <code>table-layout</code>.</p> <p>I hope it becomes more clear than I asked first :D</p> <hr> <p>I have got the cause</p> <p>The problem is width : <code>80%</code>, <code>width: 20%</code>, <code>table-layout:fixed</code>.</p> <p>So when I resize the browser it takes these options for it.</p> <p>But I still do not know how to replace it.</p> <p>All of these are in a div which is small part of the web site and I want responsive web. </p> <hr> <p>Edited after choose an answer.</p> <p>Thanks for answering my question!</p> <p>However I found the cause, but could not fix this.</p> <p>The chosen answer was not relevant, however it was helpful.</p> <p>My problem was not by bootstrap, but width.</p> <p>Even though using responsive web library, </p> <p>can not be responsive if you use width with <code>%</code> or <code>px</code> properties.</p>
0
1,235
Concatenate two audio files and play resulting file
<p>I am really facing problem from last couple of days but I am not able to find the exact solution please help me.</p> <p>I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with <code>SequenceInputStream</code> or byte array but I am not able to get exact result please help me.</p> <p>My code is the following: </p> <pre><code>public class MerginFileHere extends Activity { public ArrayList&lt;String&gt; audNames; byte fileContent[]; byte fileContent1[]; FileInputStream ins,ins1; FileOutputStream fos = null; String combined_file_stored_path = Environment .getExternalStorageDirectory().getPath() + "/AudioRecorder/final.mp3"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); audNames = new ArrayList&lt;String&gt;(); String file1 = Environment.getExternalStorageDirectory().getPath() + "/AudioRecorder/one.mp3"; String file2 = Environment.getExternalStorageDirectory().getPath() + "/AudioRecorder/two.mp3"; File file = new File(Environment.getExternalStorageDirectory() .getPath() + "/AudioRecorder/" + "final.mp3"); try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } audNames.add(file1); audNames.add(file2); Button btn = (Button) findViewById(R.id.clickme); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub createCombineRecFile(); } }); } public void createCombineRecFile() { // String combined_file_stored_path = // File path in String to store // recorded audio try { fos = new FileOutputStream(combined_file_stored_path, true); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { File f = new File(audNames.get(0)); File f1 = new File(audNames.get(1)); Log.i("Record Message", "File Length=========&gt;&gt;&gt;" + f.length()+"-------------&gt;"+f1.length()); fileContent = new byte[(int) f.length()]; ins = new FileInputStream(audNames.get(0)); int r = ins.read(fileContent);// Reads the file content as byte fileContent1 = new byte[(int) f1.length()]; ins1 = new FileInputStream(audNames.get(1)); int r1 = ins1.read(fileContent1);// Reads the file content as byte // from the list. Log.i("Record Message", "Number Of Bytes Readed=====&gt;&gt;&gt;" + r); //fos.write(fileContent1);// Write the byte into the combine file. byte[] combined = new byte[fileContent.length + fileContent1.length]; for (int i = 0; i &lt; combined.length; ++i) { combined[i] = i &lt; fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length]; } fos.write(combined); //fos.write(fileContent1);* } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fos.close(); Log.v("Record Message", "===== Combine File Closed ====="); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre>
0
1,597
Unmarshalling unknown type code
<p>What I am basically trying to do is pass a Parcelable object as an Intent extra.</p> <p>Here is where I pass it,</p> <pre><code>final Intent intent = new Intent(_context, AddReminderActivity.class); final Bundle bundle = new Bundle(); bundle.putString(AddReminderActivity.EXTRA_MODE, AddReminderActivity.MODE_EDIT); bundle.putParcelable(AddReminderActivity.EXTRA_REMINDER, _reminders.get(position)); intent.putExtras(bundle); _context.startActivity(intent); </code></pre> <p><code>_reminders</code> is an <code>ArrayList&lt;Reminder&gt;</code></p> <p>Here is my <code>Reminder</code> class</p> <pre><code>package au.com.elegantmedia.vetcheck.objects; import android.os.Parcel; import android.os.Parcelable; public class Reminder implements Parcelable { private long _id; private String _message = "n/a"; private String _medication = "n/a"; private String _dosage = "n/a"; private String _date = "n/a"; private String _time = "n/a"; private int _repeatID = 0; // 1-once, 2-hourly, 3-daily, 4-weekly, 5-monthly private String _repeat = "n/a"; private int _requestCode = 0; private static int REPEAT_ID_ONCE = 1; private static String REPEAT_ONCE = "once"; private static int REPEAT_ID_HOURLY = 2; private static String REPEAT_HOURLY = "hourly"; private static int REPEAT_ID_DAILY = 3; private static String REPEAT_DAILY = "daily"; private static int REPEAT_ID_WEEKLY = 4; private static String REPEAT_WEEKLY = "weekly"; private static int REPEAT_ID_MONTHLY = 5; private static String REPEAT_MONTHLY = "monthly"; public Reminder() { // TODO Auto-generated constructor stub } public Reminder(Parcel source) { _id = source.readInt(); _message = source.readString(); _medication = source.readString(); _dosage = source.readString(); _date = source.readString(); _time = source.readString(); _repeatID = source.readInt(); _repeat = source.readString(); _requestCode = source.readInt(); } public long getID() { return _id; } public void setID(long id) { _id = id; } public String getMessage() { return _message; } public void setMessage(String message) { if(!message.equals("")) { _message = message; } } public String getMedication() { return _medication; } public void setMedication(String medication) { if(!medication.equals("")) { _medication = medication; } } public String getDosage() { return _dosage; } public void setDosage(String dosage) { if(!dosage.equals("")) { _dosage = dosage; } } public String getDate() { return _date; } public void setDate(String date) { if(!date.equals("")) { _date = date; } } public String getTime() { return _time; } public void setTime(String time) { if(!time.equals("")) { _time = time; } } public void setRepeatID(String repeat) { if(repeat.equals(REPEAT_ONCE)) { _repeatID = REPEAT_ID_ONCE; } else if(repeat.equals(REPEAT_HOURLY)) { _repeatID = REPEAT_ID_HOURLY; } else if(repeat.equals(REPEAT_DAILY)) { _repeatID = REPEAT_ID_DAILY; } else if(repeat.equals(REPEAT_WEEKLY)) { _repeatID = REPEAT_ID_WEEKLY; } else if(repeat.equals(REPEAT_MONTHLY)) { _repeatID = REPEAT_ID_MONTHLY; } } public int getRepeatID() { return _repeatID; } public void setRepeat(int repeatID) { _repeatID = repeatID; if(repeatID == REPEAT_ID_ONCE) { _repeat = REPEAT_ONCE; } else if(repeatID == REPEAT_ID_HOURLY) { _repeat = REPEAT_HOURLY; } else if(repeatID == REPEAT_ID_DAILY) { _repeat = REPEAT_DAILY; } else if(repeatID == REPEAT_ID_WEEKLY) { _repeat = REPEAT_WEEKLY; } else if(repeatID == REPEAT_ID_MONTHLY) { _repeat = REPEAT_MONTHLY; } } public String getRepeat() { return _repeat; } public void setRequestCode(int requestID) { _requestCode = requestID; } public int getRequestCode() { return _requestCode; } // parceling part public static final Parcelable.Creator&lt;Reminder&gt; CREATOR = new Parcelable.Creator&lt;Reminder&gt;() { @Override public Reminder createFromParcel(Parcel source) { return new Reminder(source); } @Override public Reminder[] newArray(int size) { return new Reminder[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(_id); dest.writeString(_message); dest.writeString(_medication); dest.writeString(_dosage); dest.writeString(_date); dest.writeString(_time); dest.writeInt(_repeatID); dest.writeInt(_requestCode); } } </code></pre> <p>The problem I'm having is that when passing the bundle from the caller activity it is like this,</p> <pre><code>Bundle[{reminder=au.com.elegantmedia.vetcheck.objects.Reminder@41fade98, mode=edit}] </code></pre> <p>meaning everything is set as expected, but when trying to access the extras from the callee activity (<code>final Bundle bundle = getIntent().getExtras();</code>) it is as follows,</p> <pre><code>Bundle[mParcelledData.dataSize=308] </code></pre> <p>and at the point I try to access the bundle as follows,</p> <pre><code>if(bundle.getString(EXTRA_MODE).equals(MODE_ADD)) { } else if(bundle.getString(EXTRA_MODE).equals(MODE_EDIT)) { final Reminder reminder = getIntent().getParcelableExtra(EXTRA_REMINDER); populateData(reminder); } </code></pre> <p>I run into the following Exception</p> <pre><code>E/AndroidRuntime(17991): Caused by: java.lang.RuntimeException: Parcel android.os.Parcel@416ee8b0: Unmarshalling unknown type code 6357102 at offset 172 </code></pre> <p>This is my first attempt on Parcelable objects so I have very little idea what this means and Googling for a couple of hours hasn't exactly helped to narrow down the problem.</p>
0
2,913
Could not load file or assembly 'XXXX.dll' or one of its dependencies. The specified module could not be found
<p>I have an application that directly references a dll file: <code>POSLink.dll</code>. </p> <p>In order to get this to run on my local machine, I have to manually copy the following dlls to the output directory: <code>libea32.dll</code> and <code>ssleay32.dll</code>.</p> <p>When I run the application on my local machine, it succeeds.</p> <p>When I run the application on the target machine, I get the following error:</p> <blockquote> <p>Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'POSLink.dll' or one of its dependencies. The specified module could not be found.<br> at FileNotFoundExceptionExample.Program.Main(String[] args)</p> </blockquote> <p>This is my SSCCE</p> <pre><code>using POSLink; using System; namespace FileNotFoundExceptionExample { class Program { static void Main(string[] args) { // this is stuff found in the POSLink namespace var commSetting = new CommSetting(); commSetting.saveFile(); Console.WriteLine("Success"); } } } </code></pre> <p>I tried using <a href="http://www.dependencywalker.com/" rel="nofollow">Dependency Walker</a> on POSLink.dll, but that wasn't very useful to me because there are 381 errors that show up, and they show up when I run it on the successful machine too. </p> <p>How do I even begin troubleshooting this error?</p> <hr> <p>When I run the Fuision log viewer and then run the application on the target machine, I get the following log:</p> <blockquote> <p><strong>* Assembly Binder Log Entry (7/19/2016 @ 2:18:48 PM) *</strong> </p> <p>The operation was successful. Bind result: hr = 0x0. The operation<br> completed successfully. </p> <p>Assembly manager loaded from:<br> C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll Running under<br> executable<br> C:\Users\Omitted\Desktop\notfoundexceptionexample\debug \FileNotFoundExceptionExample.exe<br> --- A detailed error log follows. </p> <p>=== Pre-bind state information === LOG: DisplayName = POSLink, Version=1.0.5773.36725, Culture=neutral,<br> PublicKeyToken=f3876d2e4b7eb819 (Fully-specified) LOG: Appbase =<br> file:///C:/Users/Omitted/Desktop/notfoundexceptionexample/debug/ LOG:<br> Initial PrivatePath = NULL LOG: Dynamic Base = NULL LOG: Cache Base =<br> NULL LOG: AppName = FileNotFoundExceptionExample.exe Calling assembly<br> : FileNotFoundExceptionExample, Version=1.0.0.0, Culture=neutral,<br> PublicKeyToken=null.<br> === LOG: This bind starts in default load context. LOG: Using application configuration file:<br> C:\Users\Omitted\Desktop\notfoundexceptionexample\debug\FileNotFoundExceptionExample.exe.Config<br> LOG: Using host configuration file: LOG: Using machine configuration<br> file from<br> C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.<br> LOG: Post-policy reference: POSLink, Version=1.0.5773.36725,<br> Culture=neutral, PublicKeyToken=f3876d2e4b7eb819 LOG: GAC Lookup was<br> unsuccessful. LOG: Attempting download of new URL<br> file:///C:/Users/Omitted/Desktop/notfoundexceptionexample/debug/POSLink.DLL.<br> LOG: Assembly download was successful. Attempting setup of file:<br> C:\Users\Omitted\Desktop\notfoundexceptionexample\debug\POSLink.dll<br> LOG: Entering run-from-source setup phase. LOG: Assembly Name is:<br> POSLink, Version=1.0.5773.36725, Culture=neutral,<br> PublicKeyToken=f3876d2e4b7eb819 LOG: Binding succeeds. Returns<br> assembly from<br> C:\Users\Omitted\Desktop\notfoundexceptionexample\debug\POSLink.dll.<br> LOG: Assembly is loaded in default load context. </p> </blockquote>
0
1,283
Change spinner style in toolbar
<p>I am trying to put a spinner in my <code>Toolbar</code> like the old ActionBar style navigation and my theme is this</p> <pre><code>&lt;style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;item name="colorPrimary"&gt;@color/color_primary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/color_primary_dark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/color_primary&lt;/item&gt; &lt;/style&gt; </code></pre> <p>but my spinner is black while all other icons and overflow menus are white so it looks bad</p> <p><img src="https://i.stack.imgur.com/4ROO4.png" alt="enter image description here"></p> <p>I tried changing the style of the spinner using this</p> <pre><code>&lt;style name="ToolbarSpinnerTheme" parent="Theme.AppCompat"&gt; &lt;item name="android:spinnerItemStyle"&gt;@style/TextAppearanceSpinnerItem&lt;/item&gt; &lt;/style&gt; &lt;style name="TextAppearanceSpinnerItem"&gt; &lt;item name="android:textColor"&gt;#FFFFFF&lt;/item&gt; &lt;/style&gt; </code></pre> <p>this is how my Toolbar is styled</p> <pre><code>&lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?attr/actionBarSize" android:background="?attr/colorPrimary" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light"&gt; &lt;Spinner android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/modes" android:minWidth="150dp" android:gravity="bottom" style="@style/ToolbarSpinnerTheme"/&gt; &lt;/android.support.v7.widget.Toolbar&gt; final Spinner mode = (Spinner)findViewById(R.id.modes); SpinnerAdapter mSpinner = ArrayAdapter.createFromResource(this, R.array.action_bar_spinner, android.R.layout.simple_spinner_dropdown_item); mode.setAdapter(mSpinner); </code></pre> <p>but it always stays black. How can I change the spinner arrow and text to white while still keeping the same theme for the dropdown style as you would get with the <code>Light</code> theme?</p> <p><strong>Update 4.4 arrow fix:</strong> </p> <p>The only way I got the arrow to turn white is to add the spinner programatically and not in xml so it looks something like this</p> <pre><code>final ArrayAdapter spinnerAdapter = ArrayAdapter.createFromResource(getSupportActionBar().getThemedContext(), R.array.main_navigation_list, R.layout.spinner_text); spinnerAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item); mNavigationTags = getResources().getStringArray(R.array.main_navigation_list); mNavigationSpinner = new Spinner(getSupportActionBar().getThemedContext()); mNavigationSpinner.setAdapter(spinnerAdapter); mNavigationSpinner.setOnItemSelectedListener(this); mToolbar.addView(mNavigationSpinner) </code></pre>
0
1,172
How to open a jdialog from a jframe
<p>JFrame button to open the jdialog:</p> <pre><code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: </code></pre> <p>JDialog method that opens the dialog:</p> <pre><code> public void run() { AddClient dialog = new AddClient(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); </code></pre> <p>My JDialog class is named AddClient, my JFrame class is named MainWindow. The package these are in is named my.javaapp</p> <p>How would i go onto doing this? I'm pretty new to java, was using python up until this point and dove head in into java swing gui builder with netbeans, i'm planning on watching tutorials and reading through the java documentation to learn more about java, but i would like to start by being able to open this jdialog.</p> <p><em>Before asking this question i searched a lot, and i read other questions that had been asked to solve more or less this same problem, i still couldn't solve mine though so i'm asking.</em></p> <p><strong>Solution:</strong></p> <p>Delete the main function from the class the gui you want to pop up is on e.g</p> <pre><code>public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJDialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJDialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJDialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJDialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //&lt;/editor-fold&gt; /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { NewJDialog1 dialog = new NewJDialog1(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } </code></pre> <p>Before deleting though, copy this line:</p> <pre><code>NewJDialog1 dialog = new NewJDialog1(new javax.swing.JFrame(), true); </code></pre> <p>Right click the button you want to pop this window up after pressing, events > action > action performed. Paste it there like this:</p> <pre><code>private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { NewJDialog1 dialog = new NewJDialog1(new javax.swing.JFrame(), true); dialog.setVisible(true); } </code></pre> <p>Remember to add the last line, that's what shows up the dialog.</p>
0
1,465
why android:layout_gravity="right" not working here in android xml
<p>my xml code for list view's row is</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" android:orientation="horizontal" &gt; &lt;LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="5" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" /&gt; &lt;TextView android:id="@+id/tv_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_weight="2" android:gravity="center" &gt; &lt;ImageView android:id="@+id/iv_image" android:layout_width="50dp" android:layout_height="40dp" android:background="@drawable/app_icon_17" android:contentDescription="@string/empty" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="right" android:layout_weight="2" android:gravity="center" &gt; &lt;Button android:id="@+id/btn_delete" android:layout_width="40dp" android:layout_height="40dp" android:background="@drawable/btn_delete_new" android:focusable="false" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>I want the last button with id btn_delete to stay right aligned. And its showing as I wanted in "graphical layout" while designing. But when I run it, on emulator it's not working. </p> <p>See the output :</p> <p><img src="https://i.stack.imgur.com/kcFIz.png" alt="enter image description here"></p> <p>So why the delete button not getting right aligned?</p>
0
1,067
Telnet to cisco switch using php
<p>I need to telnet to cisco switch using php and execute <code>show interface status</code> command and get results. I tried some php classes I found on internet but none of them could connect to device. So I tried to write the script myself, but I have the same problem, I cant connect to device.</p> <p>The host sends me banner message and then new line with <code>username:</code>. I send my username with <code>\r\n</code>, wait some time and tries to read data, but it looks to me like host is just ignoring my new line characters. This is response I got (explode('\n') on response):</p> <pre><code>Array ( [0] =&gt; % [1] =&gt; User Access Verification [2] =&gt; Username: timeout expired! ) </code></pre> <p>Why didn't I get prompt on password? I tried it with sending telnet headers, and without, no change. Can anyone please help me?</p> <p>Here is my code</p> <pre><code>&lt;? $host = "switchName"; $name = "name"; $pass = "pass"; $port = 23; $timeOut = 15; $connected = false; $skipNullLines = true; $timeout = 125000; $header1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x41).chr(0x4E).chr(0x53).chr(0x49).chr(0xFF).chr(0xF0); $header2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21); function read_string() { global $fw,$host,$skipNullLines; $string = ""; while( !feof($fw) ) { $read = fgets($fw); $string .= $read; // Probably prompt, stop reading if( strpos($read, ':') !== FALSE || strpos($read, '&gt; (enable)') !== FALSE || strpos($read, $host.'#') !== FALSE) { break; } } $string = explode("\n", $string); // Get rid of null lines $ret = array(); for($i = 0; $i&lt;count($string); $i++) { if( trim($string[$i]) == '' &amp;&amp; $skipNullLines ) continue; $ret[] = $string[$i]; } return $ret; } function send_string($string, $force=false) { GLOBAL $timeout,$fw; $string = trim($string); // execute only strings that are preceded by "show" (if not forced) if(!$force &amp;&amp; strpos($string, 'show ') !== 0) { return 1; } fputs($fw, $string."\r\n"); echo("SEND:".$string."\r\n"); usleep($timeout); } $fw = fsockopen($host, $port, $errno, $errorstr, $timeOut); if($fw == false) { echo("Cant connect"); } else { echo("Connected&lt;br&gt;"); $connected = true; stream_set_timeout($fw, $timeout); // fputs($fw, $header1); // usleep($timeout); // fputs($fw, $header2); // usleep($timeout); print_r(read_string()); send_string("test", true); print_r(read_string()); } fclose($fw); ?&gt; </code></pre> <p><strong>UPDATE</strong> If I send username at first, and then I read, I get password prompt. I dont understand it, why cant I firstly read messages from host and then send my response. The way it works to me now (send response and then read for prompt) is no-sense! (and I still got "% Authentication failed." message event with right password/name).</p> <pre><code>... $connected = true; stream_set_timeout($fw, $timeout); send_string("name", true); send_string("password", true); print_r(read_string()); ... </code></pre>
0
1,728
I can't find populateViewHolder Method in FirebaseRecyclerAdapter class
<p>I want to use <code>FirebaseRecyclerAdapter</code> in my project and I used this code segment in a previous Project</p> <pre><code>FirebaseRecyclerAdapter&lt;ChatMessage, ChatMessageViewHolder&gt; adapter = new FirebaseRecyclerAdapter&lt;ChatMessage, ChatMessageViewHolder&gt;(ChatMessage.class, android.R.layout.two_line_list_item, ChatMessageViewHolder.class, ref) { public void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatMessage chatMessage, int position) { chatMessageViewHolder.nameText.setText(chatMessage.getName()); chatMessageViewHolder.messageText.setText(chatMessage.getMessage()); } }; recycler.setAdapter(mAdapter); </code></pre> <p>and it was working fine but now it doesn't work any more, Is there any update in the new version of <code>FirebaseUi</code> that can't allow me to reuse this code now?</p> <p><strong>I tried this in my project</strong></p> <pre><code> @Override protected void onStart() { super.onStart(); FirebaseRecyclerAdapter&lt;BlogModel, BlogListViewHolder&gt; adapter = new FirebaseRecyclerAdapter&lt;BlogModel, BlogListViewHolder&gt;(BlogModel.class, android.R.layout.two_line_list_item, BlogListViewHolder.class, mDatabaseReference) { public void populateViewHolder(BlogListViewHolder blogListViewHolder, BlogModel blogModel, int position) { blogListViewHolder.postTitle.setText(blogModel.getPostTitle()); blogListViewHolder.postDesc.setText(blogModel.getPostDesc()); } }; mBlogList.setAdapter(adapter); } </code></pre> <p>and Android Studio gives an error saying you must implement <code>onCreateViewHolder,onBindViewHolder</code> Method.</p> <p><strong>BlogListViewHolder class</strong></p> <pre><code>public static class BlogListViewHolder extends RecyclerView.ViewHolder { ImageView postImage; TextView postTitle; TextView postDesc; public BlogListViewHolder(View view) { super(view); postImage = view.findViewById(R.id.blog_image_id); postTitle = view.findViewById(R.id.blog_title_id); postDesc = view.findViewById(R.id.blog_desc_id); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } } </code></pre> <p><strong>I use this Dependencies</strong> </p> <pre><code>dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:26.0.2' compile 'com.google.firebase:firebase-auth:11.4.2' compile 'com.google.firebase:firebase-database:11.4.2' compile 'com.google.firebase:firebase-storage:11.4.2' compile 'com.firebaseui:firebase-ui-database:3.1.0' compile 'com.firebaseui:firebase-ui-firestore:3.1.0' compile 'com.firebaseui:firebase-ui-auth:3.1.0' compile 'com.firebaseui:firebase-ui-storage:3.1.0' testCompile 'junit:junit:4.12' compile 'com.squareup.picasso:picasso:2.5.2' } apply plugin: 'com.google.gms.google-services' </code></pre>
0
1,440
Preventing a VB.Net form from closing
<p>We are using this coding to handle the clicking of the big red X as a means to bypass all textbox validation on the form.</p> <p>The code will test if any changes are made to the data bound controls on the form. The code handle cancelling changes made prior to closing the form.</p> <p>Would would also like to cancel the clicking of the big X and not allow the form to close.</p> <p>Can you show any needed coding that will not allow the form to actually close? We would like to add this new coding after the Else statement in the coding show below.</p> <pre><code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) Select Case ((m.WParam.ToInt64() And &amp;HFFFF) And &amp;HFFF0) Case &amp;HF060 ' The user chose to close the form. Me.StudentsBindingSource.EndEdit() Me.AutoValidate = System.Windows.Forms.AutoValidate.Disable If Me.StudentsDataSet.HasChanges Then ' Alert the user. '---------------- If MessageBox.Show("You are about to loose any *** Student *** changes you have made! " &amp; vbCrLf &amp; vbCrLf &amp; _ "ARE YOU SURE YOU WANT TO DO THIS?" &amp; vbCrLf &amp; vbCrLf, _ "*** W A R N I N G ***", _ MessageBoxButtons.YesNo, _ MessageBoxIcon.Warning, _ MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then RibbonButtonCancelChanges_Click(Nothing, Nothing) Else ' Reset validation. '------------------ Me.CausesValidation = True End If End If End Select MyBase.WndProc(m) End Sub </code></pre> <p>We tried this but the Validating event of the textbox controls execute which is not what we want.</p> <pre><code>Private Sub FormStudents_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing Me.AutoValidate = System.Windows.Forms.AutoValidate.Disable Me.StudentsBindingSource.EndEdit() If Me.StudentsDataSet.HasChanges Then ' Alert the user. '---------------- If MessageBox.Show("You are about to loose any *** Student *** changes you have made! " &amp; vbCrLf &amp; vbCrLf &amp; _ "ARE YOU SURE YOU WANT TO DO THIS?" &amp; vbCrLf &amp; vbCrLf, _ "*** W A R N I N G ***", _ MessageBoxButtons.YesNo, _ MessageBoxIcon.Warning, _ MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then RibbonButtonCancelChanges_Click(Nothing, Nothing) Else ' Reset validation. '------------------ Me.CausesValidation = True e.Cancel = True End If End If End Sub </code></pre>
0
1,375
Adding private key into iOS Keychain
<p>I am trying to add a private key into the iOS keychain. The certificate (public key) works fine but the private key refuses... I am totally confused why the following code does not work.</p> <p>First I am checking if the current key (=key in case of that the Keychain is a key/value store) is 'free' in the Keychain. Then I am going to add the private key.</p> <pre><code>CFStringRef labelstring = CFStringCreateWithCString(NULL, [key cStringUsingEncoding:NSUTF8StringEncoding], kCFStringEncodingUTF8); NSArray* keys = [NSArray arrayWithObjects:(__bridge id)kSecClass,kSecAttrLabel,kSecReturnData,kSecAttrAccessible,nil]; NSArray* values = [NSArray arrayWithObjects:(__bridge id)kSecClassKey,labelstring,kCFBooleanTrue,kSecAttrAccessibleWhenUnlocked,nil]; NSMutableDictionary* searchdict = [NSMutableDictionary dictionaryWithObjects:values forKeys:keys]; CFRelease(labelstring); NSMutableDictionary *query = searchdict; CFTypeRef item = NULL; OSStatus error = SecItemCopyMatching((__bridge_retained CFDictionaryRef) query, &amp;item); if (error) { NSLog(@"Error: %ld (statuscode)", error); } if(error != errSecItemNotFound) { SecItemDelete((__bridge_retained CFDictionaryRef) query); } [query setObject:(id)data forKey:(__bridge id)kSecValueData]; OSStatus status = SecItemAdd((__bridge_retained CFDictionaryRef) query, &amp;item); if(status) { NSLog(@"Keychain error occured: %ld (statuscode)", status); return NO; } </code></pre> <p>The debug output is the following:</p> <pre><code>2012-07-26 15:33:03.772 App[15529:1b03] Error: -25300 (statuscode) 2012-07-26 15:33:11.195 App[15529:1b03] Keychain error occured: -25299 (statuscode) </code></pre> <p>The first error code <code>-25300</code> represents <code>errSecItemNotFound</code>. So there is no value stored for this key. Then, when I try to add the private key into the Keychain I get <code>-25299</code> which means <code>errSecDuplicateItem</code>. I do not understand this. Why is this happening?</p> <p>Does anyone have a clue or hint on this?</p> <p>Apple's error codes:</p> <pre><code>errSecSuccess = 0, /* No error. */ errSecUnimplemented = -4, /* Function or operation not implemented. */ errSecParam = -50, /* One or more parameters passed to a function where not valid. */ errSecAllocate = -108, /* Failed to allocate memory. */ errSecNotAvailable = -25291, /* No keychain is available. You may need to restart your computer. */ errSecDuplicateItem = -25299, /* The specified item already exists in the keychain. */ errSecItemNotFound = -25300, /* The specified item could not be found in the keychain. */ errSecInteractionNotAllowed = -25308, /* User interaction is not allowed. */ errSecDecode = -26275, /* Unable to decode the provided data. */ errSecAuthFailed = -25293, /* The user name or passphrase you entered is not correct. */ </code></pre> <p>Thanks in advance!</p> <p><strong>Update #1: I've figured out that it works only for the first time. Even when data and key is different, after the first time stored into the keychain I cannot store further keys.</strong></p>
0
1,121
How do I get a ListPopupWindow to work with a custom adapter?
<p>I want to display a simple array of strings in a ListPopupWindow that is shown on a button click. I'm running into problems however, as when I do some minimal setup of either an <code>ArrayAdapter&lt;String&gt;</code> or a custom-built adapter, I run into a resources not found exception when I go to show the popup window. Here is the code I'm using (with the stack trace after it). Any ideas as to what is happening?</p> <pre><code>public class AndroidSandboxActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button btn = (Button)findViewById(R.id.btn1); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showListPopup(btn); } }); } public void showListPopup(View anchor) { ListPopupWindow popup = new ListPopupWindow(this); popup.setAnchorView(anchor); ListAdapter adapter = new MyAdapter(this); popup.setAdapter(adapter); popup.show(); } public static class MyAdapter extends BaseAdapter implements ListAdapter { private final String[] list = new String[] {"one","two","three"}; private Activity activity; public MyAdapter(Activity activity) { this.activity = activity; } @Override public int getCount() { return list.length; } @Override public Object getItem(int position) { return list[position]; } @Override public long getItemId(int position) { return position; } private static int textid = 1234; @Override public View getView(int position, View convertView, ViewGroup parent) { TextView text = null; if (convertView == null) { LinearLayout layout = new LinearLayout(activity); layout.setOrientation(LinearLayout.HORIZONTAL); text = new TextView(activity); text.setId(textid); layout.addView(text); convertView = layout; } else { text = (TextView)convertView.findViewById(textid); } text.setText(list[position]); return convertView; } } } </code></pre> <p>And here's the stack trace (the thing that boggles my mind is that it says it's using an <code>ArrayAdapter</code> when I'm using my own custom adapter):</p> <pre><code>Thread [&lt;1&gt; main] (Suspended (exception Resources$NotFoundException)) Resources.loadXmlResourceParser(int, String) line: 2047 Resources.getLayout(int) line: 853 PhoneLayoutInflater(LayoutInflater).inflate(int, ViewGroup, boolean) line: 389 ArrayAdapter.createViewFromResource(int, View, ViewGroup, int) line: 375 ArrayAdapter.getView(int, View, ViewGroup) line: 366 ListPopupWindow$DropDownListView(AbsListView).obtainView(int, boolean[]) line: 2146 ListPopupWindow$DropDownListView.obtainView(int, boolean[]) line: 1156 ListPopupWindow$DropDownListView(ListView).measureHeightOfChildren(int, int, int, int, int) line: 1261 ListPopupWindow.buildDropDown() line: 1083 ListPopupWindow.show() line: 517 AndroidSandboxActivity.showListPopup() line: 41 AndroidSandboxActivity$1.onClick(View) line: 28 Button(View).performClick() line: 3122 View$PerformClick.run() line: 11942 ViewRoot(Handler).handleCallback(Message) line: 587 ViewRoot(Handler).dispatchMessage(Message) line: 92 Looper.loop() line: 132 ActivityThread.main(String[]) line: 4028 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 491 ZygoteInit$MethodAndArgsCaller.run() line: 844 ZygoteInit.main(String[]) line: 602 NativeStart.main(String[]) line: not available [native method] </code></pre> <p>Any help would be appreciated!</p>
0
1,686
how get Result from onActivityResult in Fragment?
<p>I have used <code>Navigation drawer</code> in each item click i have called <code>Fragments</code> so in one item i have called one <code>Fragment</code> in this fragment i need to get picture from camera and set it to as <code>canvas background</code>. In this I have captured camera picture but don't know how to get this picture after captured and set it to on canvas background.</p> <p><strong><em>Fragment code</em></strong></p> <pre><code>import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Toast; import com.ssoft.admin.code.SharedPreferenceStore; import com.ssoft.admin.code.Tools; import com.ssoft.admin.salesmateco.FragSiteInspectionAdditional; import com.ssoft.admin.salesmateco.R; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FragSignature extends Fragment implements View.OnClickListener { Button mSIBtnCamera; Fragment fragment; Tools mTools; private static final int RESULT_OK = 1; private static final int RESULT_CANCELED = 0; Uri imageUri = null; final int CAMERA_DATA = 100, INTENT_DATA = 1; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate( R.layout.frag_site_inspection_signature, null); mSIBtnCamera = (Button) rootView.findViewById(R.id.camera); mSIBtnCamera.setOnClickListener(this); return rootView; } @Override public void onClick(View v) { if (v.getId() == R.id.camera) { captureImage(); } else { Toast.makeText(getActivity().getApplicationContext(), "FragSIPhotos Add Button OnClick", Toast.LENGTH_SHORT) .show(); } } public void captureImage() { // Define the file-name to save photo taken by Camera activity String fileName = "Images.jpg"; // Create parameters for Intent with filename ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, fileName); values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera"); // imageUri is the current activity attribute, define and save it for // later usage Uri imageUri = getActivity().getApplicationContext() .getContentResolver() .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); /**** * EXTERNAL_CONTENT_URI : style URI for the "primary" external storage * volume. ****/ // Standard Intent action that can be sent to have the camera // application capture an image and return it. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, INTENT_DATA); Log.e("captureImage()", "state -1"); getActivity().startActivityForResult(intent, CAMERA_DATA); Log.e("captureImage()", "end"); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.e("OnActivityResult()", "1"); if (requestCode == CAMERA_DATA) { Log.e("OnActivityResult()", "2"); if (resultCode == RESULT_OK) { // Image captured and saved to fileUri specified in the Intent Log.e("OnActivityResult()", "3"); } else if (resultCode == RESULT_CANCELED) { // User cancelled the image capture Log.e("OnActivityResult()", "4"); } else { // Image capture failed, advise user Log.e("OnActivityResult()", "5"); } } Log.e("OnActivityResult()", "6"); super.onActivityResult(requestCode, resultCode, data); Log.e("OnActivityResult()", "7"); } } </code></pre>
0
1,876
C# How to await a method that returns Task<dynamic>?
<p>I have a method that is parsing the results from a JSON object. The method returns a Task object but when I run the code, I am getting the following error:</p> <pre><code>'System.Collections.Generic.Dictionary&lt;string,object&gt;' does not contain a definition for 'GetAwaiter' </code></pre> <p>The object returned from the dynamic method is an array of objects of type System.Collections.Generic.Dictionary and System.Collections.Generic.KeyValuePair. Here is the code:</p> <pre><code>private static async Task&lt;dynamic&gt; GetReslutstAsync(string url) { WebRequest request; WebResponse response = null; try { request = WebRequest.Create(url); request.Credentials = new NetworkCredential("username", "password", "company"); //request.Credentials = CredentialCache.DefaultNetworkCredentials; response = await request.GetResponseAsync(); } catch (Exception e) { Console.WriteLine(e.Message); } using (var reader = new StreamReader(response.GetResponseStream())) { try { JavaScriptSerializer js = new JavaScriptSerializer(); var objects = js.Deserialize&lt;dynamic&gt;(reader.ReadToEnd()); return objects; } catch (Exception e) { Console.WriteLine(e.Message); return null; } } } </code></pre> <p>The exception occurs here:</p> <pre><code>private static async Task&lt;dynamic&gt; MakeRequest(string url) { try { return await GetReslutstAsync(url).Result; //&lt;---- This is where I get the error! } catch (Exception e) { Console.WriteLine(e.Message); return null; } } </code></pre> <p>I believe this has something to do with the fact that I am returning a dynamic type object. How can I get around this? I need to await this task inside the "MakeRequest" method so that it does not continue until the request is completed.</p> <p>EDIT: </p> <p>My "MakeRequest" method is in a loop like this:</p> <pre><code>while (true) { ClockTimer timer = new ClockTimer(); timer.StartTimer(); //&lt;---This does not stop untill 5 sec has passed MakeRequest("www.someurl.com"); //&lt;--- This just skips into the next loop even if not complete. } </code></pre> <p>My issue is that <code>MakeRequest</code> is being run asynchronously so basically, it just skips over this and goes right into the next loop. I need "MakeRequest" to HALT until the request is finished. I have tried removing all async/await keywords but this just results in "Result was not calculated".</p>
0
1,139
Angular 4 Dynamic form with nested groups
<p>I want to generate a reactive form from the tree structure.</p> <p>Here is the code that creates the form items (form groups and controls). For the controls nested in form group it I use a recursive template.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import { Component, Input, NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; @Component({ selector: 'form-item', template: ` &lt;ng-container [formGroup]="form"&gt; &lt;ng-container *ngTemplateOutlet="formItemTemplate; context:{ $implicit: pathSegments }"&gt;&lt;/ng-container&gt; &lt;ng-template #formItemTemplate let-pathSegments&gt; &lt;ng-container *ngIf="pathSegments.length &gt; 1"&gt; &lt;div [formGroupName]="pathSegments[0]" class="form-group"&gt; &lt;ng-container *ngTemplateOutlet="formItemTemplate; context:{ $implicit: pathSegments.slice(1) }"&gt;&lt;/ng-container&gt; &lt;/div&gt; &lt;/ng-container&gt; &lt;ng-container *ngIf="pathSegments.length === 1"&gt; &lt;div class="form-control"&gt; &lt;label&gt;{{pathSegments[pathSegments.length - 1]}}&lt;/label&gt; &lt;!--&lt;input type="text" [formControlName]="pathSegments[pathSegments.length - 1]"/&gt;--&gt; &lt;input type="text"/&gt; &lt;/div&gt; &lt;/ng-container&gt; &lt;/ng-template&gt; &lt;/ng-container&gt; `, }) export class AppControlComponent { @Input() form: FormGroup; @Input() set path(path: string) { this.pathSegments = path.split('.'); } pathSegments: string[] = []; constructor() { } } @Component({ selector: 'app-root', template: ` &lt;form [formGroup]="questionForm"&gt; &lt;h1&gt;Question Form&lt;/h1&gt; &lt;form-item [form]="questionForm" path="question"&gt;&lt;/form-item&gt; &lt;form-item [form]="questionForm" path="answers.answer1"&gt;&lt;/form-item&gt; &lt;form-item [form]="questionForm" path="answers.answer2"&gt;&lt;/form-item&gt; &lt;form-item [form]="questionForm" path="answers.answer3"&gt;&lt;/form-item&gt; &lt;button type="submit"&gt;submit&lt;/button&gt; &lt;pre&gt;{{questionForm.value | json}}&lt;/pre&gt; &lt;/form&gt; `, }) export class AppComponent { private questionForm: FormGroup; constructor(private fb: FormBuilder) { this.questionForm = this.fb.group({ question: ['', Validators.required], answers: this.fb.group({ answer1: ['', Validators.required], answer2: ['', Validators.required], answer3: ['', Validators.required], }), }); } } @NgModule({ imports: [BrowserModule, FormsModule, ReactiveFormsModule], declarations: [ AppComponent, AppControlComponent ], bootstrap: [AppComponent] }) export class AppModule {}</code></pre> </div> </div> </p> <p>The form HTML is generated perfectly. But when I add the <code>formControlName</code> directive to the input the HTML generation breaks. Then I get such error:</p> <pre><code>Error: Cannot find control with name: 'answer1' </code></pre>
0
1,373
Java: no security manager: RMI class loader disabled
<p>Hi I have RMI application and now I try to invoke some methods at server from my client. I have following code:</p> <pre><code>public static void main(final String[] args) { try { //Setting the security manager System.setSecurityManager(new RMISecurityManager()); IndicatorsService server = (IndicatorsService) Naming .lookup("rmi://localhost/" + IndicatorsService.SERVICE_NAME); DataProvider provider = new OHLCProvider(server); server.registerOHLCProvider(provider); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } </code></pre> <p>server Is correctly loaded, but when I am trying to call <code>server.registerOHLCProvider(provider);</code> I get these errors:</p> <pre><code> java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: java.lang.ClassNotFoundException: sk.xorty.client.providers.OHLCProvider (no security manager: RMI class loader disabled) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:336) at sun.rmi.transport.Transport$1.run(Transport.java:159) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.Transport.serviceCall(Transport.java:155) at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649) 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:662) at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255) at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142) at sk.fri.statistics.service.impl.IndicatorsServiceImpl_Stub.registerOHLCProvider(Unknown Source) at sk.fri.statistics.service.Client.main(Client.java:61) Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: java.lang.ClassNotFoundException: sk.xorty.client.providers.OHLCProvider (no security manager: RMI class loader disabled) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:296) at sun.rmi.transport.Transport$1.run(Transport.java:159) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.Transport.serviceCall(Transport.java:155) at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649) 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:662) Caused by: java.lang.ClassNotFoundException: sk.xorty.client.providers.OHLCProvider (no security manager: RMI class loader disabled) at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:375) at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:165) at java.rmi.server.RMIClassLoader$2.loadClass(RMIClassLoader.java:620) at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247) at sun.rmi.server.MarshalInputStream.resolveClass(MarshalInputStream.java:197) at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1574) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350) at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:306) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:290) ... 9 more </code></pre> <p>I have added my policy file as VM argument, here is how it looks like:</p> <pre><code>grant { permission java.security.AllPermission; } </code></pre> <p>It keeps saying something about disabled classloading, so I guess problem is somewhere there ... Thanks!</p>
0
1,689
java.security.cert.CertificateExpiredException: NotAfter
<p>I am using EWSJavaAPI 1.1.5 to connect to Exchange Server 2010.</p> <p>Everything was working fine until today while trying to connect to the server, I am getting the following exception:</p> <pre><code>microsoft.exchange.webservices.data.ServiceRequestException: The request failed. java.security.cert.CertificateExpiredException: NotAfter: Fri Dec 28 01:26:27 GMT+02:00 2012 at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(Unknown Source) at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source) at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(Unknown Source) at microsoft.exchange.webservices.data.ExchangeService.bindToFolder(Unknown Source) at microsoft.exchange.webservices.data.ExchangeService.bindToFolder(Unknown Source) at microsoft.exchange.webservices.data.Folder.bind(Unknown Source) at microsoft.exchange.webservices.data.Folder.bind(Unknown Source) at com.xeno.phonesuite.web.Mail.Mail.authenticate(Mail.java:100) at org.apache.jsp.mailandcalendar.dologin_jsp._jspService(dologin_jsp.java:121) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) 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:662) Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateExpiredException: NotAfter: Fri Dec 28 01:26:27 GMT+02:00 2012 at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1649) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:893) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:632) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123) at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:506) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at microsoft.exchange.webservices.data.HttpClientWebRequest.executeRequest(Unknown Source) at microsoft.exchange.webservices.data.ServiceRequestBase.emit(Unknown Source) ... 31 more Caused by: java.security.cert.CertificateExpiredException: NotAfter: Fri Dec 28 01:26:27 GMT+02:00 2012 at sun.security.x509.CertificateValidity.valid(CertificateValidity.java:256) at sun.security.x509.X509CertImpl.checkValidity(X509CertImpl.java:570) at sun.security.x509.X509CertImpl.checkValidity(X509CertImpl.java:543) at microsoft.exchange.webservices.data.EwsX509TrustManager.checkServerTrusted(Unknown Source) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1198) ... 49 more </code></pre> <p>Please advise why I am getting this exception and how to solve it, thanks.</p>
0
2,092
Failed to convert property value of type [java.lang.String] to required type [java.time.LocalDate]
<pre><code>{ "toDepartureDate": "2016-12-28", "fromDepartureDate": "2016-12-28" } </code></pre> <p>I want to post above String dates in json as <code>java.time.LocalDate</code>, but I am receiving 400 Bad Request as error. Could some one help here. I have used <code>@JsonFormat</code> but it did not help me either.</p> <pre><code>@JsonFormat(shape=JsonFormat.Shape.STRING,pattern="yyyy-MM-dd",timezone = "GMT+5:30") private LocalDate fromDepartureDate; @JsonFormat(shape=JsonFormat.Shape.STRING,pattern="yyyy-MM-dd",timezone = "GMT+5:30") private LocalDate toDepartureDate; { "timestamp": 1482942147246, "status": 400, "error": "Bad Request", "exception": "org.springframework.validation.BindException", "errors": [ { "codes": [ "typeMismatch.flightReportSearchDto.fromDepartureDate", "typeMismatch.fromDepartureDate", "typeMismatch.java.time.LocalDate", "typeMismatch" ], "arguments": [ { "codes": [ "flightReportSearchDto.fromDepartureDate", "fromDepartureDate" ], "arguments": null, "defaultMessage": "fromDepartureDate", "code": "fromDepartureDate" } ], "defaultMessage": "Failed to convert property value of type [java.lang.String] to required type [java.time.LocalDate] for property 'fromDepartureDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat java.time.LocalDate] for value '2016-12-28'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2016-12-28]", "objectName": "flightReportSearchDto", "field": "fromDepartureDate", "rejectedValue": "2016-12-28", "bindingFailure": true, "code": "typeMismatch" }, { "codes": [ "typeMismatch.flightReportSearchDto.toDepartureDate", "typeMismatch.toDepartureDate", "typeMismatch.java.time.LocalDate", "typeMismatch" ], "arguments": [ { "codes": [ "flightReportSearchDto.toDepartureDate", "toDepartureDate" ], "arguments": null, "defaultMessage": "toDepartureDate", "code": "toDepartureDate" } ], "defaultMessage": "Failed to convert property value of type [java.lang.String] to required type [java.time.LocalDate] for property 'toDepartureDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat java.time.LocalDate] for value '2016-12-29'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2016-12-29]", "objectName": "flightReportSearchDto", "field": "toDepartureDate", "rejectedValue": "2016-12-29", "bindingFailure": true, "code": "typeMismatch" } ] } </code></pre>
0
1,279
How to fix Next.js Vercel deployment module not found error
<p>My next.js app works on my machine and was working when deployed on Vercel but now it fails when building on Vercel with the following error: </p> <p>I've tried deleting node_modules and running <code>npm install</code> a few times but with no joy. </p> <p>Any help would be hugely appreciated. Thank you!</p> <blockquote> <p>Running "npm run build" 20:43:24.926<br> tdwcks@1.0.0 build /vercel/5ccaedc9 20:43:24.926<br> next build 20:43:24.967<br> internal/modules/cjs/loader.js:983 20:43:24.967<br> throw err; 20:43:24.967<br> ^ 20:43:24.967<br> Error: Cannot find module '../build/output/log' 20:43:24.967<br> Require stack: 20:43:24.967<br> - /vercel/5ccaedc9/node_modules/.bin/next 20:43:24.967<br> at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15) 20:43:24.967<br> at Function.Module._load (internal/modules/cjs/loader.js:862:27) 20:43:24.967<br> at Module.require (internal/modules/cjs/loader.js:1042:19) 20:43:24.967<br> at require (internal/modules/cjs/helpers.js:77:18) 20:43:24.967<br> at Object. (/vercel/5ccaedc9/node_modules/.bin/next:2:46) 20:43:24.967<br> at Module._compile (internal/modules/cjs/loader.js:1156:30) 20:43:24.967<br> at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10) 20:43:24.967<br> at Module.load (internal/modules/cjs/loader.js:1000:32) 20:43:24.967<br> at Function.Module._load (internal/modules/cjs/loader.js:899:14) 20:43:24.967<br> at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) { 20:43:24.967<br> code: 'MODULE_NOT_FOUND', 20:43:24.967<br> requireStack: [ '/vercel/5ccaedc9/node_modules/.bin/next' ] 20:43:24.967<br> } 20:43:24.969<br> npm ERR! code ELIFECYCLE 20:43:24.969<br> npm ERR! errno 1 20:43:24.970<br> npm ERR! tdwcks@1.0.0 build: <code>next build</code> 20:43:24.970<br> npm ERR! Exit status 1 20:43:24.970<br> npm ERR! 20:43:24.970<br> npm ERR! Failed at the tdwcks@1.0.0 build script. 20:43:24.970<br> npm ERR! This is probably not a problem with npm. There is likely additional logging output above. 20:43:24.974<br> npm ERR! A complete log of this run can be found in: 20:43:24.974<br> npm ERR! /vercel/.npm/_logs/2020-06-17T19_43_24_971Z-debug.log 20:43:24.979<br> Error: Command "npm run build" exited with 1 20:43:25.342<br> [dmesg] follows: 20:43:25.342<br> [ 962.449223] ecs-bridge: port 1(veth2a021300) entered disabled state 20:43:25.342<br> [ 962.453655] device veth2a021300 entered promiscuous mode 20:43:25.342<br> [ 962.457686] ecs-bridge: port 1(veth2a021300) entered blocking state 20:43:25.342<br> [ 962.462004] ecs-bridge: port 1(veth2a021300) entered forwarding state 20:43:26.242<br> Done with "package.json"</p> </blockquote> <p>Here's my Package.json</p> <pre><code>{ "name": "tdwcks", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "next", "build": "next build", "start": "next start" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "cjs": "0.0.11", "core-util-is": "^1.0.2", "framer-motion": "^1.11.0", "gray-matter": "^4.0.2", "next": "^9.4.4", "raw-loader": "^4.0.1", "react": "^16.13.1", "react-dom": "^16.13.1", "react-ga": "^3.0.0", "react-markdown": "^4.3.1", "react-player": "^2.2.0", "react-scripts": "^3.4.1" }, "devDependencies": { "postcss-preset-env": "^6.7.0", "tailwindcss": "^1.4.6" } } </code></pre>
0
1,725
Display data from SQLite database into ListView in Android
<p>Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this.</p> <p>Here's my code <strong>getClientNames</strong> in <strong>DatabaseHelper</strong> class:</p> <pre><code>public Cursor getSitesByClientname(String id) { String[] args={id}; Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args); String results = ""; /*int count = myCursor.getCount(); String[] results = new String[count + 1]; int i = 0;*/ if (myCursor != null) { if(myCursor.getCount() &gt; 0) { for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext()) { results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename")); } } } return results; } </code></pre> <p>One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.</p> <p>Here's the <strong>ClientSites</strong> class where I want to display the data:</p> <pre><code>public class ClientSites extends Activity { //public final static String ID_EXTRA="com.example.loginfromlocal._ID"; private DBUserAdapter dbHelper = null; private Cursor ourCursor = null; private Adapter adapter=null; @SuppressWarnings("deprecation") @SuppressLint("NewApi") public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.client_sites); Intent i = getIntent(); String uID = String.valueOf(i.getIntExtra("userID", 0)); ListView myListView = (ListView)findViewById(R.id.myListView); dbHelper = new DBUserAdapter(this); //dbHelper.createDatabase(); dbHelper.openDataBase(); ourCursor = dbHelper.getSitesByClientname(uID); Log.e("ALERT", uID.toString()); startManagingCursor(ourCursor); Log.e("ERROR", "After start manage cursor: "); //@SuppressWarnings("deprecation") //SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0); adapter = new Adapter(ourCursor); //Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show(); myListView.setAdapter(adapter); myListView.setOnItemClickListener(onListClick); } catch (Exception e) { Log.e("ERROR", "XXERROR IN CODE: " + e.toString()); e.printStackTrace(); } } private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Intent i=new Intent(ClientSites.this, InspectionPoints.class); i.putExtra(ID_EXTRA, String.valueOf(id)); startActivity(i); } }; class Adapter extends CursorAdapter { @SuppressWarnings("deprecation") Adapter(Cursor c) { super(ClientSites.this, c); } //@Override public void bindView(View row, Context ctxt, Cursor c) { Holder holder=(Holder)row.getTag(); holder.populateFrom(c, dbHelper); } @Override public View newView(Context ctxt, Cursor c, ViewGroup parent) { LayoutInflater inflater=getLayoutInflater(); View row = inflater.inflate(R.layout.row, parent, false); Holder holder=new Holder(row); row.setTag(holder); return(row); } } static class Holder { private TextView name=null; Holder(View row) { name=(TextView)row.findViewById(R.id.ingredientText); } void populateFrom(Cursor c, DBUserAdapter r) { name.setText(r.getName(c)); } } } </code></pre> <p>Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong.</p> <pre><code>public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); //setContentView(R.layout.client_sites); Intent i = getIntent(); String uID = String.valueOf(i.getIntExtra("userID", 0)); //int uID = i.getIntExtra("userID", 0); //ListView myListView = (ListView)findViewById(R.id.myListView); dbHelper = new DBUserAdapter(this); dbHelper.createDatabase(); dbHelper.openDataBase(); String[] results = dbHelper.getSitesByClientname(uID); //setListAdapter(new ArrayAdapter&lt;String&gt;(ClientSites.this, R.id.myListView, results)); //adapter = new ArrayAdapter&lt;String&gt;(ClientSites.this, R.id.myListView, results); setListAdapter(new ArrayAdapter&lt;String&gt;(ClientSites.this, R.layout.client_sites, results)); //ListView myListView = (ListView)findViewById(R.id.myListView); ListView listView = getListView(); listView.setTextFilterEnabled(true); //ourCursor = dbHelper.getSitesByClientname(uID); //Log.e("ALERT", uID.toString()); //startManagingCursor(ourCursor); //Log.e("ERROR", "After start manage cursor: "); //@SuppressWarnings("deprecation") //SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!! //CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0); //adapter = new Adapter(ourCursor); //Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show(); //myListView.setAdapter(adapter); //myListView.setOnItemClickListener(onListClick); </code></pre>
0
2,959
jboss-as-maven-plugin can't deploy to remote JBoss AS7?
<p>I've tried for days to use <code>jboss-as-maven-plugin</code> to deploy web projects to remote JBoss AS7, but it didn't work. </p> <p>Here is my <code>pom.xml</code>: </p> <pre><code>&lt;!-- JBoss Application Server --&gt; &lt;plugin&gt; &lt;groupId&gt;org.jboss.as.plugins&lt;/groupId&gt; &lt;artifactId&gt;jboss-as-maven-plugin&lt;/artifactId&gt; &lt;version&gt;7.1.0.CR1b&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;install&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;deploy&lt;/goal&gt; &lt;/goals&gt; &lt;!-- Only remote server needs --&gt; &lt;configuration&gt; &lt;hostname&gt;192.168.1.104&lt;/hostname&gt; &lt;port&gt;9999&lt;/port&gt; &lt;username&gt;admin&lt;/username&gt; &lt;password&gt;admin123&lt;/password&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>Using this configuration I can deploy to <strong>localhost</strong> without <code>&lt;configuration&gt;</code>, even no <code>&lt;username&gt;</code> and <code>&lt;password&gt;</code>.</p> <p>To deploy to my real IP address, I modified <strong>${JBOSS_HOME}/configuration/standlone.xml</strong>, by changing <code>jboss.bind.address</code> from <strong>127.0.0.1</strong> to <strong>0.0.0.0</strong> (to unbind JBoss address), so I can deploy projects by using:</p> <pre><code>&lt;configuration&gt; &lt;!-- 192.168.1.106 is my ip --&gt; &lt;hostname&gt;192.168.1.06&lt;/hostname&gt; &lt;port&gt;9999&lt;/port&gt; &lt;/configuration&gt; </code></pre> <p>It works too, but by changing <code>&lt;hostname&gt;</code> to point to my other computer (in the same router) it doesn't work but that computer receives a request, and the request is cut by something. (I thought it may be JBoss)</p> <p>The error message in Maven console is as follows:</p> <pre><code> INFO: JBoss Remoting version 3.2.0.CR8 [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 30.572s [INFO] Finished at: Fri Feb 10 23:41:25 CST 2012 [INFO] Final Memory: 18M/170M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.jboss.as.plugins:jboss-as-maven-plugin:7.1.0. CR1b:deploy (default) on project MessagePushX-RELEASE: Could not execute goal de ploy on MessagePush.war. Reason: java.net.ConnectException: JBAS012144: Could no t connect to remote://192.168.1.104:9999. The connection timed out -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit ch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please rea d the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException </code></pre> <p>Who can tell me is JBoss as 7.1.0 is not allowed remote deploy? </p> <p>For some security issues? </p>
0
1,287
android expandablelistview how to set space between groups items
<p>I have expandablelistview and I want to add padding (or margin) between the groups items, I used <code>margin-botton</code> on the group items, it works but now it is also applied to the group item and its childs, I want to keep a space between groups items, not between a group item and its child, i work like this:</p> <h3> main xml</h3> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#FFFFFF"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif" android:textSize="25dip" android:textColor="#025f7c" android:text="@string/tv_allAddresses" android:layout_gravity="center" android:layout_marginTop="20dip" android:layout_marginBottom="25dip"/&gt; &lt;ExpandableListView android:id="@+id/elv_all_addresses_addresses" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dip"&gt; &lt;/ExpandableListView&gt; &lt;/LinearLayout&gt; </code></pre> <h3>group xml </h3> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/tv_all_address_group_groupName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="30dip" android:textColor="#000000" android:textSize="20dip" android:typeface="serif" /&gt; &lt;/LinearLayout&gt; </code></pre> <h3> child xml </h3> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" &gt; &lt;TextView android:id="@+id/tv_all_address_child_label" android:paddingLeft="50dip" android:typeface="serif" android:textSize="15dip" android:textColor="@color/BlueViolet" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/tv_all_address_child_value" android:textColor="#000000" android:layout_marginLeft="10dip" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; </code></pre>
0
1,169
Bootstrap carousel with responsive HTML5 videos?
<p>I'm trying to make a carousel with videos. With the images it works fine the image are responsive even in mobile view. But with videos the width is responsive but not the height. Basically I would like to achieve the same comportement with a carousel image but with a video. I've tried many tricks online but none is doing it. My video is 1024/552px</p> <p>Tried my best at a fiddle. You can see if you load the fiddle with a small width, it keeps the same height and it isn't responsive but the width of the carousel/video is (it crops the video on the sides though). It doesn't have the same comportement as an image. As you will see I have included an image in the second slide to further demonstrate my problem. </p> <p><a href="https://jsfiddle.net/687bsb21/1/" rel="noreferrer">https://jsfiddle.net/687bsb21/1/</a></p> <p>Here's the code :</p> <pre><code>&lt;div id="carousel-example-generic" class="carousel slide" data-ride="carousel"&gt; &lt;ol class="carousel-indicators"&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="0" class="active"&gt;&lt;/li&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="1"&gt;&lt;/li&gt; &lt;/ol&gt; &lt;!-- Wrapper for slides --&gt; &lt;div class="carousel-inner" role="listbox"&gt; &lt;div class="item active"&gt; &lt;div align="center"&gt; &lt;video autoplay loop&gt; &lt;source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" width="1024" height="552" type="video/mp4"&gt; Your browser does not support the video tag. &lt;/video&gt; &lt;/div&gt; &lt;div class="carousel-caption"&gt; &lt;h3&gt;hello&lt;/h3&gt; &lt;p&gt;hello&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src="http://dummyimage.com/1024x552/000/fff" class="img-responsive" alt="asfds"&gt; &lt;div class="carousel-caption"&gt; &lt;h3&gt;hello&lt;/h3&gt; &lt;p&gt;hello.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="left carousel-control" href="#carouselHelp" role="button" data-slide="prev"&gt; &lt;span class="glyphicon glyphicon-chevron-left" aria-hidden="true"&gt;&lt;/span&gt; &lt;span class="sr-only"&gt;Previous&lt;/span&gt; &lt;/a&gt; &lt;a class="right carousel-control" href="#carouselHelp" role="button" data-slide="next"&gt; &lt;span class="glyphicon glyphicon-chevron-right" aria-hidden="true"&gt;&lt;/span&gt; &lt;span class="sr-only"&gt;Next&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; </code></pre> <p>Thanks for helping.</p>
0
1,259
Using Butter Knife library for view injection
<p><strong>What i am doing</strong>::</p> <ol> <li>I am trying to run <a href="http://jakewharton.github.io/butterknife/" rel="noreferrer">butter knife library</a> for my simple project</li> <li>I have followed all the steps in documentation, but still i am getting log errors</li> <li>How can i resolve this, am i missing any step</li> <li>I have also added the jar in libs folder</li> </ol> <hr> <p><strong>MainActivity.java</strong></p> <pre><code>package com.example.butterknife; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; public class MainActivity extends Activity { @InjectView(R.id.txtID) TextView title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); title.setText("Hello Everyone !!"); } } </code></pre> <p><strong>Log</strong>::</p> <pre><code>04-15 11:50:57.845: E/AndroidRuntime(913): FATAL EXCEPTION: main 04-15 11:50:57.845: E/AndroidRuntime(913): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.butterknife/com.example.butterknife.MainActivity}: java.lang.NullPointerException 04-15 11:50:57.845: E/AndroidRuntime(913): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.app.ActivityThread.access$600(ActivityThread.java:122) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.os.Handler.dispatchMessage(Handler.java:99) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.os.Looper.loop(Looper.java:137) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.app.ActivityThread.main(ActivityThread.java:4340) 04-15 11:50:57.845: E/AndroidRuntime(913): at java.lang.reflect.Method.invokeNative(Native Method) 04-15 11:50:57.845: E/AndroidRuntime(913): at java.lang.reflect.Method.invoke(Method.java:511) 04-15 11:50:57.845: E/AndroidRuntime(913): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 04-15 11:50:57.845: E/AndroidRuntime(913): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 04-15 11:50:57.845: E/AndroidRuntime(913): at dalvik.system.NativeStart.main(Native Method) 04-15 11:50:57.845: E/AndroidRuntime(913): Caused by: java.lang.NullPointerException 04-15 11:50:57.845: E/AndroidRuntime(913): at com.example.butterknife.MainActivity.onCreate(MainActivity.java:19) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.app.Activity.performCreate(Activity.java:4465) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 04-15 11:50:57.845: E/AndroidRuntime(913): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919) 04-15 11:50:57.845: E/AndroidRuntime(913): ... 11 more 04-15 11:51:06.722: I/Process(913): Sending signal. PID: 913 SIG: 9 </code></pre>
0
1,236
std::unique_ptr deleted function, initializer_list - driven allocation
<p>All, </p> <p>When I instantiate a widgets array using an initializer-list format, a naked pointer that points to a member-variable widget instance compiles but after change to std::unique_ptr&lt;> gcc gives a compilation error regarding a deleted function. </p> <p>$ uname -a </p> <p>Linux .. 3.5.0-21-generic #32-Ubuntu SMP Tue Dec 11 18:51:59 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux</p> <p>$ g++ --version</p> <p>g++ (Ubuntu/Linaro 4.7.2-5ubuntu1) 4.7.2</p> <p>This code gives the following compiler error:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;memory&gt; class Widget { public: Widget() {} }; class W1 : public Widget { public: W1() {} }; class W2 : public Widget { public: W2() {} }; class WFactory { public: WFactory(const int i) : _w(new W1()) {} WFactory(const char* s) : _w(new W2()) {} ~WFactory() { _w.reset(nullptr); } // ~WFactory() { delete _w; } &lt;--- for naked ptr private: // NOTE: does not compile std::unique_ptr&lt;Widget&gt; _w; // NOTE: does compile // Widget* _w; }; int main() { std::unique_ptr&lt;Widget&gt; a(new W1()); // &lt;--- compiles fine WFactory wf[] { 4, "msg" }; // &lt;--- compiler error using unique_ptr&lt;&gt; } </code></pre> <p>error:</p> <pre><code>$ g++ -o unique_ptr -std=c++11 -Wall unique_ptr.cpp unique_ptr.cpp: In function ‘int main()’: unique_ptr.cpp:36:30: error: use of deleted function ‘WFactory::WFactory(const WFactory&amp;)’ unique_ptr.cpp:22:7: note: ‘WFactory::WFactory(const WFactory&amp;)’ is implicitly deleted because the default definition would be ill-formed: unique_ptr.cpp:22:7: error: use of deleted function ‘std::unique_ptr&lt;_Tp, _Dp&gt;::unique_ptr(const std::unique_ptr&lt;_Tp, _Dp&gt;&amp;) [with _Tp = Widget; _Dp = std::default_delete&lt;Widget&gt;; std::unique_ptr&lt;_Tp, _Dp&gt; = std::unique_ptr&lt;Widget&gt;]’ In file included from /usr/include/c++/4.7/memory:86:0, from unique_ptr.cpp:2: /usr/include/c++/4.7/bits/unique_ptr.h:262:7: error: declared here unique_ptr.cpp:36:30: error: use of deleted function ‘WFactory::WFactory(const WFactory&amp;)’ unique_ptr.cpp:36:14: warning: unused variable ‘wf’ [-Wunused-variable] </code></pre> <p>I'm at a loss as to either: the mechanics behind the scenes that yields a deleted fcxn; or more simply, why the expressiveness of std::unique_ptr&lt;> appears to be restricted compared w/ a naked ptr.</p> <p>My question is:</p> <ul> <li>pilot error?</li> <li>compiler error? </li> <li>can I get my intended code to work w/ some change?</li> </ul> <p>Thank you.</p> <p><strong>Edit 1</strong></p> <p>Based on your answers, which I appreciate, I can make the following change to WFactory:</p> <p>(<strong>flagged as immoral code</strong>)</p> <pre><code>class WFactory { public: WFactory(const WFactory&amp; wf) { (const_cast&lt;WFactory&amp;&gt;(wf)).moveto(_w); } WFactory(const int i) : _w(new W1()) {} WFactory(const char* s) : _w(new W2()) {} ~WFactory() { _w.reset(nullptr); } void moveto(std::unique_ptr&lt;Widget&gt;&amp; w) { w = std::move(_w); } private: std::unique_ptr&lt;Widget&gt; _w; }; </code></pre> <p>and now the program compiles and runs. I appreciate that the standards folks wrote the specification for a reason, so I post my result as a good-faith specialization for my case at hand, where I really would like to emphasize the uniqueness of the ptr. </p> <p><strong>Edit 2</strong></p> <p>Based on Jonathan's replies, the following code does not suppress the implicit move ctor:</p> <pre><code>class WFactory { public: WFactory(const int i) : _w(new W1()) {} WFactory(const char* s) : _w(new W2()) {} private: std::unique_ptr&lt;Widget&gt; _w; }; </code></pre> <p>Note that there is no <code>~WFactory() {..}</code> at all. </p> <p>Perhaps there's ya-ans, but I have found that using a c++11-style iteration over wf[] in Main() brings back the no-copy-ctor-for-WFactory error. That is:</p> <pre><code>int Main() .. WFactory wf[] { 4, "msg" }; for ( WFactory iwf : wf ) &lt;---- compiler error again // .. for (unsigned i = 0; i &lt; 2; ++i) &lt;--- gcc happy wf[i] // .. } </code></pre> <p>I guess it's self-evident that the new c++11-style iteration is doing an object copy. </p>
0
1,770
Tomcat error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists
<p>I have NOT worked on Java, SpringBoot and Maven a lot. I had gone through several posts for the issue mentioned above, but nothing was close to my scenario</p> <p>I compile and package SpringBoot project using <code>Maven with JDK1.8.0_172</code> on Windows 10 </p> <p>I then deploy this packaged war to Linux server (<code>RHEL with JDK1.8.0_201 and Tomcat 8</code>)</p> <p>When I hit the URL <a href="http://localhost:8080/MyApp" rel="nofollow noreferrer">http://localhost:8080/MyApp</a>, tomcat errors and I don't see anything wrong in Tomcat logs</p> <p>I am not sure what I am doing wrong. Any help is highly appreciated</p> <p><strong>Error from Tomcat Server</strong></p> <pre><code>The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. </code></pre> <p><strong>POM.xml file</strong></p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.htc.myapp.main&lt;/groupId&gt; &lt;artifactId&gt;SpringProject&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;properties&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.5.4.RELEASE&lt;/version&gt; &lt;/parent&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.bmc.remedy&lt;/groupId&gt; &lt;artifactId&gt;remedyapi&lt;/artifactId&gt; &lt;version&gt;8.1&lt;/version&gt; &lt;scope&gt;system&lt;/scope&gt; &lt;systemPath&gt;${basedir}/lib/remedyapi-8.1.jar&lt;/systemPath&gt; &lt;/dependency&gt; &lt;!-- JSTL tag lib --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet.jsp.jstl-api&lt;/artifactId&gt; &lt;version&gt;1.2.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;taglibs&lt;/groupId&gt; &lt;artifactId&gt;standard&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa --&gt; &lt;!-- &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; --&gt; &lt;!-- Tomcat for JSP rendering --&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tomcat.embed&lt;/groupId&gt; &lt;artifactId&gt;tomcat-embed-jasper&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt; &lt;version&gt;4.3.8.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.9&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-core&lt;/artifactId&gt; &lt;version&gt;2.8.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;net.sourceforge.jtds&lt;/groupId&gt; &lt;artifactId&gt;jtds&lt;/artifactId&gt; &lt;version&gt;1.3.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; &lt;!-- &lt;dependency&gt; &lt;groupId&gt;net.sourceforge.jtds&lt;/groupId&gt; &lt;artifactId&gt;jtds&lt;/artifactId&gt; &lt;version&gt;1.3.1&lt;/version&gt; &lt;/dependency&gt; --&gt; &lt;!-- &lt;dependency&gt; &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt; &lt;artifactId&gt;httpclient&lt;/artifactId&gt; &lt;version&gt;4.5.3&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt; &lt;/dependency&gt; &lt;!-- &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;version&gt;2.5.3&lt;/version&gt; &lt;/dependency&gt; --&gt; &lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client --&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt; &lt;artifactId&gt;jersey-client&lt;/artifactId&gt; &lt;version&gt;1.19&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-cache&lt;/artifactId&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;MyApp&lt;/finalName&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;procedure&gt;&lt;packaging&gt;war&lt;/packaging&gt;&lt;/properties&gt; &lt;/project&gt; </code></pre> <p><strong>EDIT</strong></p> <p>I installed Tomcat 7 and was able to open the application. However, invoking some action on application throws 'Something went wrong'</p> <p>Looking into Tomcat logs it appears there's some issue with DB connectivity</p> <p><strong>Error on Logs</strong></p> <pre><code>2019-06-19 12:42:55.943 ERROR 20177 --- [bio-8080-exec-3] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool. java.sql.SQLException: No suitable driver found for jdbc:jtds:sqlserver://10.xxx.xxx.xxx:1433/MyDatabase;user=username;password=pwd </code></pre> <p>I copied jtds-1.3.1.jar to $TOMCAT_instance/lib directory and also tried used the following DB settings but <strong>NOTHING</strong> worked</p> <pre><code>db_LMS.url=jdbc:jtds:sqlserver://10.xxx.xxx.xxx:1433;databaseName=MyDatabase;integratedSecurity=true;user=username;password=pwd spring.datasource.driver-class-name=com.mysql.jdbc.Driver db_LMS.url=jdbc:jtds:sqlserver://10.xxx.xxx.xxx:1433/MyDatabase;user=username;password=pwd spring.datasource.driver-class-name=com.mysql.jdbc.Driver </code></pre> <p>Any help on this issue is highly appreciated</p>
0
4,117
Generate SSL Certificate using keytool provide in jdk
<p>Keystore files I have used in my web application expired last week. I generated it long time ago. So I started generating new certificate using keytool. I used this certificate to connect a transaction server and the web server. I wanted to use self signed certificate for this application. I generate it using following command to generate self signed key for transaction server. </p> <pre><code>keytool -genkey -keystore keys/SvrKeyStore -keyalg rsa -validity 365 -alias Svr -storepass 123456 -keypass abcdefg -dname "CN=One1, OU=Development1, O=One, L=Bamba, S=Western Prov1, C=S1" </code></pre> <p>following commnad to generate keystore for web application</p> <pre><code>keytool -genkey -keystore keys/ClientKeyStore -keyalg rsa -validity 365 -alias Web -storepass 123456 -keypass abcdefg -dname "CN=One, OU=Development, O=One, L=Bamba, S=Western Prov, C=SL" </code></pre> <p>I used following code in the transaction server to create the socket connection</p> <pre><code> String KEYSTORE = Config.KEYSTORE_FILE;//SvrKeyStore keystore file char[] KEYSTOREPW = "123456".toCharArray(); char[] KEYPW = "abcdefg".toCharArray(); com.sun.net.ssl.TrustManagerFactory tmf; boolean requireClientAuthentication; java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl. Provider()); java.security.KeyStore keystore = java.security.KeyStore.getInstance( "JKS"); keystore.load(new FileInputStream(KEYSTORE), KEYSTOREPW); com.sun.net.ssl.KeyManagerFactory kmf = com.sun.net.ssl. KeyManagerFactory.getInstance("SunX509"); kmf.init(keystore, KEYPW); com.sun.net.ssl.SSLContext sslc = com.sun.net.ssl.SSLContext. getInstance("SSLv3"); tmf = com.sun.net.ssl.TrustManagerFactory.getInstance("sunx509"); tmf.init(keystore); sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); SSLServerSocketFactory ssf = sslc.getServerSocketFactory(); SSLServerSocket ssocket = (SSLServerSocket) ssf.createServerSocket(port); ssocket.setNeedClientAuth(true); </code></pre> <p>But it gives following exception when I used it in my application and try to connect to the transaction server through web server</p> <pre><code>javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHands hakeException: java.security.cert.CertificateException: Untrusted Server Certifi cate Chain at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.jav a:1172) at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java: 65) at net.schubart.fixme.internal.MessageInput.readExactly(MessageInput.jav a:166) at net.schubart.fixme.internal.MessageInput.readMessage(MessageInput.jav a:78) at cc.aot.itsWeb.ClientWriterThread.run(ClientWriterThread.java:241) at java.lang.Thread.run(Thread.java:619) Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateEx ception: Untrusted Server Certificate Chain at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1 520) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:182) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:176) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Clien tHandshaker.java:975) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHa ndshaker.java:123) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:5 11) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.jav a:449) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.j ava:817) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SS LSocketImpl.java:1029) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl. java:621) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.ja va:59) at java.io.OutputStream.write(OutputStream.java:58) </code></pre> <p>Please can any one tell me where is the problem</p>
0
1,743
How do I fix MainActivity does not have a navcontroller?
<p>I just got my code to compile and when I try to start the app I receive the error. I'm currently trying to setup RecycleView for my class project. My goal is to make the RecycleView show content sorta like the reddit mobile app. I thought my RecycleView named "scrollview1" had a navcontroller setup. Not sure why I'm getting this output</p> <pre><code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.john.chanapi/com.john.chanapi.MainActivity}: java.lang.IllegalStateException: Activity com.john.chanapi.MainActivity@1850938 does not have a NavController set on 2131230866 </code></pre> <p>My MainActivity.kt:</p> <pre><code>package com.john.chanapi import android.os.Bundle import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import androidx.drawerlayout.widget.DrawerLayout import com.google.android.material.navigation.NavigationView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.view.Menu import android.view.View class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val fab: FloatingActionButton = findViewById(R.id.fab) fab.setOnClickListener { view -&gt; Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) val navView: NavigationView = findViewById(R.id.nav_view) val navController = findNavController(R.id.scrollview1) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home, R.id.nav_new, R.id.nav_rising, R.id.nav_top, R.id.nav_inbox, R.id.nav_message ), drawerLayout ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.scrollview1) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } } </code></pre> <p>My activity_main.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"&gt; &lt;include layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" /&gt; &lt;/androidx.drawerlayout.widget.DrawerLayout&gt; </code></pre>
0
1,543
Why is this giving me "Undefined references to constructors and destructors"?
<p>I have the following pieces of code:</p> <p>Leomedia.h</p> <pre><code>#include "MusicMetaDatter.h" #ifndef LEOMEDIA_H #define LEOMEDIA_H namespace Leomedia { typedef enum { read, write } FileMode; } #endif // LEOMEDIA_H </code></pre> <p>MusicMetaDatter.h</p> <pre><code>#ifndef MUSICMETADATTER_H #define MUSICMETADATTER_H #include "Leomedia.h" #include &lt;string&gt; /** * METADATTER * @Version 1.0.0a * @Author: Sergio Andrés Ibañez (Leonnears) * @Twitter: Leonnears * @Package: Leomedia */ namespace Leomedia { typedef enum { mp3, m4a, flac, ape, wavPack, aiff, wav, ogg, tta } AudioFileType; class MusicMetaDatter { public: MusicMetaDatter(std::string fileName, AudioFileType type, FileMode mode); virtual ~MusicMetaDatter(); private: std::string md_fileName; AudioFileType md_fileType; FileMode md_fileMode; }; } #endif // MUSICMETADATTER_H </code></pre> <p>MusicMetaDatter.cpp</p> <pre><code>#include "MusicMetaDatter.h" #include &lt;string&gt; Leomedia::MusicMetaDatter::MusicMetaDatter(std::string fileName, AudioFileType type, FileMode mode) { this -&gt; md_fileName = fileName; this -&gt; md_fileType = type; this -&gt; md_fileMode = mode; } Leomedia::MusicMetaDatter::~MusicMetaDatter() { //dtor } </code></pre> <p>MetaDatterTest.cpp</p> <pre><code>#include &lt;iostream&gt; #include "Leomedia.h" #include &lt;string&gt; using namespace std; int main() { Leomedia::MusicMetaDatter meta("troll", Leomedia::mp3, Leomedia::read); return 0; } </code></pre> <p>When I compile MetaDatterTest I get the following errors:</p> <p>undefined reference to Leomedia::MusicMetaDatter::MusicMetaDatter(std::string, Leomedia::AudioFileType, Leomedia::FileMode)' undefined reference to Leomedia::MusicMetaDatter::~MusicMetaDatter()' undefined reference to Leomedia::MusicMetaDatter::~MusicMetaDatter()'</p> <p>All the files are in the same directory. I'm using mingw 4.4.1</p> <p>Can someone help me with this? It has dumbfounded me beyond understanding.</p>
0
1,089
Flutter Firestore causing D8: Cannot fit requested classes in a single dex file (# methods: 71610 > 65536) in Android Studio
<p>I am attempting to use firestore with a Flutter app in latest version of Android Studio. I have followed these instructions exactly. <a href="https://www.youtube.com/watch?v=DqJ_KjFzL9I&amp;list=PLjxrf2q8roU2HdJQDjJzOeO6J3FoFLWr2&amp;index=9" rel="noreferrer">https://www.youtube.com/watch?v=DqJ_KjFzL9I&amp;list=PLjxrf2q8roU2HdJQDjJzOeO6J3FoFLWr2&amp;index=9</a> I even got them to work last week with a different app. Now I get the following error when I attempt to run my new app after completing all the steps up to (and including) updating pubspec.yaml. Keep in mind, in this example, i am getting the error on a fresh flutter counter app with no other code changes but what you see here.</p> <pre><code>D8: Cannot fit requested classes in a single dex file (# methods: 71610 &gt; 65536) FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. &gt; com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\2.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\3.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\4.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\5.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\6.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\7.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\8.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\9.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\10.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\11.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\12.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\13.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\14.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\15.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\16.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\17.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\18.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\19.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\20.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\21.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\22.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\23.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\24.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\25.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\26.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\27.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\28.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\29.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\30.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\31.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\32.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\33.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\34.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\35.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\36.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\37.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\38.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\39.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\40.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\41.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\42.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\43.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\44.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\45.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\46.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\47.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\48.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\49.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\50.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\51.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\52.jar, C:\Users\DonBo\AndroidStudioProjects\don_flutter_projects\bakery\bakery\build\app\intermediates\transforms\dexBuilder\debug\53.jar The number of method references in a .dex file cannot exceed 64K. Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 21s Finished with error: Gradle task assembleDebug failed with exit code 1 </code></pre> <p>Here is my pubspec file</p> <pre><code>name: bakery description: A new Flutter application. # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # In Android, build-name is used as versionName while build-number used as versionCode. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0+1 environment: sdk: "&gt;=2.1.0 &lt;3.0.0" dependencies: cloud_firestore: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://www.dartlang.org/tools/pub/pubspec # The following section is specific to Flutter. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.io/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.io/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.io/custom-fonts/#from-packages </code></pre> <p>Here is my app level gradle file</p> <pre><code>def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -&gt; localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 28 lintOptions { disable 'InvalidPackage' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.boody.sag.bakery" minSdkVersion 16 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } apply plugin: 'com.google.gms.google-services' </code></pre> <p>Here is my android level gradle file</p> <pre><code>buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' classpath 'com.google.gms:google-services:3.2.0' } } allprojects { repositories { google() jcenter() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } </code></pre>
0
4,764
Angular Material - Filter Table by multiple filters and multiple filter values at the same time
<p>I'm trying to be able to have two different filters for a table of objects. The first one is a normal text/input based filter and works as expected.</p> <p>The second one I'm trying to get working is a row of checkboxes labeled &quot;Level 1&quot;, &quot;Level 2&quot;, etc. On checking a checkbox I want to filter by the column &quot;level&quot; all of the currently checked checkboxes. Ideally the user could filter the table by both the text and level selection</p> <p>I've read about using filterPredicate and tried to use <a href="https://stackblitz.com/edit/angular-hbakxo-5jeaic?file=app%2Ftable-filtering-example.ts" rel="nofollow noreferrer">this as a template</a> but I must be missing something.</p> <p>Current code snippet:</p> <p>HTML:</p> <pre><code>//Input for text filter &lt;mat-form-field &gt; &lt;input matInput (keyup)=&quot;applyFilter($event.target.value)&quot; placeholder=&quot;Filter...&quot;&gt; &lt;/mat-form-field&gt; ... //Checkboxes for level filter &lt;div fxLayout=&quot;row&quot; fxLayoutAlign=&quot;space-between center&quot; class=&quot;margin-1&quot;&gt; &lt;mat-checkbox (change)=&quot;customFilterPredicate()&quot; [(ngModel)]=&quot;level.active&quot; *ngFor=&quot;let level of levelsToShow&quot;&gt;{{level.level}}&lt;/mat-checkbox&gt; &lt;/div&gt; </code></pre> <p>TS</p> <pre><code>ngOnInit() { this.dataSource.filterPredicate = this.customFilterPredicate(); } ... applyFilter(filterValue: string) { this.dataSource.filter = filterValue.trim().toLowerCase(); } customFilterPredicate() { const myFilterPredicate = (data): boolean =&gt; { return this.levelsToShow.some(data['level'].toString().trim()); }; return myFilterPredicate; } </code></pre> <h2>Update</h2> <p>So far I was able to make some progress thanks to Fabian Küng but am still not home free. To clarify I'm hoping to have the text filter be able to search through multiple columns ('castingTime', 'duration', etc), and have the checkboxes only filter by level.</p> <p>As of right now when I click on a checkbox I get this error: 'Cannot read property 'toLowerCase' of undefined' that points to this line of code:</p> <pre><code>return data['level'].toString().trim().toLowerCase().indexOf(searchString.name.toLowerCase()) !== -1 &amp;&amp; </code></pre> <p>but when I console log out data I can see that it has a level property, so I'm not seeing where I'm going wrong.</p> <p>Here are the relevant code snippets:</p> <pre><code> HTML: &lt;input matInput (keyup)=&quot;applyFilter($event.target.value)&quot; placeholder=&quot;Filter...&quot; [formControl]=&quot;textFilter&quot;&gt; &lt;mat-checkbox (change)=&quot;updateFilter()&quot; [(ngModel)]=&quot;level.active&quot; *ngFor=&quot;let level of levelsToShow&quot;&gt;{{level.name}}&lt;/mat-checkbox&gt; TS: levelsToShow: Level[] = [ { level: '1', active: false, name: 'Level 1' }, { level: '2', active: false, name: 'Level 2' }, { level: '3', active: false, name: 'Level 3' }, { level: '4', active: false, name: 'Level 4' }, { level: '5', active: false, name: 'Level 5' }, { level: '6', active: false, name: 'Level 6' }, { level: '7', active: false, name: 'Level 7' }, { level: '8', active: false, name: 'Level 8' }, { level: '9', active: false, name: 'Level 9' } ]; levelFilter = new FormControl(); textFilter = new FormControl(); globalFilter = ''; filteredValues = { level: '', text: '', }; ngOnInit() { ... this.textFilter.valueChanges.subscribe((textFilterValue) =&gt; { this.filteredValues['text'] = textFilterValue; this.dataSource.filter = JSON.stringify(this.filteredValues); }); this.dataSource.filterPredicate = this.customFilterPredicate(); } customFilterPredicate() { const myFilterPredicate = (data: Spell, filter: string): boolean =&gt; { var globalMatch = !this.globalFilter; if (this.globalFilter) { // search all text fields globalMatch = data['spellName'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['level'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['castingTime'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['distance'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['details'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['duration'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['school'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['effect'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1; } if (!globalMatch) { return; } let searchString = JSON.parse(filter); return data['level'].toString().trim().toLowerCase().indexOf(searchString.name.toLowerCase()) !== -1 &amp;&amp; (this.levelsToShow.filter(level =&gt; !level.active).length === this.levelsToShow.length || this.levelsToShow.filter(level =&gt; level.active).some(level =&gt; level.level === data.level.toString())); } return myFilterPredicate; } updateFilter() { this.dataSource.filter = JSON.stringify(this.filteredValues); } </code></pre> <h2>Update II</h2> <p>As requested here is an example of one of the table rows: (this is for a d&amp;d table of spells)</p> <pre><code>{ castingTime: &quot;1 half action&quot; distance: &quot;Short range attack&quot; duration: &quot;1 round per Casting Level&quot; effect: &quot;Once per round, you may take a half action to launch an arrow of acid from your palm, generating a new Spellcasting result to see if you hit.Each arrow inflicts 1d6 acid damage.↵ &quot; index: 0 level: &quot;4&quot; school: &quot;Creation&quot; spellName: &quot;ACID ARROW&quot; } </code></pre> <h2>Final Update</h2> <p>This is what I ended up with in case anyone gets stuck. Thanks to Fabian Küng for figuring all this out! The only weird thing of note is that I ended up using the actual value of the text input &quot;textFilter&quot; because stringifying the text filteredValues and then parsing them (the filter only accepts strings as far as I can tell) kept giving me &quot;JSON error, unexpected value at 0&quot; messages and as far as I can tell this will work fine EXCEPT now I need to figure out how to throttle the filter.</p> <pre><code>customFilterPredicate() { const myFilterPredicate = (data: Spell, filter: string): boolean =&gt; { var globalMatch = !this.globalFilter; if (this.globalFilter) { // search all text fields globalMatch = data['spellName'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['level'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['castingTime'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['distance'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['details'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['duration'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['school'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1 || data['effect'].toString().trim().toLowerCase().indexOf(this.globalFilter.toLowerCase()) !== -1; } if (!globalMatch) { return; } return data.spellName.toString().trim().toLowerCase().indexOf(this.textFilter.value) !== -1 &amp;&amp; (this.levelsToShow.filter(level =&gt; !level.active).length === this.levelsToShow.length || this.levelsToShow.filter(level =&gt; level.active).some(level =&gt; level.level === data.level.toString())); } return myFilterPredicate; } </code></pre>
0
3,340
Adding new rows to table on clicking button in JQuery
<p>I am pretty new to jquery. I have the following code. Here I want to get new rows in the table by clicking the add button, but I can't get it.,</p> <p>can someone tell me what mistake I have done here?</p> <pre><code>&lt;script type="text/javascript"&gt; var $ = jQuery.noConflict(); $("#addrows").click(function () { if (document.getElementById("hiddenprice").value == "") { imagecounter = 4; } else { imagecounter = parseFloat(document.getElementById("hiddenprice").value) +1; } //imagecounter=4; var newImageDiv = $(document.createElement('div')) .attr("id", 'add_div' + imagecounter); newImageDiv.after().html('&lt;table width="100%" cellpadding="0" cellspacing="0" class="pdzn_tbl1" border="0"&gt;' + '&lt;tr&gt;&lt;td&gt;&lt;input type="text" name="rollno&lt;? $i ?&gt;"/&gt;&lt;/td&gt;' + '&lt;td&gt;&lt;input type="text" name="firstname&lt;? $i ?&gt;" /&gt;&lt;/td&gt;' + '&lt;td&gt;&lt;input type="text" name="lastname&lt;? $i ?&gt;" /&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;'); newImageDiv.appendTo("#addgroup"); $("tr:last").after(newImageDiv); document.getElementById("hiddenprice").value = imagecounter; imagecounter++; }); &lt;/script&gt; &lt;div class="common" style="width:1040px; -overflow-x:scroll; padding: 5px 5px 0 5px;"&gt; &lt;table id="maintable" width="50%" cellpadding="0" cellspacing="0" class="pdzn_tbl1" border="#729111 1px solid" &gt; &lt;tr&gt; &lt;th&gt;Roll No&lt;/th&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;/tr&gt; &lt;?php $t_row=3; for($i=1;$i&lt;=$t_row;$i++) { ?&gt; &lt;tr id="rows"&gt; &lt;div&gt; &lt;td&gt;&lt;input type="text" name="rollno&lt;? $i ?&gt;"/&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="firstname&lt;? $i ?&gt;"/&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="text" name="lastname&lt;? $i ?&gt;"/&gt;&lt;/td&gt; &lt;/div&gt; &lt;/tr&gt; &lt;? } ?&gt; &lt;div id="addgroup"&gt; &lt;div id="add_div1"&gt; &lt;/div&gt; &lt;/div&gt; &lt;table&gt; &lt;input type="button" name="add" value="+Add" id="addrows" /&gt; &lt;input type="hidden" id="hiddenprice" name="hiddenprice" value="3"/&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p><strong>Code Formatted &amp; Edit</strong>: Code alignments updated and removed unwanted style codes for better readability</p>
0
1,078
Java: package cucumber.api.junit does not exist
<p>I've been trying to get this to work. </p> <p>I would like set up a test runner class <a href="https://cucumber.io/docs/reference/jvm" rel="nofollow noreferrer">like so</a></p> <p>However I get this error:</p> <blockquote> <p>Error:(3, 26) java: package cucumber.api.junit does not exist<br> Error:(10, 10) java: cannot find symbol<br> symbol: class Cucumber</p> </blockquote> <p>The class looks like:</p> <pre><code>package nl.prvgld.sigma.aanvraagtitels.testutil; import cucumber.api.junit.Cucumber; import org.junit.runner.RunWith; @RunWith(Cucumber.class) public class RunFeature { } </code></pre> <p>Pom.xml looks like:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;nl.prvgld.sigma.aanvraagtitels&lt;/groupId&gt; &lt;artifactId&gt;Aanvraagtitels&lt;/artifactId&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;name&gt;Aanvraagtitels&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;dependencies&gt; &lt;!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --&gt; &lt;dependency&gt; &lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt; &lt;artifactId&gt;selenium-java&lt;/artifactId&gt; &lt;version&gt;3.2.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.12&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java --&gt; &lt;dependency&gt; &lt;groupId&gt;info.cukes&lt;/groupId&gt; &lt;artifactId&gt;cucumber-java8&lt;/artifactId&gt; &lt;version&gt;1.2.5&lt;/version&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/info.cukes/cucumber-core --&gt; &lt;dependency&gt; &lt;groupId&gt;info.cukes&lt;/groupId&gt; &lt;artifactId&gt;cucumber-core&lt;/artifactId&gt; &lt;version&gt;1.2.5&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit --&gt; &lt;dependency&gt; &lt;groupId&gt;info.cukes&lt;/groupId&gt; &lt;artifactId&gt;cucumber-junit&lt;/artifactId&gt; &lt;version&gt;1.2.5&lt;/version&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc --&gt; &lt;dependency&gt; &lt;groupId&gt;com.microsoft.sqlserver&lt;/groupId&gt; &lt;artifactId&gt;mssql-jdbc&lt;/artifactId&gt; &lt;version&gt;6.1.0.jre8&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.smartbear.readyapi.testserver.cucumber&lt;/groupId&gt; &lt;artifactId&gt;testserver-cucumber-core&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre> <p>All classes are somewhere under the Test folder. I've been lookin at some related questions here and tried the solutions like removing test from Pom, and making sure I have junit, cucumber-junit, cucumber-java8 and cucumber-core in the Pom. </p> <p>I am using Intellij.</p> <p>Any help in the right direction is highly appreciated!</p> <p>Cheers!</p>
0
2,140
Doctrine 2 - No Metadata Classes to process by orm:generate-repositories
<p>I'm trying to generate entity repositories and getting such message </p> <p><strong>No Metadata Classes to process</strong></p> <p>I'd tracked down that use of </p> <p>use Doctrine\ORM\Mapping as ORM; and @ORM\Table is not working properly. </p> <p>If i change all @ORM\Table to just @Table(and other annotations) - it start to work, but I really don't want to get it that way as it should work with @ORM annotation. </p> <p>I followed instructions from page below with no luck. I know I'm close but missing something with file paths or namespaces. Please help. </p> <p><a href="http://docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/annotations.html" rel="noreferrer">http://docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/annotations.html</a></p> <p>Does anyone had such problem? What I missing?</p> <p>cli-config, </p> <pre><code>use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationRegistry; require_once 'Doctrine/Common/ClassLoader.php'; define('APPLICATION_ENV', "development"); error_reporting(E_ALL); //AnnotationRegistry::registerFile("Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php"); //AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "Doctrine/Symfony"); //AnnotationRegistry::registerAutoloadNamespace("Annotations", "/Users/ivv/workspaceShipipal/shipipal/codebase/application/persistent/"); $classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); $classLoader-&gt;register(); $classLoader = new \Doctrine\Common\ClassLoader('Entities', __DIR__ . '/application/'); $classLoader-&gt;register(); $classLoader = new \Doctrine\Common\ClassLoader('Proxies', __DIR__ . '/application/persistent'); $classLoader-&gt;register(); $config = new \Doctrine\ORM\Configuration(); $config-&gt;setProxyDir(__DIR__ . '/application/persistent/Proxies'); $config-&gt;setProxyNamespace('Proxies'); $config-&gt;setAutoGenerateProxyClasses((APPLICATION_ENV == "development")); $driverImpl = $config-&gt;newDefaultAnnotationDriver(array(__DIR__ . "/application/persistent/Entities")); $config-&gt;setMetadataDriverImpl($driverImpl); if (APPLICATION_ENV == "development") { $cache = new \Doctrine\Common\Cache\ArrayCache(); } else { $cache = new \Doctrine\Common\Cache\ApcCache(); } $config-&gt;setMetadataCacheImpl($cache); $config-&gt;setQueryCacheImpl($cache); $connectionOptions = array( 'driver' =&gt; 'pdo_mysql', 'host' =&gt; '127.0.0.1', 'dbname' =&gt; 'mydb', 'user' =&gt; 'root', 'password' =&gt; '' ); $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config); $platform = $em-&gt;getConnection()-&gt;getDatabasePlatform(); $platform-&gt;registerDoctrineTypeMapping('enum', 'string'); $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array( 'db' =&gt; new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em-&gt;getConnection()), 'em' =&gt; new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) )); </code></pre> <p>User.php(working version, initially it was as described, @Table was @ORM\Table and other annotations similar had @ORM\ part like @ORM\Column etc)</p> <pre><code>&lt;?php namespace Entities; use Doctrine\Mapping as ORM; /** * User * * @Table(name="user") * @Entity(repositoryClass="Repository\User") */ class User { /** * @var integer $id * * @Column(name="id", type="integer", nullable=false) * @Id * @GeneratedValue */ private $id; /** * @var string $userName * * @Column(name="userName", type="string", length=45, nullable=false) */ private $userName; /** * @var string $email * * @Column(name="email", type="string", length=45, nullable=false) */ private $email; /** * @var text $bio * * @Column(name="bio", type="text", nullable=true) */ private $bio; public function __construct() { } } </code></pre>
0
1,501
Gradle refuse to start process command 'cmd'
<p>I'm encountering issue with a custom gradle task. Seems like gradle refuse to start a command line process.</p> <p>Here is the custom task:</p> <pre><code>task generateAllure(type: Exec) { workingDir "$projectDir/allure/bin" if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) { commandLine 'cmd', '/c', 'allure.bat', 'generate', '-c', '../../integration/build/allure-results' } else { commandLine 'bash', '-c', 'allure', 'generate', '-c',"$projectDir/integration/build/allure-results" } } tasks.withType(Test)*.finalizedBy generateAllure </code></pre> <p>With the appropriate dependency:</p> <pre><code>compile group: 'ru.yandex.qatools.allure', name: 'allure-commandline', version: '1.4.18' </code></pre> <p>After using <code>gradle clean test</code> execution fails on:</p> <pre><code>2: Task failed with an exception. ----------- * What went wrong: Execution failed for task ':generateAllure'. &gt; A problem occurred starting process 'command 'cmd'' </code></pre> <p>Any thoughts about that? Thanks!</p> <p>UPD: This is the stacktrace i'm getting after performing gradle -S clean test:</p> <pre><code>* Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':generateAllure'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77) at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59) at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101) at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44) at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91) at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51) at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317) at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309) at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185) at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:97) at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$ExecuteTaskAction.execute(DefaultTaskExecutionGraph.java:262) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$ExecuteTaskAction.execute(DefaultTaskExecutionGraph.java:246) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:136) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.execute(DefaultTaskPlanExecutor.java:201) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.executeWithTask(DefaultTaskPlanExecutor.java:192) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:130) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55) at java.lang.Thread.run(Thread.java:748) Caused by: org.gradle.process.internal.ExecException: A problem occurred starting process 'command 'cmd'' at org.gradle.process.internal.DefaultExecHandle.execExceptionFor(DefaultExecHandle.java:231) at org.gradle.process.internal.DefaultExecHandle.setEndStateInfo(DefaultExecHandle.java:209) at org.gradle.process.internal.DefaultExecHandle.failed(DefaultExecHandle.java:355) at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:85) at org.gradle.internal.operations.CurrentBuildOperationPreservingRunnable.run(CurrentBuildOperationPreservingRunnable.java:42) ... 6 more Caused by: net.rubygrapefruit.platform.NativeException: Could not start 'cmd' at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:27) at net.rubygrapefruit.platform.internal.WindowsProcessLauncher.start(WindowsProcessLauncher.java:22) at net.rubygrapefruit.platform.internal.WrapperProcessLauncher.start(WrapperProcessLauncher.java:36) at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:67) ... 7 more Caused by: java.io.IOException: Cannot run program "cmd" (in directory "D:\Git\rozetka-test-automation\allure\bin"): CreateProcess error=267, The directory name is invalid at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:25) ... 10 more Caused by: java.io.IOException: CreateProcess error=267, The directory name is invalid at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.&lt;init&gt;(ProcessImpl.java:386) at java.lang.ProcessImpl.start(ProcessImpl.java:137) at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) ... 11 more </code></pre>
0
2,598
Autowiring not working in Spring 3.1.2, JUnit 4.10.0
<p>Using Spring 3.1.2, JUnit 4.10.0, and pretty new to both versions. I'm having the problem that I can't get the annotation-based autowiring to work.</p> <p>Below are two samples, the one not using annotations, which is working fine. And the second one using annotation, which doesn't work, and I don't find the reason. I followed the samples of spring-mvc-test pretty much.</p> <p><strong>Working</strong>:</p> <pre><code>package com.company.web.api; // imports public class ApiTests { @Test public void testApiGetUserById() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("/com/company/web/api/ApiTests-context.xml"); UserManagementService userManagementService = (UserManagementService) ctx.getBean("userManagementService"); ApiUserManagementController apiUserManagementController = new ApiUserManagementController(userManagementService); MockMvc mockMvc = standaloneSetup(apiUserManagementController).build(); // The actual test mockMvc.perform(get("/api/user/0").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); } } </code></pre> <p><strong>Failing</strong>, because <code>userManagementService</code> is null, not getting autowired:</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration // should default to ApiTests-context.xml in same package public class ApiTests { @Autowired UserManagementService userManagementService; private MockMvc mockMvc; @Before public void setup(){ // SetUp never gets called?! } @Test public void testGetUserById() throws Exception { // !!! at this point, userManagementService is still null - why? !!! ApiUserManagementController apiUserManagementController = new ApiUserManagementController(userManagementService); mockMvc = standaloneSetup(apiUserManagementController).build(); // The actual test mockMvc.perform(get("/api/user/0").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); } } </code></pre> <p>Note that both test classes above should be using the same context configuration, and the userManagementService is defined in there.</p> <p>ApiTests-context.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" 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.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;property name="driverClassName" value="com.mysql.jdbc.Driver"/&gt; &lt;property name="url" value="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;amp;characterEncoding=utf8"/&gt; &lt;property name="username" value="user"/&gt; &lt;property name="password" value="passwd"/&gt; &lt;/bean&gt; &lt;!-- Hibernate SessionFactory --&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingResources="company.hbm.xml"&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;${hibernate.dialect}&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;${hibernate.show_sql}&lt;/prop&gt; &lt;prop key="hibernate.generate_statistics"&gt;${hibernate.generate_statistics}&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="eventListeners"&gt; &lt;map&gt; &lt;entry key="merge"&gt; &lt;bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/&gt; &lt;/entry&gt; &lt;/map&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/&gt; &lt;!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= --&gt; &lt;context:annotation-config/&gt; &lt;tx:annotation-driven/&gt; &lt;context:mbean-export/&gt; &lt;!-- tried both this and context:component-scan --&gt; &lt;!--&lt;bean id="userManagementService" class="com.company.web.hibernate.UserManagementServiceImpl"/&gt;--&gt; &lt;context:component-scan base-package="com.company"/&gt; &lt;!-- Hibernate's JMX statistics service --&gt; &lt;bean name="application:type=HibernateStatistics" class="org.hibernate.jmx.StatisticsService" autowire="byName"/&gt; &lt;/beans&gt; </code></pre> <p>and the UserManagementService (interface) as well as UserManagementServiceImpl has the <code>@Service</code> annotation.</p> <p>Two minor questions/observations: setup() never gets called, even though it has the @Before annotation. Furthermore, I noticed that my test methods don't get executed/recognized if they don't start with the name 'test', which is not the case though with all spring-mvc-test samples I saw.</p> <p>pom.xml:</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;org.junit&lt;/groupId&gt; &lt;artifactId&gt;com.springsource.org.junit&lt;/artifactId&gt; &lt;version&gt;4.10.0&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p><img src="https://i.stack.imgur.com/uma4p.png" alt="enter image description here"></p> <p><strong>Update:</strong></p> <p>The problem only occurs when I run the tests from maven; it's ok when I run the test from within my IDE (IntelliJ IDEA).</p> <pre><code> &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.12.3&lt;/version&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;**/*Tests.java&lt;/include&gt; &lt;/includes&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre>
0
2,836
How to add title to the custom Dialog?
<p>How can i add title to this custom dialog??</p> <p><img src="https://i.stack.imgur.com/luw1g.jpg" alt="enter image description here"></p> <p>I have tried like this</p> <pre><code>public void customDialog() { Dialog dialog=new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); dialog.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.string.app_name ); dialog.setContentView(R.layout.dialog_submit); TextView edit_model=(TextView) dialog.findViewById(R.id.edit_model); edit_model.setText(android.os.Build.DEVICE); dialog.show(); }//end of custom dialog function </code></pre> <p>I have tried to set title like this too..<code>dialog.setTitle("Enter Details");</code> but this too didn't yielded any result. So how can i set title to this custom dialog??</p> <p>This is my dialog_submit.xml file used for the custom dialog.</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_root" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" &gt; &lt;TextView android:id="@+id/txt_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFF" android:text="Name" android:textStyle="bold" /&gt; &lt;EditText android:id="@+id/edit_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/txt_name" /&gt; &lt;TextView android:id="@+id/txt_model" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFF" android:layout_below="@+id/edit_name" android:text="Phone Model" /&gt; &lt;TextView android:id="@+id/edit_model" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/txt_model" /&gt; &lt;Button android:id="@+id/but_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/edit_model" android:text="Cancel" /&gt; &lt;Button android:id="@+id/but_submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/edit_model" android:layout_toRightOf="@+id/but_cancel" android:text="Submit" /&gt; &lt;/RelativeLayout&gt; </code></pre>
0
1,226
CMake: create_symlink vs ln
<p>I have a macro to create links E.g.</p> <pre><code>makeLink($BUILD_ROOT/lib somewhere/somelibrary.so makelinks) </code></pre> <p>The purpose of this is so that a completed build includes a directory structure analogous to a developers installation with <em>bin</em>, <em>include</em> &amp; <em>lib</em> directories containing links to the actual products.</p> <p><em>However, the purpose is not relevant to my question which is about create_symlink and not a meta-question about whether links should be used for this or any other purpose.</em></p> <p>The macro can be implemented in several ways including:</p> <pre><code>macro(makeLink src dest target) add_custom_command(TARGET ${target} PRE_BUILD COMMAND ln -sf ${src} ${dest} DEPENDS ${dest} COMMENT &quot;mklink ${src} -&gt; ${dest}&quot;) endmacro() </code></pre> <p>or:</p> <pre><code>macro(makeLink src dest target) add_custom_command(TARGET ${target} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E create_symlink ${src} ${dest} DEPENDS ${dest} COMMENT &quot;mklink ${src} -&gt; ${dest}&quot;) endmacro() </code></pre> <p>Now I understand the point of create_symlink is to be portable in case the platform doesn't understand links. However it seems to be functionally incomplete. There are several different use cases with <em>ln</em></p> <ul> <li>create a link whether the source exists yet or not</li> <li>create a link only if the source exists</li> <li>overwrite an existing link or not</li> </ul> <p>As far as I can see the cmake documentation under-specifies the behaviour (its actually: create the link if the destination doesn't exist and the source exists. Fail if the source doesn't exist)</p> <p><a href="https://cmake.org/cmake/help/v3.2/manual/cmake.1.html" rel="nofollow noreferrer">https://cmake.org/cmake/help/v3.2/manual/cmake.1.html</a></p> <p>This seems possibly to confuse many users who think it ought to work according to one and only one of the possibly use cases. E.g.</p> <p><a href="https://cmake.org/Bug/view.php?id=14928" rel="nofollow noreferrer">https://cmake.org/Bug/view.php?id=14928</a> <a href="https://cmake.org/Bug/print_bug_page.php?bug_id=4418" rel="nofollow noreferrer">https://cmake.org/Bug/print_bug_page.php?bug_id=4418</a></p> <p><em>Given this why should anyone ever use create_symlink? Wouldn't the sensible course be to incorporate support for all the common use cases (essentially by implementing a system portable wrapper to ln)?</em> <strong>Is there a semi-standard .cmake file for this somewhere?</strong></p> <p>Also is cmake really doing a recursive call to fork itself when you use cmake -E or does the parser recognise it as a special case. I suspect the latter as seems very fast (granted creating links this way would still seem fast) but if that's so why the unnecessarily verbose syntax?</p> <hr /> <p>Note: I am not building the libraries as part of configure. <em>links</em> to libraries are created to support two things:</p> <ul> <li>linking programs that use the libraries in other sub-projects</li> <li>running tests that use the libraries</li> </ul> <p>The libraries are not actually being built during the 'configure' stage. The links only need to be available just in time. This is part of a migration from a configure/make based build system to cmake/ninja. Its a largish project where a phased roll out of cmake is preferable to a big bang. It just so happens that in the existing system the links are made at configure time (though not used until build time).</p>
0
1,088
Cannot load configuration class error spring boot
<p>I am working on a spring boot project where I am integrating my api with google calendar api.While running the application I am getting this error:</p> <pre><code>java.lang.IllegalStateException: Cannot load configuration class: com.api.GoogleCalApplication at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:403) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:249) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:281) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:125) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:524) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at com.api.GoogleCalApplication.main(GoogleCalApplication.java:10) ~[classes/:na] Caused by: java.lang.ExceptionInInitializerError: null at org.springframework.context.annotation.ConfigurationClassEnhancer.newEnhancer(ConfigurationClassEnhancer.java:122) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:110) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:393) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] ... 12 common frames omitted Caused by: java.lang.IllegalStateException: Unable to load cache item at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:79) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.KeyFactory$Generator.create(KeyFactory.java:221) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.KeyFactory.create(KeyFactory.java:174) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.KeyFactory.create(KeyFactory.java:153) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.proxy.Enhancer.&lt;clinit&gt;(Enhancer.java:73) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] ... 15 common frames omitted Caused by: java.lang.ExceptionInInitializerError: null at org.springframework.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:243) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:329) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na] at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] ... 22 common frames omitted Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not &quot;opens java.lang&quot; to unnamed module @7a1ebcd8 at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:357) ~[na:na] at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297) ~[na:na] at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:199) ~[na:na] at java.base/java.lang.reflect.Method.setAccessible(Method.java:193) ~[na:na] at org.springframework.cglib.core.ReflectUtils$1.run(ReflectUtils.java:54) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] at java.base/java.security.AccessController.doPrivileged(AccessController.java:312) ~[na:na] at org.springframework.cglib.core.ReflectUtils.&lt;clinit&gt;(ReflectUtils.java:44) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE] ... 30 common frames omitted 2021-07-26 14:09:13.625 INFO 8492 --- [ main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7bedc48a: startup date [Mon Jul 26 14:09:12 IST 2021]; root of context hierarchy 2021-07-26 14:09:13.636 WARN 8492 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception thrown from LifecycleProcessor on context close java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7bedc48a: startup date [Mon Jul 26 14:09:12 IST 2021]; root of context hierarchy at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:417) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1002) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:961) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:794) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:325) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at com.api.GoogleCalApplication.main(GoogleCalApplication.java:10) ~[classes/:na] 2021-07-26 14:09:13.638 ERROR 8492 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7bedc48a: startup date [Mon Jul 26 14:09:12 IST 2021]; root of context hierarchy at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1009) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:961) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:794) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:325) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at com.api.GoogleCalApplication.main(GoogleCalApplication.java:10) ~[classes/:na] </code></pre> <p>Here's my controller:</p> <pre><code>package com.api.controllers; import java.io.IOException; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.view.RedirectView; import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.Details; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.DateTime; import com.google.api.services.calendar.Calendar.Events; import com.google.api.services.calendar.CalendarScopes; import com.google.api.services.calendar.model.Event; @Controller public class GoogleCalController { private final static Log logger = LogFactory.getLog(GoogleCalController.class); private static final String APPLICATION_NAME = &quot;&quot;; private static HttpTransport httpTransport; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static com.google.api.services.calendar.Calendar client; GoogleClientSecrets clientSecrets; GoogleAuthorizationCodeFlow flow; Credential credential; @Value(&quot;${google.client.client-id}&quot;) private String clientId; @Value(&quot;${google.client.client-secret}&quot;) private String clientSecret; @Value(&quot;${google.client.redirectUri}&quot;) private String redirectURI; private Set&lt;Event&gt; events = new HashSet&lt;&gt;(); final DateTime date1 = new DateTime(&quot;2020-07-26T16:30:00.000+05:30&quot;); final DateTime date2 = new DateTime(new Date()); public void setEvents(Set&lt;Event&gt; events) { this.events = events; } @RequestMapping(value = &quot;/login/google&quot;, method = RequestMethod.GET) public RedirectView googleConnectionStatus(HttpServletRequest request) throws Exception { return new RedirectView(authorize()); } @RequestMapping(value = &quot;/login/google&quot;, method = RequestMethod.GET, params = &quot;code&quot;) public ResponseEntity&lt;String&gt; oauth2Callback(@RequestParam(value = &quot;code&quot;) String code) { com.google.api.services.calendar.model.Events eventList; String message; try { TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectURI).execute(); credential = flow.createAndStoreCredential(response, &quot;userID&quot;); client = new com.google.api.services.calendar.Calendar.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); Events events = client.events(); eventList = events.list(&quot;primary&quot;).setTimeMin(date1).setTimeMax(date2).execute(); message = eventList.getItems().toString(); System.out.println(&quot;My:&quot; + eventList.getItems()); } catch (Exception e) { logger.warn(&quot;Exception while handling OAuth2 callback (&quot; + e.getMessage() + &quot;).&quot; + &quot; Redirecting to google connection status page.&quot;); message = &quot;Exception while handling OAuth2 callback (&quot; + e.getMessage() + &quot;).&quot; + &quot; Redirecting to google connection status page.&quot;; } System.out.println(&quot;cal message:&quot; + message); return new ResponseEntity&lt;&gt;(message, HttpStatus.OK); } public Set&lt;Event&gt; getEvents() throws IOException { return this.events; } private String authorize() throws Exception { AuthorizationCodeRequestUrl authorizationUrl; if (flow == null) { Details web = new Details(); web.setClientId(clientId); web.setClientSecret(clientSecret); clientSecrets = new GoogleClientSecrets().setWeb(web); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)).build(); } authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectURI); System.out.println(&quot;cal authorizationUrl-&gt;&quot; + authorizationUrl); return authorizationUrl.build(); } } </code></pre> <p>Here's my app starting point:</p> <pre><code>package com.api; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GoogleCalApplication { public static void main(String[] args) { SpringApplication.run(GoogleCalApplication.class, args); } } </code></pre> <p>How to solve it?I am stuck for hours now.I have all the dependencies installed.</p> <p>Here's my pom.xml</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.app&lt;/groupId&gt; &lt;artifactId&gt;google-calendar-api&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;google-calendar-api&lt;/name&gt; &lt;description&gt;Demo Project for Google Calendar Api&lt;/description&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.5.2.RELEASE&lt;/version&gt; &lt;relativePath /&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-configuration-processor&lt;/artifactId&gt; &lt;optional&gt;true&lt;/optional&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client --&gt; &lt;!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-calendar --&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.apis&lt;/groupId&gt; &lt;artifactId&gt;google-api-services-calendar&lt;/artifactId&gt; &lt;version&gt;v3-rev224-1.22.0&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Gmail Maven Dependency--&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.apis&lt;/groupId&gt; &lt;artifactId&gt;google-api-services-gmail&lt;/artifactId&gt; &lt;version&gt;v1-rev65-1.18.0-rc&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.apis&lt;/groupId&gt; &lt;artifactId&gt;google-api-services-calendar&lt;/artifactId&gt; &lt;version&gt;v3-rev411-1.25.0&lt;/version&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;fork&gt;true&lt;/fork&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>all my client keys and secret are in resources application.properties file from where I am refering all my variables like clientId and all.While running the application I straight away get this error.How to solve it?</p>
0
8,159
Pass parameter to subquery
<p>I'm using SSRS/SSDT in Visual Studio 2015 and SQL Server 2014. There's a bug that's been present for > 8 years where <a href="https://stackoverflow.com/questions/14466874/in-ssrs-why-do-i-get-the-error-item-with-same-key-has-already-been-added-wh">you can't select multiple columns from different tables that have the same name</a>. To get around this, I need to use a subquery. Every single answer I find rewrites the given query to remove the subquery, which would normally be great but <strong>is not applicable in this case</strong>. How do I pass a parameter to a subquery in SQL Server?</p> <p>Column aliases do not work with this bug--Using <code>AS</code> returns an unknown column error on the "duplicate" columns even though it works with all others. The last two lines in the <code>SELECT</code> clause work because the values are being queried so the report can use them, but the remainder of the actual query doesn't use them.</p> <p>Here's my current code (doesn't work because the subquery returns multiple rows).</p> <pre><code>SELECT t.[Description], t.RequestedCompletionDate, t.CommitDate, t.StatusId, t.PriorityId, p.ProjectNumber, s.Name AS StatusDescription, pr.Name AS PriorityDescription FROM ProjectTask t inner join Project p on p.Id = t.ProjectId inner join Project_TaskStatus s on s.Id = t.StatusId inner join Project_Priority pr on pr.Id = t.PriorityId WHERE t.Type = 'ET' AND t.StatusId NOT IN (4,7) AND ( SELECT StatusId FROM Project -- WHERE ? ) NOT IN (3, 4) ORDER BY t.PriorityId, t.CommitDate, t.RequestedCompletionDate </code></pre> <p>This is the code with aliases as requested in the comments. It throws an error:</p> <pre><code>SELECT t.[Description], t.RequestedCompletionDate, t.CommitDate, t.StatusId AS TaskStatusId, t.PriorityId, p.ProjectNumber, p.StatusId AS ProjectStatusId, s.Name AS StatusDescription, pr.Name AS PriorityDescription FROM ProjectTask t inner join Project p on p.Id = t.ProjectId inner join Project_TaskStatus s on s.Id = TaskStatusId inner join Project_Priority pr on pr.Id = t.PriorityId WHERE t.Type = 'ET' AND TaskStatusId NOT IN (4,7) AND ProjectStatusId NOT IN (3,4) ORDER BY t.PriorityId, t.CommitDate, t.RequestedCompletionDate -- Invalid column name 'TaskStatusId'. -- Invalid column name 'TaskStatusId'. -- Invalid column name 'TaskStatusId'. -- Invalid column name 'ProjectStatusId'. -- Invalid column name 'ProjectStatusId'. </code></pre> <p>The ideal code is below, but it throws the error <code>An item with the same key has already been added</code>, which is the error that SSRS/SSDT throws when trying to return multiple columns of the same name.</p> <pre><code>SELECT t.[Description], t.RequestedCompletionDate, t.CommitDate, t.StatusId, t.PriorityId, p.ProjectNumber, p.StatusId, s.Name AS StatusDescription, pr.Name AS PriorityDescription FROM ProjectTask t inner join Project p on p.Id = t.ProjectId inner join Project_TaskStatus s on s.Id = t.StatusId inner join Project_Priority pr on pr.Id = t.PriorityId WHERE t.Type = 'ET' AND t.StatusId NOT IN (4,7) AND p.StatusId NOT IN (3,4) ORDER BY t.PriorityId, t.CommitDate, t.RequestedCompletionDate </code></pre>
0
1,223
HTTP Error 500.19 - Error Code 0x80070021
<p><strong>Background:</strong> Trying to debug WebForms application and get authenticated windows user from AD, </p> <p>On F5 I get greeted with this amazing page.</p> <p><strong>Module</strong> WindowsAuthenticationModule </p> <p><strong>Notification</strong> AuthenticateRequest </p> <p><strong>Handler</strong> ExtensionlessUrl-Integrated-4.0 </p> <p><strong>Error Code</strong> 0x80070021 </p> <p><strong>Config Error</strong> This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false". </p> <p><a href="https://i.stack.imgur.com/f33Jo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f33Jo.png" alt="onDebug"></a></p> <p><strong>Config Source:</strong></p> <pre><code> 81: &lt;anonymousAuthentication enabled="false"/&gt; 82: &lt;windowsAuthentication enabled="true"/&gt; 83: &lt;basicAuthentication enabled="false" </code></pre> <p>My Web.config(JustDifferentNames)</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt; &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/&gt; &lt;!--&lt;section name="windowsAuthentication" overrideModeDefault="Allow" /&gt; &lt;section name="anonymousAuthentication" overrideModeDefault="false" /&gt; &lt;add name="WindowsAuthenticationModule" lockItem="false" /&gt; &lt;add name="AnonymousAuthenticationModule" lockItem="false" /&gt;--&gt; &lt;/configSections&gt; &lt;connectionStrings&gt; &lt;!--&lt;add name="MyContext" connectionString="Data Source=idea-pc;Initial Catalog=componentnameNumber;Integrated Security=True" providerName="System.Data.SqlClient"/&gt;--&gt; &lt;add name="DBComponent1" connectionString="Data Source=idea-pc;Initial Catalog=comp2;Integrated Security=True" providerName="System.Data.SqlClient"/&gt; &lt;add name="DBComponent2" connectionString="Data Source=idea-pc;Initial Catalog=comp3;Integrated Security=True" providerName="System.Data.SqlClient"/&gt; &lt;add name="DBComponent3" connectionString="Data Source=idea-pc;Initial Catalog=comp4;Integrated Security=True" providerName="System.Data.SqlClient"/&gt; &lt;add name="DBComponent4" connectionString="Data Source=idea-pc;Initial Catalog=comp5;Integrated Security=True" providerName="System.Data.SqlClient"/&gt; &lt;add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MyProj-20160209113257.mdf;Initial Catalog=aspnet-MyProjectEvents-20160209113257;Integrated Security=True" providerName="System.Data.SqlClient"/&gt; &lt;/connectionStrings&gt; &lt;system.web&gt; &lt;authentication mode="Windows"/&gt; &lt;identity impersonate="false"/&gt; &lt;authorization&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;compilation debug="true" strict="false" explicit="true" targetFramework="4.5"/&gt; &lt;customErrors mode="Off"/&gt; &lt;!--&lt;/system.web&gt;--&gt; &lt;pages&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Optimization"/&gt; &lt;add namespace="Microsoft.AspNet.Identity"/&gt; &lt;/namespaces&gt; &lt;controls&gt; &lt;add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/&gt; &lt;add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"/&gt; &lt;/controls&gt; &lt;/pages&gt; &lt;membership&gt; &lt;providers&gt; &lt;!-- ASP.NET Membership is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template --&gt; &lt;clear/&gt; &lt;/providers&gt; &lt;/membership&gt; &lt;profile&gt; &lt;providers&gt; &lt;!-- ASP.NET Membership Profile is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template --&gt; &lt;clear/&gt; &lt;/providers&gt; &lt;/profile&gt; &lt;roleManager&gt; &lt;!-- ASP.NET Membership Role is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template --&gt; &lt;providers&gt; &lt;clear/&gt; &lt;/providers&gt; &lt;/roleManager&gt; &lt;!-- If you are deploying to a cloud environment that has multiple web server instances, you should change session state mode from "InProc" to "Custom". In addition, change the connection string named "DefaultConnection" to connect to an instance of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express. --&gt; &lt;sessionState mode="InProc" cookieless="false" timeout="30" customProvider="DefaultSessionProvider"&gt; &lt;providers&gt; &lt;add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection"/&gt; &lt;/providers&gt; &lt;/sessionState&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;security&gt; &lt;authentication&gt; &lt;anonymousAuthentication enabled="false"/&gt; &lt;windowsAuthentication enabled="true"/&gt; &lt;basicAuthentication enabled="false" realm="" defaultLogonDomain="TestDomain"/&gt; &lt;/authentication&gt; &lt;/security&gt; &lt;modules&gt; &lt;!--&lt;remove name="FormsAuthentication"/&gt;--&gt; &lt;/modules&gt; &lt;/system.webServer&gt; &lt;runtime&gt; &lt;gcAllowVeryLargeObjects enabled="true" /&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/&gt; &lt;bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35"/&gt; &lt;bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089"/&gt; &lt;bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35"/&gt; &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35"/&gt; &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35"/&gt; &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35"/&gt; &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/&gt; &lt;/dependentAssembly&gt; &lt;/assemblyBinding&gt; &lt;/runtime&gt; &lt;entityFramework&gt; &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt; &lt;parameters&gt; &lt;parameter value="mssqllocaldb"/&gt; &lt;/parameters&gt; &lt;/defaultConnectionFactory&gt; &lt;providers&gt; &lt;provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/&gt; &lt;/providers&gt; &lt;/entityFramework&gt; &lt;system.codedom&gt; &lt;compilers&gt; &lt;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"/&gt; &lt;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=\&amp;quot;Web\&amp;quot; /optionInfer+"/&gt; &lt;/compilers&gt; &lt;/system.codedom&gt; &lt;/configuration&gt; </code></pre> <p>Looked around checked my settings and I found that I dont have Win Auth under my IIS -> World Wide Web Services -> Security</p> <p><a href="https://i.stack.imgur.com/A0SK3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A0SK3.png" alt="enter image description here"></a></p> <p>Neither do i have it here (Even after disabling anonymous auth)</p> <p><a href="https://i.stack.imgur.com/zR8Xw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zR8Xw.png" alt="enter image description here"></a></p> <p>What am i missing to check ? or do for that matter, <strong>im still a noob</strong>.</p> <p>Edit:</p> <p><a href="https://i.stack.imgur.com/PL5X6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PL5X6.png" alt="enter image description here"></a></p>
0
4,315
MessageContext in SOAPHandler JAX-WS WebService
<p>I have a JAX-WS 2.2 WebService and I must take the IP Address of each client that communicate with it. I write a SOAP protocol handler but I can't see the addresses because the handlers doesn't contain this information and using the mimeheaders I can't also see this information. The code of my handler is the follow:</p> <pre><code>public class AddressHandler implements SOAPHandler&lt;SOAPMessageContext&gt; { private void takeIPAddress(SOAPMessageContext context) { try { SOAPMessage original = context.getMessage(); MimeHeaders mimeheaders = original.getMimeHeaders(); MimeHeader mimeheader = null; Iterator&lt;?&gt; iter = mimeheaders.getAllHeaders(); for (; iter.hasNext();) { mimeheader = (MimeHeader) iter.next(); System.out.println("name=" + mimeheader.getName() + ", value=" + mimeheader.getValue()); } } catch (Exception e) { e.printStackTrace(); } } @Override public void close(MessageContext arg0) { // TODO Auto-generated method stub } @Override public boolean handleFault(SOAPMessageContext arg0) { // TODO Auto-generated method stub return false; } @Override public boolean handleMessage(SOAPMessageContext context) { takeIPAddress(context); return true; } @Override public Set&lt;QName&gt; getHeaders() { // TODO Auto-generated method stub return null; } } </code></pre> <p>Now I'm seeing that would be possible to see the addresses using the following code:</p> <pre><code>SOAPMessageContext jaxwsContext = (SOAPMessageContext)wsContext.getMessageContext(); HttpServletRequest request = HttpServletRequest)jaxwsContext.get(SOAPMessageContext.SERVLET_REQUEST); String ipAddress = request.getRemoteAddr(); </code></pre> <p>But I can't import correctly the HttpServletRequest class. Do you have any ideas?</p> <p><strong>UPDATE</strong></p> <p>Thanks to A Nyar Thar, I've seen that exists another method to take address and I've implemented this in my code, that now is:</p> <pre><code>private void takeIPAddress(SOAPMessageContext context) { HttpExchange exchange = (HttpExchange)context.get("com.sun.xml.ws.http.exchange"); InetSocketAddress remoteAddress = exchange.getRemoteAddress(); String remoteHost = remoteAddress.getHostName(); System.out.println(remoteHost); } </code></pre> <p>But the code execution create this error (where row 39 is where I do exchange.getRemoteAddress()):</p> <pre><code>java.lang.NullPointerException at server.AddressHandler.takeIPAddress(AddressHandler.java:39) at server.AddressHandler.handleMessage(AddressHandler.java:80) at server.AddressHandler.handleMessage(AddressHandler.java:1) at com.sun.xml.internal.ws.handler.HandlerProcessor.callHandleMessage(HandlerProcessor.java:282) at com.sun.xml.internal.ws.handler.HandlerProcessor.callHandlersRequest(HandlerProcessor.java:125) at com.sun.xml.internal.ws.handler.ServerSOAPHandlerTube.callHandlersOnRequest(ServerSOAPHandlerTube.java:123) at com.sun.xml.internal.ws.handler.HandlerTube.processRequest(HandlerTube.java:105) at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Fiber.java:626) at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Fiber.java:585) at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Fiber.java:570) at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Fiber.java:467) at com.sun.xml.internal.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:299) at com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:593) at com.sun.xml.internal.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:244) at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handleExchange(WSHttpHandler.java:95) at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handle(WSHttpHandler.java:80) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77) at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:80) at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:677) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77) at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:649) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) </code></pre> <p>I think that the real problem is that I don't know how take WebServiceContext from my class AddressHandler. Do you have ideas?</p>
0
1,591
How Do I Catch by FullyQualifiedErrorId in PowerShell?
<p>I have a script that creates new AD Objects (via New-ADObject, as it happens). If the object already exists, I need to catch and handle that. However, the exception type isn't nearly as explicit as the FullyQualifiedErrorId. Observe the below:</p> <pre><code>&gt; $Error[-1] | Format-List -Property * -Force writeErrorStream : True PSMessageDetails : Exception : Microsoft.ActiveDirectory.Management.ADException: An attempt was made to add an object to the directory with a name that is already in use ---&gt; System.ServiceModel.FaultException: The supplied entry already exists. --- End of inner exception stack trace --- at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForExtendedError(String extendedErrorMessage, Exception innerException) at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForFaultDetail(FaultDetail faultDetail, FaultException faultException) at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowException(AdwsFault adwsFault, FaultException faultException) at Microsoft.ActiveDirectory.Management.AdwsConnection.Create(ADAddRequest request) at Microsoft.ActiveDirectory.Management.ADWebServiceStoreAccess.Microsoft.ActiveDirectory.Management.IADSy ncOperations.Add(ADSessionHandle handle, ADAddRequest request) at Microsoft.ActiveDirectory.Management.ADActiveObject.Create() at Microsoft.ActiveDirectory.Management.Commands.ADNewCmdletBase`3.ProcessRecordOverride() at Microsoft.ActiveDirectory.Management.Commands.ADCmdletBase.ProcessRecord() TargetObject : ou=Domain Controllers,DC=cryotest,DC=testdom CategoryInfo : NotSpecified: (ou=Domain Contr...test,DC=afcdom1:String) [New-ADObject], ADException FullyQualifiedErrorId : An attempt was made to add an object to the directory with a name that is already in use,Microsoft.ActiveDirectory.Management.Commands.NewADObject ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo ScriptStackTrace : at Import-ADObjectOfClass, C:\Users\administrator\Desktop\Import-ADObjects.ps1: line 103 at &lt;ScriptBlock&gt;, C:\Users\administrator\Desktop\Import-ADObjects.ps1: line 137 at &lt;ScriptBlock&gt;, &lt;No file&gt;: line 1 PipelineIterationInfo : {1, 1} </code></pre> <p>How can I make use of the more verbose information here in my Catch block?</p>
0
1,057
Why do we need to use import 'babel-polyfill'; in react components?
<p>I wonder if we user babel loader + all the presets, why do we need to include babel-polyfill anyway into our components? I just think that babel-loader should do all the job itself.</p> <p>Examples were taken here <a href="https://github.com/reactjs/redux/tree/master/examples" rel="noreferrer">https://github.com/reactjs/redux/tree/master/examples</a></p> <p>What i am asking about is:</p> <pre><code>import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import App from './containers/App'; </code></pre> <p>Here is package example:</p> <pre><code>{ "name": "redux-shopping-cart-example", "version": "0.0.0", "description": "Redux shopping-cart example", "scripts": { "start": "node server.js", "test": "cross-env NODE_ENV=test mocha --recursive --compilers js:babel-register", "test:watch": "npm test -- --watch" }, "repository": { "type": "git", "url": "https://github.com/reactjs/redux.git" }, "license": "MIT", "bugs": { "url": "https://github.com/reactjs/redux/issues" }, "homepage": "http://redux.js.org", "dependencies": { "babel-polyfill": "^6.3.14", "react": "^0.14.7", "react-dom": "^0.14.7", "react-redux": "^4.2.1", "redux": "^3.2.1", "redux-thunk": "^1.0.3" }, "devDependencies": { "babel-core": "^6.3.15", "babel-loader": "^6.2.0", "babel-preset-es2015": "^6.3.13", "babel-preset-react": "^6.3.13", "babel-preset-react-hmre": "^1.1.1", "cross-env": "^1.0.7", "enzyme": "^2.0.0", "express": "^4.13.3", "json-loader": "^0.5.3", "react-addons-test-utils": "^0.14.7", "redux-logger": "^2.0.1", "mocha": "^2.2.5", "node-libs-browser": "^0.5.2", "webpack": "^1.9.11", "webpack-dev-middleware": "^1.2.0", "webpack-hot-middleware": "^2.9.1" } } </code></pre> <p>Here is webpack config example taken from <a href="https://github.com/reactjs/redux/tree/master/examples" rel="noreferrer">https://github.com/reactjs/redux/tree/master/examples</a></p> <pre><code>var path = require('path') var webpack = require('webpack') module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: [ 'babel?presets[]=react,presets[]=es2015,presets[]=react-hmre' ], exclude: /node_modules/, include: __dirname }, { test: /\.json$/, loaders: [ 'json' ], exclude: /node_modules/, include: __dirname } ] } } </code></pre>
0
1,295
css cursor using data-uri
<p>I'm trying to use custom png cursor using data uri but the cursor doesn't change. I've tested on FF 17 which support png as custom cursor. The same data uri work as a background image.</p> <p>Am I using wrong syntax or maybe data-uri can't be used as a cursor image?</p> <p>example: <a href="http://jsfiddle.net/u8t3j/" rel="noreferrer">http://jsfiddle.net/u8t3j/</a></p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=utf-8 /&gt; &lt;title&gt;cursor test&lt;/title&gt; &lt;style&gt; #cursor { width: 300px; height: 300px; border: 1px solid black; cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAJFklEQVR42rWXCXBU9R3Hv+/Ye7PZTbLZJCQBRIej2JHSkStgoS2jWJlBzhpNOKscBR2wIrSlVA4NIGoJMBVBoTOFloKlDGEIV0K4hyvDCBEQAiSQY7PZ7G52913//t4L4WiCoh3ezl5v3/v/Pr/f//s7lsN9h8fjcdpstmcFnq9rjkYrOY6L1NfXq3iMB3f/F7fbnZGamrqtS5cnfnL7dk1JdXV1SSwWKzObTRV1dfW3HjuA3W7J8KZmbFmw/KOcZ7pkYf++Azh69AiruFhxrPpWdVE8Ht9vtVrL/X5/6PEAWO2+5BT3P976YNWg/LEjkCQAtAU4d+4sjh09hrLDhwPnz58vbmxs/JLn+ZKmpqbq/xsgi8uxArxFYXI4yF9JTe7Ab576x2WDeg38OXqlJ8Lnst+9+Nq1azhz5gz27d+vHC4rO3b16tXdpJedDYHAuR8MkMn1d9Fbqsa0UEyo89p9sU/nLFrSt8+QYWiONqN3tg+JdjPYfeGKRCK4fOUKSkpKULRr16Uzp08fjkWjfwuGQvt+CEACA5/GGIvJQtBnTmlc9faihX2GvTwW9cEQBDL9TFYqRF4AQYIyAwLfgqIxhpqa26STY9i+bXvdkSOHT/gb/BtUWf13OBJWHgmgAzcggd58LQCNXlNKYPWs38/rO2JcPmRZQigag8tmRbe0JAOAsXs3kw5whwXNzc2klXPYtGlT8969e8tramoKnU7nVsqk2LcD8P0TwPg7AEGvmOQvnDb37X5jXpsMWZGhqSqisop0twNZngSoqgb2v4tQVHgi0Vk0jeHEiePYuHEjKy0tPUgAK0VRLK6rq2sXhLYgh7YABoAiBlN4d33hlNlv9s+dOBWKqhCAZnguaxo6p7iR7LC2C3EvKgRDQPrvBw8cxOefb2DFxcVrSTfvUda0qSVcFj/IqWmaj5aUCMDDu+oKJ8yanpP/xiyoigJVUw3PZDKqh7yrzwObWSQ47Vv3VhB4475QKIQPP1yJDRvW7wlHIpP89fU3HwDI5gY4VSMCIICmROa8vSpvxhvPTZoxh8Kpkbdyi2fklb4VdjKuQ+hCVDX2UABdK3QLRAKpq/dj+EsvSZe+rnjV39DwzwcjwD3r1GDxgWmyJISczHnrL+Mmjx8ydfa7xt4qinJnn2lReoRjCpIcNoJwG1mgsfYhdMP6cf36daz7bB02b95cVnWzaiyJ9YHixXUU+jpkTUzjGJMlPmTXnLc/eTlv9C9nzv0ThVE0hHj3Yt0zegaaJXRKSkDHFFfbrSBS8U5q7NixA+vXr8ep06fOUvWcEA6Fz7bRQCe+n0NiQhrPoMTRZNZcNStfGPXii7MXLIbFYjNSscU4Z0RA3wrdqD8SQ/f0ZGRQdrRCtKblhYsXsaZwNUpKS0B9Y08gEJhJnle0mwU+5NjNHEvXGKdS1nPMVftBztD+o+ctWYkElwuSAdDqewuGQBCBWNzYjt7ZqUhJsBmLkZcU6i04VFqKyuuVuF55Yx+l38hYPBp8mFa4NOTYBI5l0LoE0Mw4d+3Cp/t0z1+4Yg2SvamQJemesO6D0D9VB8OwWaz4aWYSvqKGtWXrVmRnZyM3N5ckxTBz5szKnTt3jg6Fmk4+FCAT/W2M4wiAYzIicd7TMLdz9/QZC1YUolOXpyDF4w+q+04F0GMS0zjUNoVxdNeXiNZWY9KE8ejxox53+0Z5eTny8vKOkxCH0jY0PQzASgBp5JcpzqIhwR2Y6s2yzV+wfJXQs1dvxOP3Clir71S0YLPZ0Uxw69cWIhgMYuL0tzCwayZIzEZ6tvaMpUuXqgUFBX+g7VnaLkAGBljo2nTeAIgFhcSmXzu8yuJ5i5c5+g8ZSgBRtJY9HUAvTHa7wzi17qMCNIQiGPn6m+ApY5502/AkpWdrpdRT8UJFBcaMGnW6qqpqcHtR0JuRid4zaHGzwqQgczT9zJoc+XjGO/PTho/JRTwWM7xuNe5wOI3FVxcsQmXlDUx6989wJ7ogU+t22S3o2SEFZkGgazUDgMov8vPzbx06dGgkZcTRtmnI9RNl8OlkwKYyNaxagp1FT+CzMfnju74+ey4USW7pghRWZ4KTIiJh9bLFOFi8G7OXrUbPnk/DxasUbh7BqIRMali+RLsBoJ/TS/HkyZP9RUVFE+jzf9oAZKGPoHGirgGHXo7jXKPZ6gut7dG7x+DFn/wVdvJYkWU4nQkI+OuxZsX72LNjGzI6PoGFa77AUx18oKZhiC4iqYhT9+zidcNtMxlFqeLSZbyW+0otCTGXWvTedkTYh+N4kSYiJNJXJcbCUUda83y7m02bMvMdbsSreSQsDV9f+Aprlr+P8lPHYXM4qFGq4rARY/DbOb+jAiRQyZYNATZGZUjkvcdJBYpqyOrlS7Br+9ZL9NPzNNJ9004EBujwSZRRyRQFTWJSBI7AwJRsodDudKb8atQ4WEnxO7f+HTW3bsLEO8oDtbG19kRhuMmqPf+LF4bjlYlTkOpLgyiajC4UpiJ15epV/OuL9ThZdgA02n9K8+Nv2s0C/SWL6+eiZptqpBn1lxgaeUeaND0hWciPxpo9+nmT2eJXouLuULXwsSoJ3zBTuJsnk3+PM8mDU7w+dOvxY3gJQqHuWV9Tg0sUsQa/HxzPH6utrc1raGi49FAAmgttpPM0vXvCCLiqxVmTYEqUBjvc4lAaMdRoI3ZJQUuxCTYmcLyTaobevn2udEyjSAyT5bi3pQfrT54ywHJTlpWiSCRcQKP95YdWQv0lFQNFE6+mUzW00Ql98tRVT6WZchCKlUqKxMEcMcHkIQN6nDX9VpUaaBwhkylBGWBN4PuYzBwNt6TDqHBDFkO7q6orD+A7jrt/TDK5vh4G0Xun6rCWCU8fArQw9cAAOUW+MS9NKVaqcrqvxjU0D9DEIMUYZJGusNF8SedFfy1OBr7L+AMAejoyTkwiI/r/BOq6TNEYHxHABW+wQ0ZD6MDrf2JYCjG2tD8j5i2jF/TZxCjSkEwQ/JUojX0vABjlcABHPckmMt6kUEJwjI9Xs7IHJg7Si4nucpP/DjImoLVXUwsg6AhjYqjqEY23AXjUI417jqd4m8BkC8czXtN4KgKQSb7yTRxh32et/wJPSoRd6oGs9QAAAABJRU5ErkJggg==); } #background { width: 300px; height: 300px; border: 1px solid black; margin-top: 10px; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAJFklEQVR42rWXCXBU9R3Hv+/Ye7PZTbLZJCQBRIej2JHSkStgoS2jWJlBzhpNOKscBR2wIrSlVA4NIGoJMBVBoTOFloKlDGEIV0K4hyvDCBEQAiSQY7PZ7G52913//t4L4WiCoh3ezl5v3/v/Pr/f//s7lsN9h8fjcdpstmcFnq9rjkYrOY6L1NfXq3iMB3f/F7fbnZGamrqtS5cnfnL7dk1JdXV1SSwWKzObTRV1dfW3HjuA3W7J8KZmbFmw/KOcZ7pkYf++Azh69AiruFhxrPpWdVE8Ht9vtVrL/X5/6PEAWO2+5BT3P976YNWg/LEjkCQAtAU4d+4sjh09hrLDhwPnz58vbmxs/JLn+ZKmpqbq/xsgi8uxArxFYXI4yF9JTe7Ab576x2WDeg38OXqlJ8Lnst+9+Nq1azhz5gz27d+vHC4rO3b16tXdpJedDYHAuR8MkMn1d9Fbqsa0UEyo89p9sU/nLFrSt8+QYWiONqN3tg+JdjPYfeGKRCK4fOUKSkpKULRr16Uzp08fjkWjfwuGQvt+CEACA5/GGIvJQtBnTmlc9faihX2GvTwW9cEQBDL9TFYqRF4AQYIyAwLfgqIxhpqa26STY9i+bXvdkSOHT/gb/BtUWf13OBJWHgmgAzcggd58LQCNXlNKYPWs38/rO2JcPmRZQigag8tmRbe0JAOAsXs3kw5whwXNzc2klXPYtGlT8969e8tramoKnU7nVsqk2LcD8P0TwPg7AEGvmOQvnDb37X5jXpsMWZGhqSqisop0twNZngSoqgb2v4tQVHgi0Vk0jeHEiePYuHEjKy0tPUgAK0VRLK6rq2sXhLYgh7YABoAiBlN4d33hlNlv9s+dOBWKqhCAZnguaxo6p7iR7LC2C3EvKgRDQPrvBw8cxOefb2DFxcVrSTfvUda0qSVcFj/IqWmaj5aUCMDDu+oKJ8yanpP/xiyoigJVUw3PZDKqh7yrzwObWSQ47Vv3VhB4475QKIQPP1yJDRvW7wlHIpP89fU3HwDI5gY4VSMCIICmROa8vSpvxhvPTZoxh8Kpkbdyi2fklb4VdjKuQ+hCVDX2UABdK3QLRAKpq/dj+EsvSZe+rnjV39DwzwcjwD3r1GDxgWmyJISczHnrL+Mmjx8ydfa7xt4qinJnn2lReoRjCpIcNoJwG1mgsfYhdMP6cf36daz7bB02b95cVnWzaiyJ9YHixXUU+jpkTUzjGJMlPmTXnLc/eTlv9C9nzv0ThVE0hHj3Yt0zegaaJXRKSkDHFFfbrSBS8U5q7NixA+vXr8ep06fOUvWcEA6Fz7bRQCe+n0NiQhrPoMTRZNZcNStfGPXii7MXLIbFYjNSscU4Z0RA3wrdqD8SQ/f0ZGRQdrRCtKblhYsXsaZwNUpKS0B9Y08gEJhJnle0mwU+5NjNHEvXGKdS1nPMVftBztD+o+ctWYkElwuSAdDqewuGQBCBWNzYjt7ZqUhJsBmLkZcU6i04VFqKyuuVuF55Yx+l38hYPBp8mFa4NOTYBI5l0LoE0Mw4d+3Cp/t0z1+4Yg2SvamQJemesO6D0D9VB8OwWaz4aWYSvqKGtWXrVmRnZyM3N5ckxTBz5szKnTt3jg6Fmk4+FCAT/W2M4wiAYzIicd7TMLdz9/QZC1YUolOXpyDF4w+q+04F0GMS0zjUNoVxdNeXiNZWY9KE8ejxox53+0Z5eTny8vKOkxCH0jY0PQzASgBp5JcpzqIhwR2Y6s2yzV+wfJXQs1dvxOP3Clir71S0YLPZ0Uxw69cWIhgMYuL0tzCwayZIzEZ6tvaMpUuXqgUFBX+g7VnaLkAGBljo2nTeAIgFhcSmXzu8yuJ5i5c5+g8ZSgBRtJY9HUAvTHa7wzi17qMCNIQiGPn6m+ApY5502/AkpWdrpdRT8UJFBcaMGnW6qqpqcHtR0JuRid4zaHGzwqQgczT9zJoc+XjGO/PTho/JRTwWM7xuNe5wOI3FVxcsQmXlDUx6989wJ7ogU+t22S3o2SEFZkGgazUDgMov8vPzbx06dGgkZcTRtmnI9RNl8OlkwKYyNaxagp1FT+CzMfnju74+ey4USW7pghRWZ4KTIiJh9bLFOFi8G7OXrUbPnk/DxasUbh7BqIRMali+RLsBoJ/TS/HkyZP9RUVFE+jzf9oAZKGPoHGirgGHXo7jXKPZ6gut7dG7x+DFn/wVdvJYkWU4nQkI+OuxZsX72LNjGzI6PoGFa77AUx18oKZhiC4iqYhT9+zidcNtMxlFqeLSZbyW+0otCTGXWvTedkTYh+N4kSYiJNJXJcbCUUda83y7m02bMvMdbsSreSQsDV9f+Aprlr+P8lPHYXM4qFGq4rARY/DbOb+jAiRQyZYNATZGZUjkvcdJBYpqyOrlS7Br+9ZL9NPzNNJ9004EBujwSZRRyRQFTWJSBI7AwJRsodDudKb8atQ4WEnxO7f+HTW3bsLEO8oDtbG19kRhuMmqPf+LF4bjlYlTkOpLgyiajC4UpiJ15epV/OuL9ThZdgA02n9K8+Nv2s0C/SWL6+eiZptqpBn1lxgaeUeaND0hWciPxpo9+nmT2eJXouLuULXwsSoJ3zBTuJsnk3+PM8mDU7w+dOvxY3gJQqHuWV9Tg0sUsQa/HxzPH6utrc1raGi49FAAmgttpPM0vXvCCLiqxVmTYEqUBjvc4lAaMdRoI3ZJQUuxCTYmcLyTaobevn2udEyjSAyT5bi3pQfrT54ywHJTlpWiSCRcQKP95YdWQv0lFQNFE6+mUzW00Ql98tRVT6WZchCKlUqKxMEcMcHkIQN6nDX9VpUaaBwhkylBGWBN4PuYzBwNt6TDqHBDFkO7q6orD+A7jrt/TDK5vh4G0Xun6rCWCU8fArQw9cAAOUW+MS9NKVaqcrqvxjU0D9DEIMUYZJGusNF8SedFfy1OBr7L+AMAejoyTkwiI/r/BOq6TNEYHxHABW+wQ0ZD6MDrf2JYCjG2tD8j5i2jF/TZxCjSkEwQ/JUojX0vABjlcABHPckmMt6kUEJwjI9Xs7IHJg7Si4nucpP/DjImoLVXUwsg6AhjYqjqEY23AXjUI417jqd4m8BkC8czXtN4KgKQSb7yTRxh32et/wJPSoRd6oGs9QAAAABJRU5ErkJggg==); } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="cursor"&gt;&lt;/div&gt; &lt;div id="background"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The answer works for png in FF and Chrome so I'm adding an example for .cur image that doesn't work in IE</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=utf-8 /&gt; &lt;title&gt;cursor test&lt;/title&gt; &lt;style&gt; #cursor { width: 300px; height: 300px; border: 1px solid black; cursor: url(data:application/cur;base64,AAACAAEAICAAAAAAAACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAgBAAABMLAAATCwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPwEYAkABHAc7ABwOOgIdEDwAGws8ARsGOgAcAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADsBGgE6AhkKPAEdDzoCGQk8ARoCAAAAAAAAAAAAAAAAAAAAADoBHAU6AhwVOwEcIDsBGyM7ARskOwEbIzsAGyA6ARwVPgAbCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3AB0DOwEcFToBGyM7ARslOgIcITwBGhY9AR0HAAAAAAAAAAA8AhsIOwIbHDsBGyU7ARslOgEbJDwBGyQ8ARwkPAAcIjsAGyE7ABobPgAfCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgBHBE8ARsmOwEbJjsBGyU8ARwlPQEcJTsAHBk9ABsIPQIcCTwCGx46ABsmOwEcJTsBGyQ8ARwkOwAaIDUAFhgwABUcLwEVJTEAFSQ1ABYRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9ABYEOgIbHTsBGyY7ARwkPAIcJDsAGyEzABUZLwAVITIAFhs4ABcQPQAcITwBHCY7ARwkPAEcJDcAGR4qABIjJg0XXigaH5UpICStKR8jpiwWIIkfGhtBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADoBHAk7ARshOwEcJTwBHCQ5ARoiKwATJSUPGGYpHyOsKx8kqSsPG18yABUaOwAaGT0BHSU0ABYfJgQSNiYdIKAkJSXqHSAg/xwfIP8bICD/HSEg/yQkJOMgHx+aFBQUJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOQEdDjsBGyQ8ARwkPAAbIiwAEyQmGB6PKSsr7h8jIv8gIyP/Jyko7CsgJKQuBhc1MQAUEyUFEzsnISS+IiYl/zk7Of9nZWH/f3x2/3p5cv9jYl7/OTk5/yYmJ/8oKCjHEhISJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADsAHQE7AB0TOwEbJjwBHCQ2ABYZJQsWVigpKus0NTT/jImA/5aSiP89Pjz/ISUl/ywnKtEkERlpJyAjtyUoKP9zcWz/2NPG//Dq3P/17uD/9O3g/+3l1P/MxLH/amVe/ykpKf8hISGaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAcATsCHRc7ARsmPAEbIjAAExkmGB6UJSgo/pyWjf/68t7/+PHf/87Iuf9WVFD/HyEi/yosK/snKCj/fXly//Pt3//27+H/8evd//Dq3v/r4c7/6d/I//Tr2f/u5tX/dHJr/yAhIdogICAiAAAAAAAAAAAAAAAAAAAAAAAAAAA3AB0DOwEbGzwBHCY8ABsgLAEUJh8YHL5JS0b/493L/+/o1f/q49H/9+/d/+PczP9raWP/GRsd/zs6N//c0bj/8+zd/+/p3f/v6d7/7OPT/+ngzP/59e///v7////////b2tj/NTU16RcXF0QAAAAAAAAAAAAAAAAAAAAAAAAAADkBIAQ7ARsdPAEcJjkAGRoqBxY7GRga2Hl3cP/x6tf/7OTT/+rj0f/p4dD/9e7c/+/n1f90cmv/LC0r/8K4nv/v5Mr/7ObY/+7o2//o38z/9fDo///////9/fz///////Ly8v9WVlbsDQ0NTQAAAAAAAAAAAAAAAAAAAAAAAAAAOwEbBTsBGx88ARwlNgAYFigLF1YdHh/nmJWL//Pr2f/r49L/6uPR/+vj0v/o4c//9Oza//Ts2f94dm//W1dQ/93Qs//r38P/4da+/+jgzP/8+/j///7+//38+///////8fHx/1BQUOYTExM5AAAAAAAAAAAAAAAAAAAAAAAAAAA7ABoHOwEbIDwBHSU0ABYWJg8ZbyIkJPStqZ7/8+vY/+rk0f/q49H/6uPR/+vj0v/o4c//8+vZ//Pr2P99e3T/cm5i/+LVtf/m2Lf/7+jb///////9/Pz//fz7///////Y2Nb/LCwszREREQ4AAAAAAAAAAAAAAAAAAAAAAAAAADoAHAg7ARsgPAEcJTMAFRgiEBiBKy0t/L+5rP/y6tj/6uPR/+rj0f/q49H/6+PS/+rj0f/p4tD/8+vZ/+zkz/+BfG3/cm1e/+PYwP////3//v7+//38+//+/fz//////4aGhvwQEBB5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOgAcCTsBGyM8ABsiMQAWGx8RGJM4Ojn/zce4//Lq2P/r49L/6+PS/+vj0v/r49L/6uPR/+rj0f/q49L/6+HK/9/TtP+PiXv/dXNy/9XU1f/////////+///////R0dH/Ly8vyBEREQ4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8ABgJOwEbIzsAGyAxABUfGxAWoERHQ//b1MT/8enX/+vj0v/r49L/6+PS/+rj0f/r49H/6uPS/+rj0f/e1Lf/5tvA//j39P/IyMr/dHRz/5KSkf/t7ez/7Ovr/1pZWeAODQ01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwAFwo7AR0jPAAbIC8AFSEZDhSqU1RQ/+Layv/w6Nf/6uPR/+vj0f/q49H/6+PR/+rj0v/r5NX/5NzE/+DUuP/28uv////////////v7+//mJeX/1pZWv87Ozv/HhwdvAkHCA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOQIgCzwBGiM8ABwfLgAVJRcOE7RiYlz/5+HP//Do1v/q49H/6uPR/+vj0v/q49H/6+TT/+nhz//h1rz/9O/l///////9/Pv//fz7///+/f//////19fW/21sbf8uLi7/GxsbuQoKCicAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4Ax8LPAEaIzsAGx4uAhUoFg4TumtsZf/r5NP/7+fW/+rj0f/q49H/6uPR/+rj0v/q49H/5NnA//Hr4P///////fz7//38+//9/Pv//fz7//79+////////////7Gxsf9PT0//HB0czwwNDDAAAAAAAAAAAAAAAAAAAAAAAAAAADYBHQw9ARsjOwAbHi4DFSoVDxS9dXNs/+7m1f/v59b/6+PS/+vj0v/r5NP/6uTS/+bcxv/v59j///7///79/f/9/Pv//fz7//38+//9/Pv//fz7//38+////////////+Hh4f99fn3/JSYlwwoKChoAAAAAAAAAAAAAAAAAAAAAOwEeDDsBGyM7ABodLQQWLBUQFcB9fHP/8ejW/+/m1P/q49H/6uPR/+vk0//o38r/7OXU//38+//+/v7//fz7//38+//9/Pv//fz7//38+//9/Pv//fz7//37+v/9/Pv//////+zr6v85ODj5EhITVQAAAAAAAAAAAAAAAAAAAAA+Ah0MPAAbIzsAGR0sBBUuFxIXw4KBeP/x6df/7eXU/+rj0f/q49L/6ODN/+riz//7+fb///////38+//9/Pv//fz7//38+//9/Pv//fz7//38+//9/Pv////+///////y8vL/gYCA/x8fH7kUFBMcAAAAAAAAAAAAAAAAAAAAADwBHA08ARskOwAaHCwEFjAYFBjFiId9//Hp2P/t5tT/6+PS/+ni0P/n4Mv/9/Ts///////9/Pz//fz7//38+//9/Pv//fz7//38+//9/Pv//v79//////////7/v76+/15eXv4ZGRmWDg4OGQAAAAAAAAAAAAAAAAAAAAAAAAAAOgIbDTwBGyQ7ABocLAMVMRkVGcaOjYP/8urZ/+3m1P/q49L/597J//Lu4v///////fz8//38+//9/Pv//fz7//38+//+/fz////+///////+/f3/x8fH/2lpaf4rKyu+ERERTRUVFQgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7ARsNPAEbJDsAGhwrAxUxGhcax5STif/z69r/7ebV/+XdyP/t5tb///7+//39/P/9/Pv//fz7//38+////v3////////////19fX/xsbG/2lpafUlJSXHDg4OXBoaGggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADoBHA08ARslOwAaHSwDFTQcFxvInZuQ//Tt2v/n3sb/5t7J//z7+f///f3//fz7//79/P////////////7+/f/m5+b/rq6t/11cXOoiIiK0DxAPUwwLDAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOgEcDjsBHCQ5ABoXJAMSLBwaHMeinpD/7ODH/+LXvf/59fD//////////v////////////T09P/R0dD/kpKR/0hISNoWFhefDQ0PQwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AR0IPgEdDzkAGQMWAgoZGB0dwaObhv/m2Lf/9fHo/////////////////9/f3/+urq7/bGxr+zAwMMMPDw97ERESLwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAoIChcaHB3BrqWO///87f//////6+vr/7u8vP+Dg4T/SEhI7hwcHKkMDAxZDg4OGgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwoKGiEgH8OxrJ7/zs/O/42MjP9TU1P+LCssxhISEn0LCws7ExMTDQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAaJiYmyEhJSfoxMTG7FxcXfA8PD0AUFRUZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEREQwaGhpCHBwdLRMTEw4UFBQDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//gP/+DwB//AYAP/wAAD/4AAAf+AAAB/gAAAPwAAAD8AAAAfAAAAHwAAAB8AAAAfAAAAHwAAAD8AAAA/AAAAfwAAAH8AAAA/AAAAHwAAAA8AAAAPAAAADwAAAB8AAAA/AAAA/wAAA/8AAB//AAB//+AB///gB///4D///+D///8=), pointer; } #background { width: 300px; height: 300px; border: 1px solid black; margin-top: 10px; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAJFklEQVR42rWXCXBU9R3Hv+/Ye7PZTbLZJCQBRIej2JHSkStgoS2jWJlBzhpNOKscBR2wIrSlVA4NIGoJMBVBoTOFloKlDGEIV0K4hyvDCBEQAiSQY7PZ7G52913//t4L4WiCoh3ezl5v3/v/Pr/f//s7lsN9h8fjcdpstmcFnq9rjkYrOY6L1NfXq3iMB3f/F7fbnZGamrqtS5cnfnL7dk1JdXV1SSwWKzObTRV1dfW3HjuA3W7J8KZmbFmw/KOcZ7pkYf++Azh69AiruFhxrPpWdVE8Ht9vtVrL/X5/6PEAWO2+5BT3P976YNWg/LEjkCQAtAU4d+4sjh09hrLDhwPnz58vbmxs/JLn+ZKmpqbq/xsgi8uxArxFYXI4yF9JTe7Ab576x2WDeg38OXqlJ8Lnst+9+Nq1azhz5gz27d+vHC4rO3b16tXdpJedDYHAuR8MkMn1d9Fbqsa0UEyo89p9sU/nLFrSt8+QYWiONqN3tg+JdjPYfeGKRCK4fOUKSkpKULRr16Uzp08fjkWjfwuGQvt+CEACA5/GGIvJQtBnTmlc9faihX2GvTwW9cEQBDL9TFYqRF4AQYIyAwLfgqIxhpqa26STY9i+bXvdkSOHT/gb/BtUWf13OBJWHgmgAzcggd58LQCNXlNKYPWs38/rO2JcPmRZQigag8tmRbe0JAOAsXs3kw5whwXNzc2klXPYtGlT8969e8tramoKnU7nVsqk2LcD8P0TwPg7AEGvmOQvnDb37X5jXpsMWZGhqSqisop0twNZngSoqgb2v4tQVHgi0Vk0jeHEiePYuHEjKy0tPUgAK0VRLK6rq2sXhLYgh7YABoAiBlN4d33hlNlv9s+dOBWKqhCAZnguaxo6p7iR7LC2C3EvKgRDQPrvBw8cxOefb2DFxcVrSTfvUda0qSVcFj/IqWmaj5aUCMDDu+oKJ8yanpP/xiyoigJVUw3PZDKqh7yrzwObWSQ47Vv3VhB4475QKIQPP1yJDRvW7wlHIpP89fU3HwDI5gY4VSMCIICmROa8vSpvxhvPTZoxh8Kpkbdyi2fklb4VdjKuQ+hCVDX2UABdK3QLRAKpq/dj+EsvSZe+rnjV39DwzwcjwD3r1GDxgWmyJISczHnrL+Mmjx8ydfa7xt4qinJnn2lReoRjCpIcNoJwG1mgsfYhdMP6cf36daz7bB02b95cVnWzaiyJ9YHixXUU+jpkTUzjGJMlPmTXnLc/eTlv9C9nzv0ThVE0hHj3Yt0zegaaJXRKSkDHFFfbrSBS8U5q7NixA+vXr8ep06fOUvWcEA6Fz7bRQCe+n0NiQhrPoMTRZNZcNStfGPXii7MXLIbFYjNSscU4Z0RA3wrdqD8SQ/f0ZGRQdrRCtKblhYsXsaZwNUpKS0B9Y08gEJhJnle0mwU+5NjNHEvXGKdS1nPMVftBztD+o+ctWYkElwuSAdDqewuGQBCBWNzYjt7ZqUhJsBmLkZcU6i04VFqKyuuVuF55Yx+l38hYPBp8mFa4NOTYBI5l0LoE0Mw4d+3Cp/t0z1+4Yg2SvamQJemesO6D0D9VB8OwWaz4aWYSvqKGtWXrVmRnZyM3N5ckxTBz5szKnTt3jg6Fmk4+FCAT/W2M4wiAYzIicd7TMLdz9/QZC1YUolOXpyDF4w+q+04F0GMS0zjUNoVxdNeXiNZWY9KE8ejxox53+0Z5eTny8vKOkxCH0jY0PQzASgBp5JcpzqIhwR2Y6s2yzV+wfJXQs1dvxOP3Clir71S0YLPZ0Uxw69cWIhgMYuL0tzCwayZIzEZ6tvaMpUuXqgUFBX+g7VnaLkAGBljo2nTeAIgFhcSmXzu8yuJ5i5c5+g8ZSgBRtJY9HUAvTHa7wzi17qMCNIQiGPn6m+ApY5502/AkpWdrpdRT8UJFBcaMGnW6qqpqcHtR0JuRid4zaHGzwqQgczT9zJoc+XjGO/PTho/JRTwWM7xuNe5wOI3FVxcsQmXlDUx6989wJ7ogU+t22S3o2SEFZkGgazUDgMov8vPzbx06dGgkZcTRtmnI9RNl8OlkwKYyNaxagp1FT+CzMfnju74+ey4USW7pghRWZ4KTIiJh9bLFOFi8G7OXrUbPnk/DxasUbh7BqIRMali+RLsBoJ/TS/HkyZP9RUVFE+jzf9oAZKGPoHGirgGHXo7jXKPZ6gut7dG7x+DFn/wVdvJYkWU4nQkI+OuxZsX72LNjGzI6PoGFa77AUx18oKZhiC4iqYhT9+zidcNtMxlFqeLSZbyW+0otCTGXWvTedkTYh+N4kSYiJNJXJcbCUUda83y7m02bMvMdbsSreSQsDV9f+Aprlr+P8lPHYXM4qFGq4rARY/DbOb+jAiRQyZYNATZGZUjkvcdJBYpqyOrlS7Br+9ZL9NPzNNJ9004EBujwSZRRyRQFTWJSBI7AwJRsodDudKb8atQ4WEnxO7f+HTW3bsLEO8oDtbG19kRhuMmqPf+LF4bjlYlTkOpLgyiajC4UpiJ15epV/OuL9ThZdgA02n9K8+Nv2s0C/SWL6+eiZptqpBn1lxgaeUeaND0hWciPxpo9+nmT2eJXouLuULXwsSoJ3zBTuJsnk3+PM8mDU7w+dOvxY3gJQqHuWV9Tg0sUsQa/HxzPH6utrc1raGi49FAAmgttpPM0vXvCCLiqxVmTYEqUBjvc4lAaMdRoI3ZJQUuxCTYmcLyTaobevn2udEyjSAyT5bi3pQfrT54ywHJTlpWiSCRcQKP95YdWQv0lFQNFE6+mUzW00Ql98tRVT6WZchCKlUqKxMEcMcHkIQN6nDX9VpUaaBwhkylBGWBN4PuYzBwNt6TDqHBDFkO7q6orD+A7jrt/TDK5vh4G0Xun6rCWCU8fArQw9cAAOUW+MS9NKVaqcrqvxjU0D9DEIMUYZJGusNF8SedFfy1OBr7L+AMAejoyTkwiI/r/BOq6TNEYHxHABW+wQ0ZD6MDrf2JYCjG2tD8j5i2jF/TZxCjSkEwQ/JUojX0vABjlcABHPckmMt6kUEJwjI9Xs7IHJg7Si4nucpP/DjImoLVXUwsg6AhjYqjqEY23AXjUI417jqd4m8BkC8czXtN4KgKQSb7yTRxh32et/wJPSoRd6oGs9QAAAABJRU5ErkJggg==); } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="cursor"&gt;&lt;/div&gt; &lt;div id="background"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Thanks</p>
0
11,386
How to add/remove rows using SlickGrid
<p>How to write such functions and bind them to two buttons like "add row" and "remove row":</p> <p>The now working example code only support adding new row by editing on the blank bottom line.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt; &lt;title&gt;SlickGrid example 3: Editing&lt;/title&gt; &lt;link rel="stylesheet" href="../slick.grid.css" type="text/css"/&gt; &lt;link rel="stylesheet" href="../css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css"/&gt; &lt;link rel="stylesheet" href="examples.css" type="text/css"/&gt; &lt;style&gt; .cell-title { font-weight: bold; } .cell-effort-driven { text-align: center; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div style="position:relative"&gt; &lt;div style="width:600px;"&gt; &lt;div id="myGrid" style="width:100%;height:500px;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="options-panel"&gt; &lt;h2&gt;Demonstrates:&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;adding basic keyboard navigation and editing&lt;/li&gt; &lt;li&gt;custom editors and validators&lt;/li&gt; &lt;li&gt;auto-edit settings&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Options:&lt;/h2&gt; &lt;button onclick="grid.setOptions({autoEdit:true})"&gt;Auto-edit ON&lt;/button&gt; &amp;nbsp; &lt;button onclick="grid.setOptions({autoEdit:false})"&gt;Auto-edit OFF&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="../lib/firebugx.js"&gt;&lt;/script&gt; &lt;script src="../lib/jquery-1.7.min.js"&gt;&lt;/script&gt; &lt;script src="../lib/jquery-ui-1.8.16.custom.min.js"&gt;&lt;/script&gt; &lt;script src="../lib/jquery.event.drag-2.0.min.js"&gt;&lt;/script&gt; &lt;script src="../slick.core.js"&gt;&lt;/script&gt; &lt;script src="../plugins/slick.cellrangedecorator.js"&gt;&lt;/script&gt; &lt;script src="../plugins/slick.cellrangeselector.js"&gt;&lt;/script&gt; &lt;script src="../plugins/slick.cellselectionmodel.js"&gt;&lt;/script&gt; &lt;script src="../slick.formatters.js"&gt;&lt;/script&gt; &lt;script src="../slick.editors.js"&gt;&lt;/script&gt; &lt;script src="../slick.grid.js"&gt;&lt;/script&gt; &lt;script&gt; function requiredFieldValidator(value) { if (value == null || value == undefined || !value.length) { return {valid: false, msg: "This is a required field"}; } else { return {valid: true, msg: null}; } } var grid; var data = []; var columns = [ {id: "title", name: "Title", field: "title", width: 120, cssClass: "cell-title", editor: Slick.Editors.Text, validator: requiredFieldValidator}, {id: "desc", name: "Description", field: "description", width: 100, editor: Slick.Editors.LongText}, {id: "duration", name: "Duration", field: "duration", editor: Slick.Editors.Text}, {id: "%", name: "% Complete", field: "percentComplete", width: 80, resizable: false, formatter: Slick.Formatters.PercentCompleteBar, editor: Slick.Editors.PercentComplete}, {id: "start", name: "Start", field: "start", minWidth: 60, editor: Slick.Editors.Date}, {id: "finish", name: "Finish", field: "finish", minWidth: 60, editor: Slick.Editors.Date}, {id: "effort-driven", name: "Effort Driven", width: 80, minWidth: 20, maxWidth: 80, cssClass: "cell-effort-driven", field: "effortDriven", formatter: Slick.Formatters.Checkmark, editor: Slick.Editors.Checkbox} ]; var options = { editable: true, enableAddRow: true, enableCellNavigation: true, asyncEditorLoading: false, autoEdit: false }; $(function () { for (var i = 0; i &lt; 500; i++) { var d = (data[i] = {}); d["title"] = "Task " + i; d["description"] = "This is a sample task description.\n It can be multiline"; d["duration"] = "5 days"; d["percentComplete"] = Math.round(Math.random() * 100); d["start"] = "01/01/2009"; d["finish"] = "01/05/2009"; d["effortDriven"] = (i % 5 == 0); } grid = new Slick.Grid("#myGrid", data, columns, options); grid.setSelectionModel(new Slick.CellSelectionModel()); grid.onAddNewRow.subscribe(function (e, args) { var item = args.item; grid.invalidateRow(data.length); data.push(item); grid.updateRowCount(); grid.render(); }); }) &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
1,877
JNDI Can't Create a JDBC Connection on Tomcat 6
<p>I'm getting this error when I try to view the page:</p> <pre><code>SQLException: Cannot create JDBC driver of class '' for connect URL 'null' </code></pre> <p>I have the following /WEB-INF/web.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app&gt; &lt;display-name&gt;WSwartzendruber.net&lt;/display-name&gt; &lt;description&gt;Personal Website&lt;/description&gt; &lt;!-- Servlet stuff --&gt; &lt;servlet&gt; &lt;servlet-name&gt;PostgresTest&lt;/servlet-name&gt; &lt;servlet-class&gt;PostgresTest&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;PostgresTest&lt;/servlet-name&gt; &lt;url-pattern&gt;/servlets/postgrestest&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- JNDI --&gt; &lt;resource-ref&gt; &lt;description&gt;PostgreSQL Data Source&lt;/description&gt; &lt;res-ref-name&gt;jdbc/db_website&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;res-auth&gt;Container&lt;/res-auth&gt; &lt;/resource-ref&gt; &lt;/web-app&gt; </code></pre> <p>I have this in /META-INF/context.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Context reloadable="true"&gt; &lt;Resource name="jdbc/db_website" auth="Container" type="javax.sql.DataSource" driverClassName="org.postgresql.Driver" url="jdbc:postgresql://localhost:5432/db_website" username="website"/&gt; &lt;/Context&gt; </code></pre> <p>And here is the test code:</p> <pre><code>import java.io.*; import java.sql.*; import javax.naming.*; import javax.servlet.*; import javax.servlet.http.*; import javax.sql.*; import org.wswartzendruber.website.access.*; public class PostgresTest extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/plain"); try { Context initialContext = new InitialContext(); Context context = (Context)initialContext.lookup("java:comp/env"); DataSource dataSource = (DataSource)context.lookup("jdbc/db_website"); Connection connection = dataSource.getConnection(); NewsCategory[] newsCategory = NewsCategory.getNewsCategories(connection); connection.close(); } catch (NamingException e) { response.getWriter().println("ERROR: We have naming problems!"); } catch (SQLException se) { response.getWriter().println("ERROR: SQLException: " + se.getMessage()); } catch (AccessException ae) { response.getWriter().println("ERROR: AccessException: " + ae.getMessage()); } } } </code></pre> <p>I'm at a loss for what the issue is. I already have /usr/share/tomcat-6/lib/postgresql-8.4-702.jdbc4.jar in place. Moving it to /WEB-INF/lib makes no difference. It seems to me that it can see the resource entry in WEB-INF/web.xml, but that it can't pull the details from META-INF/context.xml. Assigning a password there also seems to make no difference.</p> <p>I'm up for whatever you guys have.</p> <hr> <p><strong>Update</strong>: here is the full stacktrace:</p> <pre><code>Sep 19, 2010 7:01:36 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet PostgresTest threw exception java.io.IOException: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null' at PostgresTest.doGet(PostgresTest.java:23) at javax.servlet.http.HttpServlet.service(Unknown Source) at javax.servlet.http.HttpServlet.service(Unknown Source) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Unknown Source) at org.apache.catalina.core.ApplicationFilterChain.doFilter(Unknown Source) at org.apache.catalina.core.StandardWrapperValve.invoke(Unknown Source) at org.apache.catalina.core.StandardContextValve.invoke(Unknown Source) at org.apache.catalina.core.StandardHostValve.invoke(Unknown Source) at org.apache.catalina.valves.ErrorReportValve.invoke(Unknown Source) at org.apache.catalina.core.StandardEngineValve.invoke(Unknown Source) at org.apache.catalina.connector.CoyoteAdapter.service(Unknown Source) at org.apache.jk.server.JkCoyoteHandler.invoke(Unknown Source) at org.apache.jk.common.HandlerRequest.invoke(Unknown Source) at org.apache.jk.common.ChannelSocket.invoke(Unknown Source) at org.apache.jk.common.ChannelSocket.processConnection(Unknown Source) at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(Unknown Source) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(Unknown Source) at java.lang.Thread.run(Thread.java:636) Caused by: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null' at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) at PostgresTest.doGet(PostgresTest.java:17) ... 17 more Caused by: java.lang.NullPointerException at org.postgresql.Driver.parseURL(Driver.java:567) at org.postgresql.Driver.acceptsURL(Driver.java:412) at java.sql.DriverManager.getDriver(DriverManager.java:268) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437) ... 20 more </code></pre>
0
2,252
SQL Query to return 24 hour, hourly count even when no values exist?
<p>I've written a query that groups the number of rows per hour, based on a given date range.</p> <pre><code>SELECT CONVERT(VARCHAR(8),TransactionTime,101) + ' ' + CONVERT(VARCHAR(2),TransactionTime,108) as TDate, COUNT(TransactionID) AS TotalHourlyTransactions FROM MyTransactions WITH (NOLOCK) WHERE TransactionTime BETWEEN CAST(@StartDate AS SMALLDATETIME) AND CAST(@EndDate AS SMALLDATETIME) AND TerminalId = @TerminalID GROUP BY CONVERT(VARCHAR(8),TransactionTime,101) + ' ' + CONVERT(VARCHAR(2),TransactionTime,108) ORDER BY TDate ASC </code></pre> <p>Which displays something like this:</p> <pre><code>02/11/20 07 4 02/11/20 10 1 02/11/20 12 4 02/11/20 13 1 02/11/20 14 2 02/11/20 16 3 </code></pre> <p>Giving the number of transactions and the given hour of the day.</p> <p>How can I display all hours of the day - from 0 to 23, and show 0 for those which have no values?</p> <p>Thanks.</p> <h2>UPDATE</h2> <p>Using the tvf below works for me for one day, however I'm not sure how to make it work for a date range.</p> <p>Using the temp table of 24 hours:</p> <pre><code> -- temp table to store hours of the day DECLARE @tmp_Hours TABLE ( WhichHour SMALLINT ) DECLARE @counter SMALLINT SET @counter = -1 WHILE @counter &lt; 23 BEGIN SET @counter = @counter + 1 --print INSERT INTO @tmp_Hours ( WhichHour ) VALUES ( @counter ) END SELECT MIN(CONVERT(VARCHAR(10),[dbo].[TerminalTransactions].[TransactionTime],101)) AS TDate, [@tmp_Hours].[WhichHour], CONVERT(VARCHAR(2),[dbo].[TerminalTransactions].[TransactionTime],108) AS TheHour, COUNT([dbo].[TerminalTransactions].[TransactionId]) AS TotalTransactions, ISNULL(SUM([dbo].[TerminalTransactions].[TransactionAmount]), 0) AS TransactionSum FROM [dbo].[TerminalTransactions] RIGHT JOIN @tmp_Hours ON [@tmp_Hours].[WhichHour] = CONVERT(VARCHAR(2),[dbo].[TerminalTransactions].[TransactionTime],108) GROUP BY [@tmp_Hours].[WhichHour], CONVERT(VARCHAR(2),[dbo].[TerminalTransactions].[TransactionTime],108), COALESCE([dbo].[TerminalTransactions].[TransactionAmount], 0) </code></pre> <p>Gives me a result of:</p> <pre><code>TDate WhichHour TheHour TotalTransactions TransactionSum ---------- --------- ------- ----------------- --------------------- 02/16/2010 0 00 4 40.00 NULL 1 NULL 0 0.00 02/14/2010 2 02 1 10.00 NULL 3 NULL 0 0.00 02/14/2010 4 04 28 280.00 02/14/2010 5 05 11 110.00 NULL 6 NULL 0 0.00 02/11/2010 7 07 4 40.00 NULL 8 NULL 0 0.00 02/24/2010 9 09 2 20.00 </code></pre> <p>So how can I get this to group properly?</p> <p>The other issue is that for some days there will be no transactions, and these days also need to appear.</p> <p>Thanks.</p>
0
1,348
Swift: use of 'self' in method call before super.init initializes self compile error
<p>I made a custom class that handles audio recording/playback and put a <code>Protocol</code> in that class. I implemented the <code>Protocol</code> in a <code>UIViewController</code> class and called my <code>setDelegate</code> method for my AudioHelper class.</p> <p>I am getting a compile error that has to do with my <code>init()</code>. Not exactly sure how to get rid of the error:</p> <p><strong><code>use of 'self' in method call 'setupAudioSession' before super.init initializes self</code></strong></p> <pre><code>override init() { setupAudioSession() super.init() } </code></pre> <p>How do I resolve this error? And why do I have to override init()?</p> <p><strong>My AudioHelper class</strong></p> <pre><code>import Foundation import AVFoundation class AudioHelper: NSObject, AVAudioRecorderDelegate { var audioSession: AVAudioSession? var audioRecorder: AVAudioRecorder? var delegate: AudioRecorderProtocol? class var sharedInstance: AudioHelper { struct Static { static var instance: AudioHelper? static var token: dispatch_once_t = 0 } dispatch_once(&amp;Static.token) { Static.instance = AudioHelper() } return Static.instance! } override init() { setupAudioSession() super.init() } func setDelegate(delegate: AudioRecorderProtocol) { self.delegate = delegate } func setupAudioSession() { audioSession = AVAudioSession.sharedInstance() audioSession?.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil) audioSession?.setActive(true, error: nil) } func createAudioMessageDirectory() { let fm = NSFileManager.defaultManager() if !fm.fileExistsAtPath(GlobalVars.kAudioMessageDirectory) { var error: NSError? if !fm.createDirectoryAtPath(GlobalVars.kAudioMessageDirectory, withIntermediateDirectories: true, attributes: nil, error: &amp;error) { println("Unable to create audio message directory: \(error)") } } } // MARK: Recording func beginRecordingAudio() { createAudioMessageDirectory() var filepath = GlobalVars.kAudioMessageDirectory.stringByAppendingPathComponent("audiofile.aac") var url = NSURL(fileURLWithPath: filepath) var recordSettings = [ AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 8000.0, AVNumberOfChannelsKey: 1, AVEncoderBitRateKey: 12800, AVLinearPCMBitDepthKey: 16, AVEncoderAudioQualityKey: AVAudioQuality.Max.rawValue ] println("Recorded Audio Message Saved: \(url!)") var error: NSError? audioRecorder = AVAudioRecorder(URL: url, settings: recordSettings as [NSObject : AnyObject], error: &amp;error) if error == nil { if audioRecorder != nil { audioRecorder!.delegate = self audioRecorder!.record() } } else { println(error!.localizedDescription) } } func stopRecordingAudio() { if audioRecorder != nil { audioRecorder!.stop() } } func handleRecordAudioButtonLongPressGestureForState(state: UIGestureRecognizerState) { if state == UIGestureRecognizerState.Ended { stopRecordingAudio() delegate?.onRecordAudioStop() } else if state == UIGestureRecognizerState.Began { beginRecordingAudio() delegate?.onRecordAudioStop() } } func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) { println("Record Audio Success: \(flag)") delegate?.onRecordAudioFinished() } func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder!, error: NSError!) { println("Record Audio Encode Error: \(error.localizedDescription)") } // MARK: Playback func playAudioMessageFromUrl(messageId: String) { if let url = NSURL(string: GlobalVars.kUrlAudioMessage + messageId) { if let data = NSData(contentsOfURL: url) { var error: NSError? = nil let audioPlayer = AVAudioPlayer(data: data, error: &amp;error) if error == nil { if audioPlayer != nil { audioPlayer.numberOfLoops = 0 audioPlayer.volume = 1.0 audioPlayer.prepareToPlay() audioPlayer.play() } } else { println("Audio playback error: \(error?.localizedDescription)") } } } } } protocol AudioRecorderProtocol { func onRecordAudioStart() func onRecordAudioStop() func onRecordAudioFinished() } </code></pre> <p><strong>My UIViewController that implements the protocol (cut out extraneous code)</strong></p> <pre><code>class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, AudioRecorderProtocol { let audioHelper = AudioHelper.sharedInstance let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() // addDemoMessages() setupGestureRecognizer() setupKeyboardObserver() setupViews() setupTableView() audioHelper.setDelegate(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) getUsersFromDb() getMessagesFromDb() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) setCurrentVC() tableView.reloadData() if partnerUserId != nil &amp;&amp; !db.doesUserExist(partnerUserId!) { HttpPostHelper.profileGet(userId: partnerUserId!) } requestMessagesFromServer() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() ViewHelper.scrollTableViewToBottom(tableView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func handleRecordAudioButtonHold(sender: UILongPressGestureRecognizer) { audioHelper.handleRecordAudioButtonLongPressGestureForState(sender.state) } func onRecordAudioStart() { dispatch_async(dispatch_get_main_queue(), { ViewHelper.showToast(NSLocalizedString("RECORDING", comment: "")) self.recordAudioButton.imageView!.image = UIImage(named: "RecordAudioClicked") }) } func onRecordAudioStop() { dispatch_async(dispatch_get_main_queue(), { self.recordAudioButton.imageView!.image = UIImage(named: "RecordAudio") }) } func onRecordAudioFinished() { HttpPostHelper.messageAudio(partnerUserId: partnerUserId) } func playAudioFromUrl(sender: UIButton) { let messageId = messages[sender.tag].id audioHelper.playAudioMessageFromUrl(messageId) } } </code></pre>
0
3,072
How to update MS Access Database (vb.net)
<p>I am created a journal program for an internship project and I am using a MS-Access Database. I am programming in <strong>VB.net</strong>. Now, I am trying to make it so that they can "Update" their journals, meaning that they click on their calendar date and it brings them to that journal if they have one for that date. If they have one for that date then it shows the title and journal text entry for that date. I want to make it so that any changes they have made to the journal (editing the textbox fields) are also changed in the database when they click the update button. Here's what i have so far</p> <pre><code> Private Sub COE_JournalBtn_Click(sender As System.Object, e As System.EventArgs) Handles COE_JournalBtn.Click If DateTimePicker1.Value &lt;&gt; Nothing Then If TitleTxt.Text &lt;&gt; "" Then If JournalTextRtxt.Text &lt;&gt; "" Then myConnection.Open() Dim DatePicked As String = DateTimePicker1.Value Dim cmd As OleDbCommand Dim str As String Try MyJournalTitle = TitleTxt.Text MyJournalText = JournalTextRtxt.Text str = "UPDATE Journals SET JournalTitle='" &amp; MyJournalTitle &amp; "', JournalText='" &amp; MyJournalText &amp; "' WHERE JournalDate=" &amp; DatePicked cmd = New OleDbCommand(str, myConnection) cmd.ExecuteNonQuery() myConnection.Close() Catch ex As Exception MessageBox.Show("There was an error processing your request. Please try again." &amp; vbCrLf &amp; vbCrLf &amp; _ "Original Error:" &amp; vbCrLf &amp; vbCrLf &amp; ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) myConnection.Close() End Try myConnection.Close() End If End If End If End Sub </code></pre> <p>Now my update string by itself is</p> <pre><code>"UPDATE Journals SET JournalTitle='" &amp; MyJournalTitle &amp; "', JournalText='" &amp; MyJournalText &amp; "' WHERE JournalDate=" &amp; DatePicked </code></pre> <p>Now, what happens, is absolutely nothing. No errorboxes come up. No messageboxes appear. The program doesn't freeze. And the database remains unchanged. What am I doing wrong? Is there an error in my code or something missing? Please help me because I really want to figure this out and i've been looking everywhere for a solution in VB.net and cannot find one that applies to me being that I am using MS-Access and NOT SQL.</p> <p>Thanks in advance, Richard Paulicelli</p>
0
1,036
VS Code can't install the Go tools
<p>I try to start using Go in VSCode. I've installed Go as well as Git and created a project in Code, containing a single <code>.go</code> file.</p> <p>When I type something, VSCode warns me that tools like <code>golint</code> are missing and prompts me to install them. I click on "Install all".</p> <p>Then the console shows this :</p> <pre><code>Installing 10 tools gocode gopkgs go-outline go-symbols guru gorename godef goreturns golint gotests Installing gocode SUCCEEDED Installing gopkgs SUCCEEDED Installing go-outline SUCCEEDED Installing go-symbols FAILED Installing guru FAILED Installing gorename FAILED Installing godef SUCCEEDED Installing goreturns FAILED Installing golint FAILED Installing gotests FAILED 6 tools failed to install. go-symbols: Error: Command failed: C:\Go\bin\go.exe get -u -v github.com/newhook/go-symbols github.com/newhook/go-symbols (download) Fetching https://golang.org/x/tools/go/buildutil?go-get=1 Parsing meta tags from https://golang.org/x/tools/go/buildutil?go-get=1 (status code 200) get "golang.org/x/tools/go/buildutil": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/go/buildutil?go-get=1 get "golang.org/x/tools/go/buildutil": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/go/buildutil: exit status 128 github.com/newhook/go-symbols (download) Fetching https://golang.org/x/tools/go/buildutil?go-get=1 Parsing meta tags from https://golang.org/x/tools/go/buildutil?go-get=1 (status code 200) get "golang.org/x/tools/go/buildutil": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/go/buildutil?go-get=1 get "golang.org/x/tools/go/buildutil": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/go/buildutil: exit status 128 guru: Error: Command failed: C:\Go\bin\go.exe get -u -v golang.org/x/tools/cmd/guru Fetching https://golang.org/x/tools/cmd/guru?go-get=1 Parsing meta tags from https://golang.org/x/tools/cmd/guru?go-get=1 (status code 200) get "golang.org/x/tools/cmd/guru": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/cmd/guru?go-get=1 get "golang.org/x/tools/cmd/guru": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/cmd/guru: exit status 128 Fetching https://golang.org/x/tools/cmd/guru?go-get=1 Parsing meta tags from https://golang.org/x/tools/cmd/guru?go-get=1 (status code 200) get "golang.org/x/tools/cmd/guru": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/cmd/guru?go-get=1 get "golang.org/x/tools/cmd/guru": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/cmd/guru: exit status 128 gorename: Error: Command failed: C:\Go\bin\go.exe get -u -v golang.org/x/tools/cmd/gorename Fetching https://golang.org/x/tools/cmd/gorename?go-get=1 Parsing meta tags from https://golang.org/x/tools/cmd/gorename?go-get=1 (status code 200) get "golang.org/x/tools/cmd/gorename": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/cmd/gorename?go-get=1 get "golang.org/x/tools/cmd/gorename": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/cmd/gorename: exit status 128 Fetching https://golang.org/x/tools/cmd/gorename?go-get=1 Parsing meta tags from https://golang.org/x/tools/cmd/gorename?go-get=1 (status code 200) get "golang.org/x/tools/cmd/gorename": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/cmd/gorename?go-get=1 get "golang.org/x/tools/cmd/gorename": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/cmd/gorename: exit status 128 goreturns: Error: Command failed: C:\Go\bin\go.exe get -u -v sourcegraph.com/sqs/goreturns Fetching https://sourcegraph.com/sqs/goreturns?go-get=1 Parsing meta tags from https://sourcegraph.com/sqs/goreturns?go-get=1 (status code 200) get "sourcegraph.com/sqs/goreturns": found meta tag main.metaImport{Prefix:"sourcegraph.com/sqs/goreturns", VCS:"git", RepoRoot:"https://github.com/sqs/goreturns"} at https://sourcegraph.com/sqs/goreturns?go-get=1 sourcegraph.com/sqs/goreturns (download) github.com/sqs/goreturns (download) Fetching https://golang.org/x/tools/imports?go-get=1 Parsing meta tags from https://golang.org/x/tools/imports?go-get=1 (status code 200) get "golang.org/x/tools/imports": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/imports?go-get=1 get "golang.org/x/tools/imports": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/imports: exit status 128 Fetching https://sourcegraph.com/sqs/goreturns?go-get=1 Parsing meta tags from https://sourcegraph.com/sqs/goreturns?go-get=1 (status code 200) get "sourcegraph.com/sqs/goreturns": found meta tag main.metaImport{Prefix:"sourcegraph.com/sqs/goreturns", VCS:"git", RepoRoot:"https://github.com/sqs/goreturns"} at https://sourcegraph.com/sqs/goreturns?go-get=1 sourcegraph.com/sqs/goreturns (download) github.com/sqs/goreturns (download) Fetching https://golang.org/x/tools/imports?go-get=1 Parsing meta tags from https://golang.org/x/tools/imports?go-get=1 (status code 200) get "golang.org/x/tools/imports": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/imports?go-get=1 get "golang.org/x/tools/imports": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/imports: exit status 128 golint: Error: Command failed: C:\Go\bin\go.exe get -u -v github.com/golang/lint/golint github.com/golang/lint (download) Fetching https://golang.org/x/tools/go/gcexportdata?go-get=1 Parsing meta tags from https://golang.org/x/tools/go/gcexportdata?go-get=1 (status code 200) get "golang.org/x/tools/go/gcexportdata": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/go/gcexportdata?go-get=1 get "golang.org/x/tools/go/gcexportdata": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/go/gcexportdata: exit status 128 github.com/golang/lint (download) Fetching https://golang.org/x/tools/go/gcexportdata?go-get=1 Parsing meta tags from https://golang.org/x/tools/go/gcexportdata?go-get=1 (status code 200) get "golang.org/x/tools/go/gcexportdata": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/go/gcexportdata?go-get=1 get "golang.org/x/tools/go/gcexportdata": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/go/gcexportdata: exit status 128 gotests: Error: Command failed: C:\Go\bin\go.exe get -u -v github.com/cweill/gotests/... github.com/cweill/gotests (download) Fetching https://golang.org/x/tools/imports?go-get=1 Parsing meta tags from https://golang.org/x/tools/imports?go-get=1 (status code 200) get "golang.org/x/tools/imports": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/imports?go-get=1 get "golang.org/x/tools/imports": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/imports: exit status 128 github.com/cweill/gotests (download) Fetching https://golang.org/x/tools/imports?go-get=1 Parsing meta tags from https://golang.org/x/tools/imports?go-get=1 (status code 200) get "golang.org/x/tools/imports": found meta tag main.metaImport{Prefix:"golang.org/x/tools", VCS:"git", RepoRoot:"https://go.googlesource.com/tools"} at https://golang.org/x/tools/imports?go-get=1 get "golang.org/x/tools/imports": verifying non-authoritative meta tag Fetching https://golang.org/x/tools?go-get=1 Parsing meta tags from https://golang.org/x/tools?go-get=1 (status code 200) golang.org/x/tools (download) # cd C:\Users\user\go\src\golang.org\x\tools; git pull --ff-only fatal: Not a git repository (or any of the parent directories): .git package golang.org/x/tools/imports: exit status 128 </code></pre> <p>Some tools are able to install, others are not. I can't do anything about the <code>Not a git repository</code> error because it's an automated process and I'm not the one typing the git commands.</p> <p>I tried installing the tools separately in PowerShell and I get the same errors. My go directory is created (in <code>%USERPROFILE%\go</code>) and the <code>GOPATH</code> is set correctly.</p> <p>Any ideas ?</p>
0
4,639