title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Run-time error '7': Out of memory
|
<p>I'm trying to edit embedded charts in Word documents. My source code is below. It has worked a long time but not for the last two days. I get this error:</p>
<blockquote>
<p>Run-time error '7': Out of memory</p>
</blockquote>
<p>I have searched a lot , but I don't understand the problem. When I shutdown computer and after open it, then it works correctly, but after I get error again.</p>
<p>It gives error in this part:</p>
<pre><code> 'create range with Cell
Set oChart = oInShapes.Chart
oChart.ChartData.Activate ' ***Note: It gives error here***
'Set oWorkbook = oChart.ChartData.Workbook
Set oWorksheet = oChart.ChartData.Workbook.Worksheets("Tabelle1")
Set oRange = oWorksheet.Range(Cell)
</code></pre>
<hr>
<pre><code>Public Sub updatechart(Doc As word.Application, ChartName As String, ChartTitle As String, Cell As String, data As String)`
Dim oInShapes As word.InlineShape
Dim oChart As word.Chart
Dim oWorksheet As Excel.Worksheet
'Dim oWorkbook As Excel.Workbook
Dim columnArray() As String
Dim rowArray() As String
Dim oRange As Range
Dim i As Integer
Dim j As Integer
For Each oInShapes In Doc.ActiveDocument.InlineShapes
' Check Shape type and Chart Title
If oInShapes.HasChart Then
'create range with Cell
Set oChart = oInShapes.Chart
oChart.ChartData.Activate ' ***Note: It gives error here***
'Set oWorkbook = oChart.ChartData.Workbook
Set oWorksheet = oChart.ChartData.Workbook.Worksheets("Tabelle1")
Set oRange = oWorksheet.Range(Cell)
' Commet for debug
'oWorksheet.Range("B33") = (ChartTitle & 33)
' Split text
columnArray = Split(data, SeperateChar)
For i = LBound(columnArray) To UBound(columnArray)
rowArray = Split(Trim(columnArray(i)), " ")
' Set Title. For example; ChartTitle = "XY" ----- Table Titles ----> | XY1 | XY2 | XY2 | ....
' After Set Value | 0,33| 0,1 | 0,46| ....
oRange.Cells(1, i + 1) = ChartTitle & (i + 1)
For j = LBound(rowArray) To UBound(rowArray)
' Set Values
oRange.Cells(j + 2, i + 1) = CDbl(rowArray(j))
Next j
Next i
'oWorkbook.Close
oChart.Refresh
End If
Next
Set oInShapes = Nothing
Set oChart = Nothing
Set oWorksheet = Nothing
'Set oWorkbook = Nothing
Erase rowArray, columnArray
End Sub
</code></pre>
| 0 | 1,351 |
MVC HTML.RenderAction – Error: Duration must be a positive number
|
<p>On my website I want the user to have the ability to login/logout from any page. When the user select login button a modal dialog will be present to the user for him to enter in his credentials.</p>
<p>Since login will be on every page, I thought I would create a partial view for the login and add it to the layout page. But when I did this I got the following error: <strong>Exception Details: System.InvalidOperationException: Duration must be a positive number.</strong></p>
<p>There are other ways to work around this that would not using partial views, but I believe this should work.</p>
<p>So to test this, I decided to make everything simple with the following code:</p>
<p>Created a layout page with the following code</p>
<pre><code>@{Html.RenderAction("_Login", "Account");}
</code></pre>
<p>In the AccountController:</p>
<pre><code>public ActionResult _Login()
{
return PartialView("_Login");
}
</code></pre>
<p>Partial View _Login</p>
<pre><code><a id="signin">Login</a>
</code></pre>
<p>But when I run this simple version this I still get this error:
<strong>Exception Details: System.InvalidOperationException: Duration must be a positive number.</strong></p>
<p>Source of error points to "@{Html.RenderAction("_Login", "Account");}"</p>
<p>There are some conversations on the web that are similar to my problem, which identifies this as bug with MVC (see links below). But the links pertain to Caching, and I'm not doing any caching.</p>
<p>OuputCache Cache Profile does not work for child actions<br />
<a href="http://aspnet.codeplex.com/workitem/7923" rel="noreferrer">http://aspnet.codeplex.com/workitem/7923</a></p>
<p>Asp.Net MVC 3 Partial Page Output Caching Not Honoring Config Settings
<a href="https://stackoverflow.com/questions/4797968/asp-net-mvc-3-partial-page-output-caching-not-honoring-config-settings/4800140#4800140">Asp.Net MVC 3 Partial Page Output Caching Not Honoring Config Settings</a></p>
<p>Caching ChildActions using cache profiles won't work?
<a href="https://stackoverflow.com/questions/4728958/caching-childactions-using-cache-profiles-wont-work/4869434#4869434">Caching ChildActions using cache profiles won't work?</a></p>
<p>I'm not sure if this makes a difference, but I'll go ahead and add it here. I'm using MVC 3 with Razor.</p>
<hr />
<p>Update<br />
Stack Trace</p>
<pre><code>[InvalidOperationException: Duration must be a positive number.]
System.Web.Mvc.OutputCacheAttribute.ValidateChildActionConfiguration() +624394
System.Web.Mvc.OutputCacheAttribute.OnActionExecuting(ActionExecutingContext filterContext) +127
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +72
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +784922
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +314
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976
System.Web.Mvc.Controller.ExecuteCore() +159
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54
System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +15
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +41
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1363
[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +2419
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +275
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +94
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +838
System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +56
ASP._Page_Views_Shared_SiteLayout_cshtml.Execute() in c:\Projects\prj Projects\prj\Source\Presentation\prj.PublicWebSite\Views\Shared\SiteLayout.cshtml:80
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +280
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +104
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +173
System.Web.WebPages.WebPageBase.Write(HelperResult result) +89
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +234
System.Web.WebPages.WebPageBase.PopContext() +234
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +384
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +33
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +784900
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +784900
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976
System.Web.Mvc.Controller.ExecuteCore() +159
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371
</code></pre>
<hr />
<p>Update<br />
When I Break in Code, it errors at @{Html.RenderAction("_Login", "Account");} with the following exception. The inner exception</p>
<pre><code>Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter)
at System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues)
at ASP._Page_Views_Shared_SiteLayout_cshtml.Execute() in c:\Projects\prj Projects\prj\Source\Presentation\prj.PublicWebSite\Views\Shared\SiteLayout.cshtml:line 80
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.WebPages.WebPageBase.Write(HelperResult result)
at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body)
at System.Web.WebPages.WebPageBase.PopContext()
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
</code></pre>
<p><img src="https://i.stack.imgur.com/erXOV.jpg" alt="enter image description here" /></p>
<hr />
<p>Answer
Thanks Darin Dimitrov</p>
<p>Come to find out, my AccountController had the following attribute</p>
<blockquote>
<p>[System.Web.Mvc.OutputCache(NoStore =true, Duration = 0, VaryByParam = "*")].</p>
</blockquote>
<p>I don't believe this should caused a problem, but when I removed the attribute everything worked.</p>
<p>BarDev</p>
| 0 | 3,040 |
Uncaught TypeError: Cannot read property 'uid' of null using website
|
<p>I want to get registered user details from firestore into html page. When user clicks my profile page it navigate to next html page with fields like first name and last name etc.. . This fields are already entered at the time of signup page. so i want get those details from firestore into next html page. But i got the error like "Cannot read property 'uid' of null ". How to resolve that problem this is my html page :</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<title> deyaPay</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-auth.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-firestore.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script>
var config = {
apiKey: "AIzaSyAJsAstiMsrB2QGJyoqiTELw0vsWFVVahw",
authDomain: "websignin-79fec.firebaseapp.com",
databaseURL: "https://websignin-79fec.firebaseio.com",
projectId: "websignin-79fec",
storageBucket: "",
messagingSenderId: "480214472501"
};
firebase.initializeApp(config);
</script>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-firestore.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<style>
// css goes here..
</style>
<script type="text/javascript">
function myProfile() {
var user = firebase.auth().currentUser.uid;
var db = firebase.firestore();
var docRef = db.collection("deyaPayusers").doc(user);
docRef.get().then(function(doc) {
if(doc && doc.exists) {
const myData = doc.data();
const ffname = myData.FirstName;
const llname = myData.LastName;
const phonen = myData.PhoneNumber;
document.getElementById("fname").value = ffname;
document.getElementById("lname").value = llname;
document.getElementById("phone").value = phonen;
}
}).catch(function(error) {
console.log("Got an error: ",error);
});
}
</script>
</head>
<body onload='myProfile()'>
<div class= "login-form">
<form method="post">
<h2>Profile</h2>
<div class="form-group">
<input type="text" name="firstname" id="fnmae" placeholder="FirstName" class="form-control" >
</div>
<div class="form-group">
<input type="text" name="lastname" id="lnmae" placeholder="LastName" class="form-control" >
</div>
<div class="form-group">
<input type="text" name="phone" id="phone" placeholder="PhoneNumber" class="form-control" >
</div>
</form>
</div>
</body>
</html>
</code></pre>
| 0 | 1,929 |
TicTacToe using two dimensional arrays
|
<p>I am trying to create a program that does the game TicTacToe. I have finished creating
all the methods and I just need to create the driver program. Before creating the
driver program, I tried to just print the board along with a character but I don't
think my methods are correct. Here is what my error looks like:</p>
<pre><code>java.lang.ArrayIndexOutOfBoundsException: 3
at TicTacToeBoard.move(TicTacToeBoard.java:75)
at TicTacToe.main(TicTacToe.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
</code></pre>
<p>Here are my two programs: </p>
<p>This is my driver program that I can't seem to complete. The last thing that will be shown is the
template so that you have the idea of how each program works. </p>
<pre><code>class TicTacToe
{
public static void main(String [] args)
{
//System.out.println("Welcome! Tic-Tac-Toe is a two player game.");
//System.out.println("Enter player one's name: ");
TicTacToeBoard game = new TicTacToeBoard();
System.out.println(game.toString());
//int count = 0;
game.move('x', 1, 3);
// game.move('o', 1, 1);
/* while (game.gameWon() !true || count != 9)
{
System.out.print(game.move());
System.out.print(game.isEmpty());
}*/
}
}
</code></pre>
<p>This is where all the methods are......</p>
<pre><code>class TicTacToeBoard
{
private char [][] board = new char[3][3];
String b;
// This a new constructor that creates a tic-tac-toe board
public TicTacToeBoard()
{
for (int rows = 0; rows < board.length; rows++)// creates rows
{
for (int columns = 0; columns <board[rows].length;columns++)// creates columns
{
//System.out.println("| ");
board[rows][columns] = ' ';
//System.out.println(" |\n" );
}
}
}
// creates a string form of the tic-tac-toe board and allows the user
// to access it during the game.
public String toString()
{
String b = "";
// creates a vertical bar at the beginning and the end of each row
for (int rows = 0; rows < board.length; rows++)
{
b += "| ";
// adds a space for each row and column character in tic-tac-toe board.
for (int columns = 0; columns < board[rows].length; columns++)
{
b += board[rows][columns] + " ";
}
b += "|\n";// prints a | space space space | and breaks off to create two new lines.
}
return b; // prints the tic-tac-toe board to be accessed by the user.
}
String move(char x, int rows, int columns)
{
String b = "";
// creates a vertical bar at the beginning and the end of each row
for (int r = 0; r < board.length; r++)
{
b += "| ";
for (int c = 0; c < board[r].length; c++)
{
b += board[r][c] + " "; //prints 3 spaces on each line.
// prints string character from user input if row and column not equal to zero
if (board[rows - 1][columns - 1] >= 0 && board[rows - 1][columns - 1] <= 2 )
{
board[rows - 1][columns - 1] = x;// prints character in the specified index from user input
b += board[rows - 1][columns - 1];// prints out the board and the new character in specified space.
}
else if (board[rows - 1][columns - 1] < 0) // makes user pick another choice
return "ILLEGAL MOVE, TRY AGAIN!";
// adds a space for each row and column character in tic-tac-toe board.
}
b += "|\n";// prints a | space space space | and breaks off to create two new lines.
}
return b; // prints the tic-tac-toe board to be accessed by the user.
}
// checks if a space character is empty
void isEmpty(char x, int row, int col)
{
if (board [row - 1][col - 1] == ' ')
board[row - 1][col - 1] = x;
else // makes user pick another row and column if space character is not empty
System.out.println("ILLEGAL CHOICE, PICK AGAIN!");
}
// checks if game is won
public boolean gameWon(int row, int col)
{
if ((board[2][0] == board[1][1]) && (board[2][0] == board[0][2]))
return true;
else if ((board[2][0] != board[1][1]) && (board[2][0] != board[0][2]))
return false;
if ((board[2][2] == board[1][1])&& (board[2][2] == board[0][0]))
return true;
else if ((board[2][2] != board[1][1])&& (board[2][2] != board[0][0]))
return false;
if ((board[0][0] == board[1][0]) && (board[0][0] == board[2][0]))
return true;
else if ((board[0][0] != board[1][0]) && (board[0][0] != board[2][0]))
return false;
if ((board[0][1] == board[1][1]) && (board[0][1] == board[2][1]))
return true;
else if ((board[0][1] != board[1][1]) && (board[0][1] != board[2][1]))
return false;
if ((board[0][2] == board[1][2]) && (board[0][2] == board[2][2]))
return true;
else if ((board[0][2] != board[1][2]) && (board[0][2] != board[2][2]))
return false;
if ((board[0][0] == board[0][1]) && (board[0][0] == board[0][2]))
return true;
else if ((board[0][0] != board[0][1]) && (board[0][0] != board[0][2]))
return false;
if ((board[1][0] == board[1][1]) && (board[1][0] == board[1][2]))
return true;
else if ((board[1][0] != board[1][1]) && (board[1][0] != board[1][2]))
return false;
if ((board[2][0] == board[2][1]) && (board[2][0] == board[2][2]))
return true;
else
return false;
}
}
</code></pre>
<p>Here is the template for the whole thing!!!!!</p>
<pre><code>class TicTacToe
{
public static void main (String [] args)
{
TicTacToeBoard b = new TicTacToeBoard();
while (game not over)
{
swtich player
increment turn counter
until user enters a valid move
{
prompt for move
}
make move
b.makeMove (player, row, col);
print board
System.out.println(b);
}
print outcome
}
}
class TicTacToeBoard
{
private char [][] board = ...;
public TicTacToeBoard()
{
initialize board with spaces
}
public void makeMove (char c, int row, int col)
{
store symbol in specified position
}
public boolean isEmpty(int row, int col)
{
return true if square is unfilled
}
public boolean gameWon()
{
check board for a win
}
public String toString ()
{
return String representation of board
}
}
</code></pre>
| 0 | 2,754 |
Error: E0902: Exception occured: [User: Root is not allowed to impersonate root
|
<p>I am trying to follow the steps given at <a href="http://www.rohitmenon.com/index.php/apache-oozie-installation/" rel="nofollow noreferrer">http://www.rohitmenon.com/index.php/apache-oozie-installation/</a>
Note: I am not using cloudera distibution of hadoop</p>
<p>The above link is similar to <a href="http://oozie.apache.org/docs/4.0.1/DG_QuickStart.html" rel="nofollow noreferrer">http://oozie.apache.org/docs/4.0.1/DG_QuickStart.html</a>
but with more descriptive seems to me
however while running the below command as a root user i am getting exception
./bin/oozie-setup.sh sharelib create -fs </p>
<p>Note: i have two live node shown at dfshealth.jsp . and i have updated the core-site.xml for all three(including namenode) with property as below</p>
<pre><code> <property>
<name>hadoop.proxyuser.root.hosts</name>
<value>*</value>
</property>
<property>
<name>hadoop.proxyuser.root.groups</name>
<value>*</value>
</property>
</code></pre>
<p>i understand this is point where i am making mistake Could someone please guide me </p>
<pre><code>Stacktrace
org.apache.oozie.service.HadoopAccessorException: E0902: Exception occured: [User: root is not allowed to impersonate root]
at
org.apache.oozie.service.HadoopAccessorService.createFileSystem(HadoopAccessorService.java:430)
at org.apache.oozie.tools.OozieSharelibCLI.run(OozieSharelibCLI.java:144)
at org.apache.oozie.tools.OozieSharelibCLI.main(OozieSharelibCLI.java:52)
Caused by: org.apache.hadoop.ipc.RemoteException: User: root is not allowed to impersonate root
at org.apache.hadoop.ipc.Client.call(Client.java:1107)
at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:229)
at com.sun.proxy.$Proxy5.getProtocolVersion(Unknown Source)
at org.apache.hadoop.ipc.RPC.getProxy(RPC.java:411)
at org.apache.hadoop.hdfs.DFSClient.createRPCNamenode(DFSClient.java:135)
at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:276)
at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:241)
at org.apache.hadoop.hdfs.DistributedFileSystem.initialize(DistributedFileSystem.java:100)
at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1411)
at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1429)
at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:254)
at org.apache.oozie.service.HadoopAccessorService$2.run(HadoopAccessorService.java:422)
at org.apache.oozie.service.HadoopAccessorService$2.run(HadoopAccessorService.java:420)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1136)
at org.apache.oozie.service.HadoopAccessorService.createFileSystem(HadoopAccessorService.java:420)
... 2 more
--------------------------------------
</code></pre>
<p>Note: <a href="https://stackoverflow.com/questions/16582126/getting-e0902-exception-occured-user-oozie-is-not-allowed-to-impersonate-ooz">Getting E0902: Exception occured: [User: oozie is not allowed to impersonate oozie]</a> i have followed this link as well but not able to solve my problem </p>
<pre><code>if i change the core-site.xml as below only for NameNode
<property>
<name>hadoop.proxyuser.hadoop.hosts</name>
<value>[NAMENODE IP]</value>
</property>
<property>
<name>hadoop.proxyuser.hadoop.groups</name>
<value>hadoop</value>
</property>
</code></pre>
<p>I get the exception as
Unauthorized connection for super-user: hadoop</p>
| 0 | 1,857 |
Inserting data into a table in WordPress database using WordPress $wpdb
|
<p>I am starting out plugin development and have followed the tutorials on the WordPress Codex sites. I am now stuck - I have a database called "wp_imlisteningto", where the <code>wp_</code> was inserted using:</p>
<pre><code>$table_name = $wpdb->prefix . "imlisteningto";
</code></pre>
<p>When the plugin is activated. </p>
<p>The database itself has three columns, set up when the plugin is activated:</p>
<pre><code>$sql = "CREATE TABLE $table_name (
id mediumint(9) AUTO_INCREMENT,
album VARCHAR(50),
artist VARCHAR(50),
PRIMARY KEY (id)
);";
</code></pre>
<p>I am trying to insert data (by creating a new row) into this database from a php form.</p>
<p>Within the WordPress admin, I create a new page which has the very simple form:</p>
<pre><code><form action="/wp-content/plugins/listeningto/formhtml.php" method="post">
Album: <input type="text" name="album" />
Artist: <input type="text" name="artist" />
<input type="submit">
</form>
</code></pre>
<p>Which as you can see calls <code>formhtml.php</code>, which is:</p>
<pre><code><?php
global $wpdb;
$wpdb->insert( $table_name, array( 'album' => $_POST['album'], 'artist' => $_POST['artist'] ), array( '$s', '$s' ) );
?>
</code></pre>
<p>When I submit the form, I get an <code>Error 500.0</code> when running the plugin in Worpdress on <code>IIS7.0</code>, and a <code>"Page Not Found"</code> when running on another web server which runs <code>apache</code>.</p>
<p>If I change <code>formhtml.php</code> to:</p>
<pre><code><?php
echo $_POST['album'];
echo $_POST['artist'];
?>
</code></pre>
<p>Works fine - I get the album and artist that I put in the form. Obviously something I'm doing wrong when inserting the data (in a new row) into the database.</p>
<p>Any thoughts as to what that might be?</p>
<p>UPDATE</p>
<p>Ok, so if I update <code>formhtml.php</code> with this:</p>
<pre><code><?php
require_once('../../../wp-config.php');
$table_name = $wpdb->prefix . "imlisteningto";
$wpdb->insert( $table_name, array( 'album' => $_POST['album'], 'artist' => $_POST['artist'] ), array( '$s', '$s' ) );
?>
</code></pre>
<p>I no longer get an error message, but data still doesn't get put into the database.</p>
<p><strong>UPDATE 2</strong></p>
<p><strong>This worked for me:</strong></p>
<pre><code><?php
require_once('../../../wp-config.php');
global $wpdb;
$table_name = $wpdb->prefix . "imlisteningto";
$wpdb->insert( $table_name, array( 'album' => $_POST['album'], 'artist' => $_POST['artist'] ) );
?>
</code></pre>
<p>as did this:</p>
<pre><code><?php
require_once('../../../wp-load.php');
global $wpdb;
$table_name = $wpdb->prefix . "imlisteningto";
$wpdb->insert( $table_name, array( 'album' => $_POST['album'], 'artist' => $_POST['artist'] ) );
?>
</code></pre>
<p>So, for some reason <code>$wpdb</code> was not working unless I required either <code>wp-config</code> or <code>wp-load.php</code>. If include <code>wp-load.php</code>, <code>$wpdb</code> gets values and all is well.</p>
| 0 | 1,182 |
CrudRepository save method not returning updated entity
|
<p>I'm working with Spring and in it <code>spring-data-jpa:1.7.0.RELEASE</code> and <code>hibernate-jpa-2.1-api:1.0.0.Final</code>. My database is a MySQL. In a integration test, when I save an entity, the <code>entityRepository.save()</code> method does not return a update version of it (with the auto-incremented id populated for example), thus I can see it is in the database.</p>
<p>Here's my configuration class:</p>
<pre><code>//@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "core.repository")
@Configuration
@PropertySource("classpath:application.properties")
public class JPAConfiguration {
@Autowired
private Environment env;
private
@Value("${db.driverClassName}")
String driverClassName;
private
@Value("${db.url}")
String url;
private
@Value("${db.username}")
String user;
private
@Value("${db.password}")
String password;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setDatabasePlatform(env.getProperty("hibernate.dialect"));
final LocalContainerEntityManagerFactoryBean em =
new LocalContainerEntityManagerFactoryBean();
em.setJpaVendorAdapter(vendorAdapter);
em.setPackagesToScan(new String[]{"core.persistence"});
em.setDataSource(dataSource());
em.afterPropertiesSet();
return em;
}
@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
@Bean
public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
</code></pre>
<p>Here's my test class:</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JPAConfiguration.class})
//@Transactional
//@TransactionConfiguration(defaultRollback = true)
public class AgencyRepositoryIntegrationTests {
@Autowired
AgencyRepository agencyRepository;
@Test
public void testThatAgencyIsSavedIntoRepoWorks() throws Exception {
Agency c = DomainTestData.getAgency();
Agency d = agencyRepository.save(c);
// here d equals to c but both have id 0.
Collection<Agency> results = Lists.newArrayList(agencyRepository.findAll());
//here results != null and it does contain the agency object.
assertNotNull(results);
}
}
</code></pre>
<p>I end up commenting the Transactional annotations (both in the test and in the configuration class) due to research other questions in stackoverflow, but it did not work.</p>
<p>Thanks</p>
| 0 | 1,244 |
WebGL - Invalid Operation useProgram
|
<p>I'm learning WebGL and am on <a href="http://learningwebgl.com/blog/?p=684" rel="noreferrer">this</a> tutorial that has to do with lighting. I'm new to JavaScript so I'm not so good at debugging it yet. I keep getting these errors, anyone know why I'm getting them and how to fix it?</p>
<pre><code>WebGL: INVALID_OPERATION: useProgram: program not valid http://insanergamer.zxq.net/:1
WebGL: INVALID_OPERATION: getAttribLocation: program not linked http://insanergamer.zxq.net/:1
WebGL: INVALID_OPERATION: getUniformLocation: program not linked http://insanergamer.zxq.net/:1
WebGL: too many errors, no more errors will be reported to the console for this context.
</code></pre>
<p><strong>index.html</strong></p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf 8" />
<link rel="stylesheet" href="main.css">
<script type="text/javascript" language="javascript" src="gl-matrix.js"></script>
<script type="text/javascript" language="javascript" src="webgl-utils.js"></script>
<script type="text/javascript" language="javascript" src="first.js"></script>
<script id="shader-fs" type="x-shader/x-fragment">
precision mediump float;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
uniform sampler2D uSampler;
void main(void) {
vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
gl_FragColor = vec4(textureColor.rgb * vLightWeighting, textureColor.a);
}
</script>
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat3 uNMatrix;
uniform vec3 uAmbientColor;
uniform vec3 uLightingDirection;
uniform vec3 uDirectionalColor;
uniform bool uUseLighting;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vTextureCoord = aTextureCoord;
if (!uUseLighting) {
vLightWeighting = vec3(1.0, 1.0, 1.0);
} else {
vec3 transformedNormal = uNMatrix * aVertexNormal;
float directionalLightWeighting = max(dot(transformedNormal, uLightingDirection), 0.0);
vLightWeighting = uAmbientColor + uDirectionalColor * directionalLightWeighting;
}
</script>
</head>
<body onLoad="webGLStart()">
<header>
</header>
<nav>
</nav>
<section>
<h3><a href="todo.html">Link to the TODO page.</a></h3>
<form>
<input type="checkbox" id="lighting"></input>Lighting On/Off<br />
Ambient Lighting Color: Red:<input type="text" id="ambientR"></input> Green:<input type="text" id="ambientG"></input> Blue:<input type="text" id="ambientB"></input> <br />
Light Direction: X:<input type="text" id="lightDirectionX"></input> Y:<input type="text" id="lightDirectionY"></input> Z:<input type="text" id="lightDirectionZ"></input> <br />
Direction Lighting Color: Red:<input type="text" id="directionalR"></input> Green:<input type="text" id="directionalG"></input> Blue:<input type="text" id="directionalB"></input> <br />
</form>
<p>Press 'F' to change Texture quality.</p>
<p>Use Arrow Keys to rotate cube.</p>
<p>Page Up and Page down to zoom in and out.</p>
<canvas canvasProperties="prop" id="canvas1" style="border: none;" width="1280" height="720"></canvas>
<article>
<header>
</header>
<footer>
</footer>
</article>
</section>
<aside>
</aside>
<footer>
</footer>
</body>
</code></pre>
<p></p>
<p><strong>first.js</strong></p>
<pre><code> var gl;
function initGL(canvas) {
try {
gl = canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
} catch (e) {
}
if (!gl) {
alert("Could not initialise WebGL, sorry :-(");
}
}
function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
var shaderProgram;
function initShaders() {
var fragmentShader = getShader(gl, "shader-fs");
var vertexShader = getShader(gl, "shader-vs");
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram);
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);
shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal");
gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);
shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, "uNMatrix");
shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler");
shaderProgram.useLightingUniform = gl.getUniformLocation(shaderProgram, "uUseLighting");
shaderProgram.ambientColorUniform = gl.getUniformLocation(shaderProgram, "uAmbientColor");
shaderProgram.lightingDirectionUniform = gl.getUniformLocation(shaderProgram, "uLightingDirection");
shaderProgram.directionalColorUniform = gl.getUniformLocation(shaderProgram, "uDirectionalColor");
}
var cubeTextures = Array();
function initTexture()
{
var cubeImage = new Image();
for(var i=0;i < 3; i++)
{
var texture = gl.createTexture();
texture.image = cubeImage;
cubeTextures.push(texture);
}
cubeImage.onload = function()
{
handleLoadedTexture(cubeTextures);
}
cubeImage.src = "cube.png";
}
function handleLoadedTexture(texture)
{
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.bindTexture(gl.TEXTURE_2D,texture[0]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture[0].image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.bindTexture(gl.TEXTURE_2D, texture[1]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture[1].image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.bindTexture(gl.TEXTURE_2D, texture[2]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture[2].image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
gl.generateMipmap(gl.TEXTURE_2D);
gl.bindTexture(gl.TEXTURE_2D, null);
}
var mvMatrix = mat4.create();
var mvMatrixStack = []
var pMatrix = mat4.create();
function mvPushMatrix()
{
var copy = mat4.create();
mat4.set(mvMatrix, copy);
mvMatrixStack.push(copy);
}
function mvPopMatrix()
{
if(mvMatrixStack.length == 0)
{
throw "No Matrix to Pop!";
}
mvMatrix = mvMatrixStack.pop();
}
function degToRad(degrees)
{
return degrees * Math.PI / 180;
}
function setMatrixUniforms() {
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
var normalMatrix = mat3.create();
mat4.toInverseMat3(mvMatrix, normalMatrix);
mat3.transpose(normalMatrix);
gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, normalMatrix);
}
var cubeVertexPositionBuffer;
var cubeVertexTextureCoordBuffer;
var cubeVertexIndexBuffer;
function initBuffers() {
cubeVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
vertices = [
// Front face
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
cubeVertexPositionBuffer.itemSize = 3;
cubeVertexPositionBuffer.numItems = 24;
cubeVertexNormalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexNormalBuffer);
var vertexNormals = [
// Front face
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
// Back face
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
// Top face
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
// Bottom face
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
// Right face
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
// Left face
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexNormals), gl.STATIC_DRAW);
cubeVertexNormalBuffer.itemSize = 3;
cubeVertexNormalBuffer.numItems = 24;
cubeVertexTextureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
var textureCoords = [
// Front face
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Back face
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
0.0, 0.0,
// Top face
0.0, 1.0,
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
// Bottom face
1.0, 1.0,
0.0, 1.0,
0.0, 0.0,
1.0, 0.0,
// Right face
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
0.0, 0.0,
// Left face
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoords), gl.STATIC_DRAW);
cubeVertexTextureCoordBuffer.itemSize = 2;
cubeVertexTextureCoordBuffer.numItems = 24;
cubeVertexIndexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
var cubeVertexIndices = [
0, 1, 2, 0, 2, 3, // Front face
4, 5, 6, 4, 6, 7, // Back face
8, 9, 10, 8, 10, 11, // Top face
12, 13, 14, 12, 14, 15, // Bottom face
16, 17, 18, 16, 18, 19, // Right face
20, 21, 22, 20, 22, 23 // Left face
]
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW);
cubeVertexIndexBuffer.itemSize = 1;
cubeVertexIndexBuffer.numItems = 36;
}
var rCubeX = 0;
var SpeedX = 0;
var rCubeY = 0;
var SpeedY = 0;
var z = -5.0;
var filter = 0;
function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);
mat4.identity(mvMatrix);
mat4.translate(mvMatrix, [0.0, 0.0, z]);
mvPushMatrix();
mat4.rotate(mvMatrix, degToRad(rCubeX), [1, 0, 0]);
mat4.rotate(mvMatrix, degToRad(rCubeY), [0, 1, 0]);
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, cubeVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexNormalBuffer);
gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, cubeVertexNormalBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, cubeVertexTextureCoordBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, cubeTextures[filter]);
gl.uniform1i(shaderProgram.samplerUniform, 0);
var lighting = document.getElementById("lighting").checked;
gl.uniform1i(shaderProgram.useLightingUniform, lighting);
if(lighting)
{
gl.uniform3f(
shaderProgram.ambientColorUniform,
parseFloat(document.getElementById("ambientR").value),
parseFloat(document.getElementById("ambientG").value),
parseFloat(document.getElementById("ambientB").value)
);
}
var lightingDirection = [
parseFloat(document.getElementById("lightDirectionX").value),
parseFloat(document.getElementById("lightDirectionY").value),
parseFloat(document.getElementById("lightDirectionZ").value)
];
var adjustedLD = vec3.create();
vec3.normalize(lightingDirection, adjustedLD);
vec3.scale(adjustedLD, -1);
gl.uniform3fv(shaderProgram.lightingDirectionUniform, adjustedLD);
gl.uniform3f(
shaderProgram.directionalColorUniform,
parseFloat(document.getElementById("directionalR").value),
parseFloat(document.getElementById("directionalG").value),
parseFloat(document.getElementById("directionalB").value)
);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
setMatrixUniforms();
gl.drawElements(gl.TRIANGLES, cubeVertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);
mvPopMatrix();
}
var lastTime = 0;
function animate()
{
var timeNow = new Date().getTime();
if(lastTime != 0)
{
var elapsed = timeNow - lastTime;
rCubeX += (SpeedX * elapsed) / 1000.0;
rCubeY += (SpeedY * elapsed) / 1000.0;
}
lastTime = timeNow;
}
var currentlyPressedKeys = {};
function handleKeyDown(event){
currentlyPressedKeys[event.keyCode] = true;
if(String.fromCharCode(event.keyCode) == "F"){
filter += 1;
if(filter == 3){
filter = 0;
}
}
}
function handleKeyUp(event){
currentlyPressedKeys[event.keyCode] = false;
}
function handleKeys()
{
if(currentlyPressedKeys[33])
{
z -= 0.05;
}
if(currentlyPressedKeys[34])
{
z += 0.05;
}
if(currentlyPressedKeys[37])
{
SpeedY --;
} else if (SpeedY < 0){
SpeedY ++;
}
if(currentlyPressedKeys[39])
{
SpeedY ++;
}else if(SpeedY > 0){
SpeedY --;
}
if (currentlyPressedKeys[38]) {
SpeedX --;
} else if(SpeedX < 0){
SpeedX ++;
}
if (currentlyPressedKeys[40]) {
SpeedX ++;
} else if(SpeedX > 0){
SpeedX--;
}
}
function update()
{
requestAnimFrame(update);
handleKeys();
drawScene();
animate();
}
function webGLStart() {
var canvas = document.getElementById("canvas1");
initGL(canvas);
initShaders();
initBuffers();
initTexture();
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;
update();
}
</code></pre>
| 0 | 8,402 |
MVC 4 - Use a different model in partial view
|
<p>Please bear with my <em>noobness</em>, I'm super new to the MVC pattern.</p>
<p><strong>What I'm trying to do</strong></p>
<p>I am building a profile information page for registered users on my site. This page would list data about the user, such as date of birth, telephone number, subscription status, etc.. You get the idea. I would also like to have a form to let users change their password, email address, personal information <strong>on the same page</strong>.</p>
<p><strong>My problem</strong></p>
<p>The user's data comes from my controller via a passed model variable:</p>
<pre><code>public ActionResult Profil()
{
var model = db.Users.First(e => e.UserName == WebSecurity.CurrentUserName);
return View(model);
}
</code></pre>
<p>The output looks like this in my view:</p>
<pre><code><label>Phone number: </label>
@if (Model.PhoneNumber != null)
{
@Model.PhoneNumber
}
else
{
<span class="red">You haven't set up your phone number yet. </span>
}
</code></pre>
<p>The form in which the user could change his info would use another model, ProfileModel. So basiccaly I need to use two models in my view, one for outputting information and one for posting data. I thought that using a partial view I can achieve this, but I get this error:</p>
<blockquote>
<p>The model item passed into the dictionary is of type
'Applicense.Models.User', but this dictionary requires a model item of
type 'Applicense.Models.ProfileModel'.</p>
</blockquote>
<p>Here's what my call to the partial view looks like:</p>
<pre><code> @using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
@Html.Partial("_ModifyProfileInfo")
}
</code></pre>
<p>Here's the partial view:</p>
<pre><code>@model Applicense.Models.ProfileModel
<ul>
<li>
@Html.LabelFor(m => m.Email)
@Html.EditorFor(m => m.Email)
</li>
<li>
@Html.LabelFor(m => m.ConfirmEmail)
@Html.EditorFor(m => m.ConfirmEmail)
</li>
<input type="submit" value="Update e-mail" />
</ul>
</code></pre>
<p>And finally here's my ProfileModel:</p>
<pre><code>public class ProfileModel
{
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "New e-mail address")]
public string Email { get; set; }
[DataType(DataType.EmailAddress)]
[Display(Name = "Confirm new e-mail address")]
[Compare("Email", ErrorMessage = "The e-mail and it's confirmation field do not match.")]
public string ConfirmEmail { get; set; }
}
</code></pre>
<p>Am I missing something? What's the proper way to do this?</p>
<p><strong>Edit:</strong>
I remade my code reflecting Nikola Mitev's answer, but now I have another problem. Here's the error I get:</p>
<blockquote>
<p>Object reference not set to an instance of an object. (@Model.UserObject.LastName)</p>
</blockquote>
<p>This only occurs when I'm posting the changed e-mail address values. Here's my ViewModel (ProfileModel.cs):</p>
<pre><code>public class ProfileModel
{
public User UserObject { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Új e-mail cím")]
public string Email { get; set; }
[DataType(DataType.EmailAddress)]
[Display(Name = "Új e-mail cím megerősítése")]
[Compare("Email", ErrorMessage = "A két e-mail cím nem egyezik.")]
public string ConfirmEmail { get; set; }
[DataType(DataType.EmailAddress)]
[Display(Name= "E-mail cím")]
public string ReferEmail { get; set; }
}
</code></pre>
<p>Controller:</p>
<pre><code>public ActionResult Profil()
{
var User = db.Users.First(e => e.UserName == WebSecurity.CurrentUserName);
var ProfileViewModel = new ProfileModel
{
UserObject = User
};
return View(ProfileViewModel);
}
</code></pre>
<p>And finally here's my <code>user.cs</code> model class:</p>
<pre><code>[Table("UserProfile")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Column("UserName")]
public string UserName { get; set; }
[Column("Email")]
[Required]
public string Email { get; set; }
[Column("FirstName")]
public string FirstName { get; set; }
[Column("LastName")]
public string LastName { get; set; }
[Column("PhoneNumber")]
public string PhoneNumber { get; set; }
... You get the idea of the rest...
</code></pre>
<p>I'm thinking it's happening because the model is trying to put data in each <code>required</code> columns into the database.</p>
<p><strong>Edit2:</strong>
The httppost method of my Profil action:</p>
<pre><code>[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult Profil(ProfileModel model)
{
if (ModelState.IsValid)
{
//insert into database
return Content("everything's good");
}
else
{
//outputs form errors
return View(model);
}
}
</code></pre>
| 0 | 2,341 |
Jest: Cannot spy the property because it is not a function; undefined given instead getting error while executing my test cases
|
<pre><code> This is my controller class(usercontoller.ts) i am trying to write junit test cases for this class
import { UpsertUserDto } from '../shared/interfaces/dto/upsert-user.dto';
import { UserDto } from '../shared/interfaces/dto/user.dto';
import { UserService } from './user.service';
async updateUser(@BodyToClass() user: UpsertUserDto): Promise<UpsertUserDto> {
try {
if (!user.id) {
throw new BadRequestException('User Id is Required');
}
return await this.userService.updateUser(user);
} catch (e) {
throw e;
}
}
</code></pre>
<p>This is my TestClass(UserContollerspec.ts)
while running my test classes getting error " Cannot spy the updateUser property because it is not a function; undefined given instead.
getting error.
However, when I use spyOn method, I keep getting TypeError: Cannot read property 'updateuser' of undefined: </p>
<p>*it seems jest.spyOn() not working properly where i am doing mistake.
could some one please help me.the argument which I am passing ? </p>
<pre><code> jest.mock('./user.service');
describe('User Controller', () => {
let usercontroller: UserController;
let userservice: UserService;
// let fireBaseAuthService: FireBaseAuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [UserService]
}).compile();
usercontroller = module.get<UserController>(UserController);
userservice = module.get<UserService>(UserService);
});
afterEach(() => {
jest.resetAllMocks();
});
describe('update user', () => {
it('should return a user', async () => {
//const result = new UpsertUserDto();
const testuser = new UpsertUserDto();
const mockDevice = mock <Promise<UpsertUserDto>>();
const mockNumberToSatisfyParameters = 0;
//const userservice =new UserService();
//let userservice: UserService;
jest.spyOn(userservice, 'updateUser').mockImplementation(() => mockDevice);
expect(await usercontroller.updateUser(testuser)).toBe(mockDevice);
it('should throw internal error if user not found', async (done) => {
const expectedResult = undefined;
****jest.spyOn(userservice, 'updateUser').mockResolvedValue(expectedResult);****
await usercontroller.updateUser(testuser)
.then(() => done.fail('Client controller should return NotFoundException error of 404 but did not'))
.catch((error) => {
expect(error.status).toBe(503);
expect(error.message).toMatchObject({error: 'Not Found', statusCode: 503}); done();
});
});
});
});
</code></pre>
| 0 | 1,542 |
Swift gyroscope yaw, pitch, roll
|
<p>I'm doing a project for my school, for a programming subject. I'm working in Xcode in Swift. I would like to make an application that uses Gyroscope. I don't know but somehow it won't run on my iphone because of some errors in Xcode that I don't know how to fix.When I run the program is says "fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)"
The main thing of my project is to display rotations (yaw,pitch,roll) in degrees on iphone screen using gyroscope. I would be really grateful if someone help me with this. Thank you in advance. </p>
<p>The code in my ViewController:</p>
<pre><code>import UIKit
import CoreMotion
class ViewController: UIViewController {
var currentMaxRotX: Double = 0.0
var currentMaxRotY: Double = 0.0
var currentMaxRotZ: Double = 0.0
let motionManager = CMMotionManager()
@IBOutlet var rotX : UILabel! = nil
@IBOutlet var rotY : UILabel! = nil
@IBOutlet var rotZ : UILabel! = nil
@IBOutlet var maxRotX : UILabel! = nil
@IBOutlet var maxRotY : UILabel! = nil
@IBOutlet var maxRotZ : UILabel! = nil
@IBOutlet weak var RollLabel: UILabel! = nil
@IBOutlet weak var PitchLabel: UILabel! = nil
@IBOutlet weak var YawLabel: UILabel! = nil
override func viewDidLoad() {
if motionManager.gyroAvailable {
if !motionManager.gyroActive {
motionManager.gyroUpdateInterval = 0.2
motionManager.startGyroUpdates()
//motionManager = [[CMMotionManager alloc]init]; should I use this ???
//motionManager.deviceMotionUpdateInterval = 0.2;
//motionManager.startDeviceMotionUpdates()
motionManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {(gyroData: CMGyroData!, error: NSError!)in
self.outputRotationData(gyroData.rotationRate)
if (error != nil)
{
println("\(error)")
}
})
}
} else {
var alert = UIAlertController(title: "No gyro", message: "Get a Gyro", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
super.viewDidLoad()
}
// radians to degrees
func radians(fromDegrees degrees: Double) -> Double {
return 180 * degrees / M_PI
}
func outputRotationData(rotation:CMRotationRate)
{
rotX.text = NSString(format:"Rotation X: %.4f",rotation.x)
if fabs(rotation.x) > fabs(currentMaxRotX)
{
currentMaxRotX = rotation.x
}
rotY.text = NSString(format:"Rotation Y: %.4f", rotation.y)
if fabs(rotation.y) > fabs(currentMaxRotY)
{
currentMaxRotY = rotation.y
}
rotZ.text = NSString(format:"Rotation Z:%.4f", rotation.z)
if fabs(rotation.z) > fabs(currentMaxRotZ)
{
currentMaxRotZ = rotation.z
}
maxRotX.text = NSString(format:"Max rotation X: %.4f", currentMaxRotX)
maxRotY.text = NSString(format:"Max rotation Y:%.4f", currentMaxRotY)
maxRotZ.text = NSString(format:"Max rotation Z:%.4f", currentMaxRotZ)
var attitude = CMAttitude()
var motion = CMDeviceMotion()
motion = motionManager.deviceMotion
attitude = motion.attitude
YawLabel.text = NSString (format: "Yaw: %.2f", attitude.yaw) //radians to degress NOT WORKING
PitchLabel.text = NSString (format: "Pitch: %.2f", attitude.pitch)//radians to degress NOT WORKING
RollLabel.text = NSString (format: "Roll: %.2f", attitude.roll)//radians to degress NOT WORKING
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
</code></pre>
| 0 | 1,722 |
Parsing a CSV file for a unique row using the new Java 8 Streams API
|
<p>I am trying to use the new Java 8 Streams API (for which I am a complete newbie) to parse for a particular row (the one with 'Neda' in the name column) in a CSV file. Using the following <a href="http://blog.codeleak.pl/2014/05/parsing-file-with-stream-api-in-java-8.html" rel="noreferrer">article</a> for motivation, I modified and fixed some errors so that I could parse the file containing 3 columns - 'name', 'age' and 'height'.</p>
<pre><code>name,age,height
Marianne,12,61
Julie,13,73
Neda,14,66
Julia,15,62
Maryam,18,70
</code></pre>
<p>The parsing code is as follows:</p>
<pre><code>@Override
public void init() throws Exception {
Map<String, String> params = getParameters().getNamed();
if (params.containsKey("csvfile")) {
Path path = Paths.get(params.get("csvfile"));
if (Files.exists(path)){
// use the new java 8 streams api to read the CSV column headings
Stream<String> lines = Files.lines(path);
List<String> columns = lines
.findFirst()
.map((line) -> Arrays.asList(line.split(",")))
.get();
columns.forEach((l)->System.out.println(l));
// find the relevant sections from the CSV file
// we are only interested in the row with Neda's name
int nameIndex = columns.indexOf("name");
int ageIndex columns.indexOf("age");
int heightIndex = columns.indexOf("height");
// we need to know the index positions of the
// have to re-read the csv file to extract the values
lines = Files.lines(path);
List<List<String>> values = lines
.skip(1)
.map((line) -> Arrays.asList(line.split(",")))
.collect(Collectors.toList());
values.forEach((l)->System.out.println(l));
}
}
}
</code></pre>
<p>Is there any way to avoid re-reading the file following the extraction of the header line? Although this is a very small example file, I will be applying this logic to a large CSV file. </p>
<p>Is there technique to use the streams API to create a map between the extracted column names (in the first scan of the file) to the values in the remaining rows?</p>
<p>How can I return just one row in the form of <code>List<String></code> (instead of <code>List<List<String>></code> containing all the rows). I would prefer to just find the row as a mapping between the column names and their corresponding values. (a bit like a result set in JDBC). I see a Collectors.mapMerger function that might be helpful here, but I have no idea how to use it.</p>
| 0 | 1,078 |
Powershell - convert log file to CSV
|
<p>I have log files that look like this...</p>
<pre><code>2009-12-18T08:25:22.983Z 1 174 dns:0-apr-credit-cards-uk.pedez.co.uk P http://0-apr-credit-cards-uk.pedez.co.uk/ text/dns #170 20091218082522021+89 sha1:AIDBQOKOYI7OPLVSWEBTIAFVV7SRMLMF - -
2009-12-18T08:25:22.984Z 1 5 dns:0-60racing.co.uk P http://0-60racing.co.uk/ text/dns #116 20091218082522037+52 sha1:WMII7OOKYQ42G6XPITMHJSMLQFLGCGMG - -
2009-12-18T08:25:23.066Z 1 79 dns:0-addiction.metapress.com.wam.leeds.ac.uk P http://0-addiction.metapress.com.wam.leeds.ac.uk/ text/dns #042 20091218082522076+20 sha1:NSUQN6TBIECAP5VG6TZJ5AVY34ANIC7R - -
...plus millions of other records
</code></pre>
<p>I need to convert these into csv files...</p>
<pre><code>"2009-12-18T08:25:22.983Z","1","174","dns:0-apr-credit-cards-uk.pedez.co.uk","P","http://0-apr-credit-cards-uk.pedez.co.uk/","text/dns","#170","20091218082522021+89","sha1:AIDBQOKOYI7OPLVSWEBTIAFVV7SRMLMF","-","-"
"2009-12-18T08:25:22.984Z","1","5","dns:0-60racing.co.uk","P","http://0-60racing.co.uk/","text/dns","#116","20091218082522037+52","sha1:WMII7OOKYQ42G6XPITMHJSMLQFLGCGMG","-","-"
"2009-12-18T08:25:23.066Z","1","79","dns:0-addiction.metapress.com.wam.leeds.ac.uk","P","http://0-addiction.metapress.com.wam.leeds.ac.uk/","text/dns","#042","20091218082522076+20","sha1:NSUQN6TBIECAP5VG6TZJ5AVY34ANIC7R","-","-"
</code></pre>
<p>The field delimiter can be either a single or multiple space characters, with both fixed width and variable width fields. This tends to confuse most CSV parsers that I find.</p>
<p>Ultimately I want to bcp these files into SQL Server but you can only specify a single character as a field delimiter (i.e. ' ') and this breaks the fixed length fields.</p>
<p>So far - I'm using PowerShell</p>
<pre><code>gc -ReadCount 10 -TotalCount 200 .\crawl_sample.log | foreach { ([regex]'([\S]*)\s+').matches($_) } | foreach {$_.Groups[1].Value}
</code></pre>
<p>and this returns a stream of the fields:</p>
<pre><code>2009-12-18T08:25:22.983Z
1
74
dns:0-apr-credit-cards-uk.pedez.co.uk
P
http://0-apr-credit-cards-uk.pedez.co.uk/
text/dns
#170
20091218082522021+89
sha1:AIDBQOKOYI7OPLVSWEBTIAFVV7SRMLMF
-
-
2009-12-18T08:25:22.984Z
1
55
dns:0-60racing.co.uk
P
http://0-60racing.co.uk/
text/dns
#116
20091218082522037+52
sha1:WMII7OOKYQ42G6XPITMHJSMLQFLGCGMG
-
</code></pre>
<p>but how do I convert that output into the CSV format? </p>
| 0 | 1,154 |
How to Make a Basic Finite State Machine in Objective-C
|
<p>I am attempting to build an FSM to control a timer in (iphone sdk) objective c. I felt it was a necessary step, because I was otherwise ending up with nasty spaghetti code containing pages of if-then statements. The complexity, non-readability, and difficulty of adding/changing features lead me to attempt a more formal solution like this. </p>
<p>In the context of the application, the state of the timer determines some complex interactions with NSManagedObjects, Core Data, and so forth. I have left all that functionality out for now, in an attempt to get a clear view of the FSM code. </p>
<p>The trouble is, I cannot find any examples of this sort of code in Obj-C, and I am not so confident about how I have translated it from the C++ example code I was using. (I don't know C++ at all, so there is some guessing involved.) I am basing this version of a state pattern design on this article: <a href="http://www.ai-junkie.com/architecture/state_driven/tut_state1.html" rel="nofollow noreferrer">http://www.ai-junkie.com/architecture/state_driven/tut_state1.html</a>. I'm not making a game, but this article outlines concepts that work for what I'm doing. </p>
<p>In order to create the code (posted below), I had to learn a lot of new concepts, including obj-c protocols, and so forth. Because these are new to me, as is the state design pattern, I'm hoping for some feedback about this implementation. Is this how you work with protocol objects effectively in obj-c? </p>
<p>Here is the protocol:</p>
<pre><code>@class Timer;
@protocol TimerState
-(void) enterTimerState:(Timer*)timer;
-(void) executeTimerState:(Timer*)timer;
-(void) exitTimerState:(Timer*)timer;
@end
</code></pre>
<p>Here is the Timer object (in its most stripped down form) header file:</p>
<pre><code>@interface Timer : NSObject
{
id<TimerState> currentTimerState;
NSTimer *secondTimer;
id <TimerViewDelegate> viewDelegate;
id<TimerState> setupState;
id<TimerState> runState;
id<TimerState> pauseState;
id<TimerState> resumeState;
id<TimerState> finishState;
}
@property (nonatomic, retain) id<TimerState> currentTimerState;
@property (nonatomic, retain) NSTimer *secondTimer;
@property (assign) id <TimerViewDelegate> viewDelegate;
@property (nonatomic, retain) id<TimerState> setupState;
@property (nonatomic, retain) id<TimerState> runState;
@property (nonatomic, retain) id<TimerState> pauseState;
@property (nonatomic, retain) id<TimerState> resumeState;
@property (nonatomic, retain) id<TimerState> finishState;
-(void)stopTimer;
-(void)changeState:(id<TimerState>) timerState;
-(void)executeState:(id<TimerState>) timerState;
-(void) setupTimer:(id<TimerState>) timerState;
</code></pre>
<p>And the Timer Object implementation:</p>
<pre><code>#import "Timer.h"
#import "TimerState.h"
#import "Setup_TS.h"
#import "Run_TS.h"
#import "Pause_TS.h"
#import "Resume_TS.h"
#import "Finish_TS.h"
@implementation Timer
@synthesize currentTimerState;
@synthesize viewDelegate;
@synthesize secondTimer;
@synthesize setupState, runState, pauseState, resumeState, finishState;
-(id)init
{
if (self = [super init])
{
id<TimerState> s = [[Setup_TS alloc] init];
self.setupState = s;
//[s release];
id<TimerState> r = [[Run_TS alloc] init];
self.runState = r;
//[r release];
id<TimerState> p = [[Pause_TS alloc] init];
self.pauseState = p;
//[p release];
id<TimerState> rs = [[Resume_TS alloc] init];
self.resumeState = rs;
//[rs release];
id<TimerState> f = [[Finish_TS alloc] init];
self.finishState = f;
//[f release];
}
return self;
}
-(void)changeState:(id<TimerState>) newState{
if (newState != nil)
{
[self.currentTimerState exitTimerState:self];
self.currentTimerState = newState;
[self.currentTimerState enterTimerState:self];
[self executeState:self.currentTimerState];
}
}
-(void)executeState:(id<TimerState>) timerState
{
[self.currentTimerState executeTimerState:self];
}
-(void) setupTimer:(id<TimerState>) timerState
{
if ([timerState isKindOfClass:[Run_TS class]])
{
secondTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(currentTime) userInfo:nil repeats:YES];
}
else if ([timerState isKindOfClass:[Resume_TS class]])
{
secondTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(currentTime) userInfo:nil repeats:YES];
}
}
-(void) stopTimer
{
[secondTimer invalidate];
}
-(void)currentTime
{
//This is just to see it working. Not formatted properly or anything.
NSString *text = [NSString stringWithFormat:@"%@", [NSDate date]];
if (self.viewDelegate != NULL && [self.viewDelegate respondsToSelector:@selector(updateLabel:)])
{
[self.viewDelegate updateLabel:text];
}
}
//TODO: releases here
- (void)dealloc
{
[super dealloc];
}
@end
</code></pre>
<p>Don't worry that there are missing things in this class. It doesn't do anything interesting yet. I'm currently just struggling with getting the syntax correct. Currently it compiles (and works) but the isKindOfClass method calls cause compiler warnings (method is not found in protocol). I'm not really sure that I want to use isKindOfClass anyway. I was thinking of giving each <code>id<TimerState></code> object a name string and using that instead. </p>
<p>On another note: all those <code>id<TimerState></code> declarations were originally TimerState * declarations. It seemed to make sense to retain them as properties. Not sure if it makes sense with <code>id<TimerState></code>'s. </p>
<p>Here is an example of one of the state classes: </p>
<pre><code>#import "TimerState.h"
@interface Setup_TS : NSObject <TimerState>{
}
@end
#import "Setup_TS.h"
#import "Timer.h"
@implementation Setup_TS
-(void) enterTimerState:(Timer*)timer{
NSLog(@"SETUP: entering state");
}
-(void) executeTimerState:(Timer*)timer{
NSLog(@"SETUP: executing state");
}
-(void) exitTimerState:(Timer*)timer{
NSLog(@"SETUP: exiting state");
}
@end
</code></pre>
<p>Again, so far it doesn't do anything except announce that what phase (or sub-state) it's in. But that's not the point. </p>
<p>What I'm hoping to learn here is whether this architecture is composed correctly in the obj-c language. One specific problem I'm encountering is the creation of the id objects in the timer's init function. As you can see, I commented out the releases, because they were causing a "release not found in protocol" warning. I wasn't sure how to handle that. </p>
<p>What I don't need is comments about this code being overkill or meaningless formalism, or whatever. It's worth me learning this even it those ideas are true. If it helps, think of it as a theoretical design for an FSM in obj-c. </p>
<p>Thank you in advance for any helpful comments. </p>
<p>(this didn't help too much: <a href="https://stackoverflow.com/questions/1110572/finite-state-machine-in-objective-c">Finite State Machine in Objective-C</a>)</p>
| 0 | 2,527 |
An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
|
<p>I'm working on a small application in C# / WPF that is fed by data from the serial port. It also reads a text file containing some constants in order to calculate something. An event handler is made to handle the incoming data when it arrives:</p>
<pre><code>_serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Receive);
</code></pre>
<p>Here is the Receive handler, along with a delegate that is created in a Dispatcher, to further update the UI.</p>
<pre><code>private delegate void UpdateUiTextDelegate(string text);
private void Receive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// collect characters received to our 'buffer' (string)
try
{
// stops long running output timer if enabled
if (dispatcherTimer.IsEnabled)
{
dispatcherTimer.Stop();
}
message = _serialPort.ReadLine();
dispatcherTimer.Start();
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(updateUI), message);
}
catch (Exception ex)
{
// timeout
dispatcherTimer.Start();
SerialCmdSend("SCAN");
}
}
</code></pre>
<p>The <code>dispatcherTimer</code> allows resending commands to the unit on the serial line, if it fails to get any data in a reasonable amount of time. </p>
<p>In addition to also reading from a text file, the application has some keyboard shortcut gestures defined in the constructor of the main window:</p>
<pre><code>public MainWindow()
{
InitializeComponent();
InitializeComponent();
KeyGesture kg = new KeyGesture(Key.C, ModifierKeys.Control);
InputBinding ib = new InputBinding(MyCommand, kg);
this.InputBindings.Add(ib);
Start();
}
</code></pre>
<p>So the MainWindow.xaml has this command binding code:</p>
<pre><code><Window.CommandBindings>
<CommandBinding Command="{x:Static custom:MainWindow.MyCommand}"
Executed="MyCommandExecuted"
CanExecute="CanExecuteMyCommand" />
</Window.CommandBindings>
</code></pre>
<p>Visual Studio Designer complains about invalid markup, but still used to run fine, until I started getting these errors when running the program:</p>
<blockquote>
<p>An unhandled exception of type
'System.Windows.Markup.XamlParseException' occurred in
PresentationFramework.dll</p>
<p>Additional information: 'The invocation of the constructor on type
'Vaernes.MainWindow' that matches the specified binding constraints
threw an exception.' Line number '4' and line position '9'.</p>
</blockquote>
<p>This kind of error appears after making small code changes. The latest was replacing the text file read by the program, with another one with the same name (Add Existing item...). I have searched around some on the web for solutions but I can't find any that is quite similar to my problem.</p>
<p>I suspect it has something to do with either the Dispatcher thread or the Input Bindings.
I also tried to add a handler for the exception and noticed that the sender was System.Windows.Threading.Dispatcher.</p>
<p>Suggestions anyone?</p>
| 0 | 1,064 |
Horizontal pod autoscaling not working: `unable to get metrics for resource cpu: no metrics returned from heapster`
|
<p>I'm trying to create an horizontal pod autoscaling after installing Kubernetes with kubeadm.</p>
<p>The main symptom is that <code>kubectl get hpa</code> returns the CPU metric in the column <code>TARGETS</code> as "undefined":</p>
<pre><code>$ kubectl get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
fibonacci Deployment/fibonacci <unknown> / 50% 1 3 1 1h
</code></pre>
<p>On further investigation, it appears that <code>hpa</code> is trying to receive the CPU metric from Heapster - but on my configuration the cpu metric is being provided by cAdvisor.</p>
<p>I am making this assumption based on the output of <code>kubectl describe hpa fibonacci</code>:</p>
<pre><code>Name: fibonacci
Namespace: default
Labels: <none>
Annotations: <none>
CreationTimestamp: Sun, 14 May 2017 18:08:53 +0000
Reference: Deployment/fibonacci
Metrics: ( current / target )
resource cpu on pods (as a percentage of request): <unknown> / 50%
Min replicas: 1
Max replicas: 3
Events:
FirstSeen LastSeen Count From SubObjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
1h 3s 148 horizontal-pod-autoscaler Warning FailedGetResourceMetric unable to get metrics for resource cpu: no metrics returned from heapster
1h 3s 148 horizontal-pod-autoscaler Warning FailedComputeMetricsReplicas failed to get cpu utilization: unable to get metrics for resource cpu: no metrics returned from heapster
</code></pre>
<p>Why does <code>hpa</code> try to receive this metric from heapster instead of cAdvisor? </p>
<p>How can I fix this?</p>
<p>Please find below my deployment, along with the contents of <code>/var/log/container/kube-controller-manager.log</code> and the output of <code>kubectl get pods --namespace=kube-system</code> and <code>kubectl describe pods</code></p>
<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: fibonacci
labels:
app: fibonacci
spec:
template:
metadata:
labels:
app: fibonacci
spec:
containers:
- name: fibonacci
image: oghma/fibonacci
ports:
- containerPort: 8088
resources:
requests:
memory: "64Mi"
cpu: "75m"
limits:
memory: "128Mi"
cpu: "100m"
---
kind: Service
apiVersion: v1
metadata:
name: fibonacci
spec:
selector:
app: fibonacci
ports:
- protocol: TCP
port: 8088
targetPort: 8088
externalIPs:
- 192.168.66.103
---
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: fibonacci
spec:
scaleTargetRef:
apiVersion: apps/v1beta1
kind: Deployment
name: fibonacci
minReplicas: 1
maxReplicas: 3
targetCPUUtilizationPercentage: 50
</code></pre>
<hr>
<pre><code>$ kubectl describe pods
Name: fibonacci-1503002127-3k755
Namespace: default
Node: kubernetesnode1/192.168.66.101
Start Time: Sun, 14 May 2017 17:47:08 +0000
Labels: app=fibonacci
pod-template-hash=1503002127
Annotations: kubernetes.io/created-by={"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"ReplicaSet","namespace":"default","name":"fibonacci-1503002127","uid":"59ea64bb-38cd-11e7-b345-fa163edb1ca...
Status: Running
IP: 192.168.202.1
Controllers: ReplicaSet/fibonacci-1503002127
Containers:
fibonacci:
Container ID: docker://315375c6a978fd689f4ba61919c15f15035deb9139982844cefcd46092fbec14
Image: oghma/fibonacci
Image ID: docker://sha256:26f9b6b2c0073c766b472ec476fbcd2599969b6e5e7f564c3c0a03f8355ba9f6
Port: 8088/TCP
State: Running
Started: Sun, 14 May 2017 17:47:16 +0000
Ready: True
Restart Count: 0
Limits:
cpu: 100m
memory: 128Mi
Requests:
cpu: 75m
memory: 64Mi
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-45kp8 (ro)
Conditions:
Type Status
Initialized True
Ready True
PodScheduled True
Volumes:
default-token-45kp8:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-45kp8
Optional: false
QoS Class: Burstable
Node-Selectors: <none>
Tolerations: node.alpha.kubernetes.io/notReady=:Exists:NoExecute for 300s
node.alpha.kubernetes.io/unreachable=:Exists:NoExecute for 300s
Events: <none>
</code></pre>
<hr>
<pre><code>$ kubectl get pods --namespace=kube-system
NAME READY STATUS RESTARTS AGE
calico-etcd-k1g53 1/1 Running 0 2h
calico-node-6n4gp 2/2 Running 1 2h
calico-node-nhmz7 2/2 Running 0 2h
calico-policy-controller-1324707180-65m78 1/1 Running 0 2h
etcd-kubernetesmaster 1/1 Running 0 2h
heapster-1428305041-zjzd1 1/1 Running 0 1h
kube-apiserver-kubernetesmaster 1/1 Running 0 2h
kube-controller-manager-kubernetesmaster 1/1 Running 0 2h
kube-dns-3913472980-gbg5h 3/3 Running 0 2h
kube-proxy-1dt3c 1/1 Running 0 2h
kube-proxy-tfhr9 1/1 Running 0 2h
kube-scheduler-kubernetesmaster 1/1 Running 0 2h
monitoring-grafana-3975459543-9q189 1/1 Running 0 1h
monitoring-influxdb-3480804314-7bvr3 1/1 Running 0 1h
</code></pre>
<hr>
<pre><code>$ cat /var/log/container/kube-controller-manager.log
"log":"I0514 17:47:08.631314 1 event.go:217] Event(v1.ObjectReference{Kind:\"Deployment\", Namespace:\"default\", Name:\"fibonacci\", UID:\"59e980d9-38cd-11e7-b345-fa163edb1ca6\", APIVersion:\"extensions\", ResourceVersion:\"1303\", FieldPath:\"\"}): type: 'Normal' reason: 'ScalingReplicaSet' Scaled up replica set fibonacci-1503002127 to 1\n","stream":"stderr","time":"2017-05-14T17:47:08.63177467Z"}
{"log":"I0514 17:47:08.650662 1 event.go:217] Event(v1.ObjectReference{Kind:\"ReplicaSet\", Namespace:\"default\", Name:\"fibonacci-1503002127\", UID:\"59ea64bb-38cd-11e7-b345-fa163edb1ca6\", APIVersion:\"extensions\", ResourceVersion:\"1304\", FieldPath:\"\"}): type: 'Normal' reason: 'SuccessfulCreate' Created pod: fibonacci-1503002127-3k755\n","stream":"stderr","time":"2017-05-14T17:47:08.650826398Z"}
{"log":"E0514 17:49:00.873703 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:49:00.874034952Z"}
{"log":"E0514 17:49:30.884078 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:49:30.884546461Z"}
{"log":"E0514 17:50:00.896563 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:50:00.89688734Z"}
{"log":"E0514 17:50:30.906293 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:50:30.906825794Z"}
{"log":"E0514 17:51:00.915996 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:51:00.916348218Z"}
{"log":"E0514 17:51:30.926043 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:51:30.926367623Z"}
{"log":"E0514 17:52:00.936574 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:52:00.936903072Z"}
{"log":"E0514 17:52:30.944724 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:52:30.945120508Z"}
{"log":"E0514 17:53:00.954785 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:53:00.955126309Z"}
{"log":"E0514 17:53:30.970454 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:53:30.972996568Z"}
{"log":"E0514 17:54:00.980735 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:54:00.981098832Z"}
{"log":"E0514 17:54:30.993176 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:54:30.993538841Z"}
{"log":"E0514 17:55:01.002941 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:55:01.003265908Z"}
{"log":"W0514 17:55:06.511756 1 reflector.go:323] k8s.io/kubernetes/pkg/controller/garbagecollector/graph_builder.go:192: watch of \u003cnil\u003e ended with: etcdserver: mvcc: required revision has been compacted\n","stream":"stderr","time":"2017-05-14T17:55:06.511957851Z"}
{"log":"E0514 17:55:31.013415 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:55:31.013776243Z"}
{"log":"E0514 17:56:01.024507 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:56:01.0248332Z"}
{"log":"E0514 17:56:31.036191 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:56:31.036606698Z"}
{"log":"E0514 17:57:01.049277 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:57:01.049616359Z"}
{"log":"E0514 17:57:31.064104 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:57:31.064489485Z"}
{"log":"E0514 17:58:01.073988 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:58:01.074339488Z"}
{"log":"E0514 17:58:31.084511 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:58:31.084839352Z"}
{"log":"E0514 17:59:01.096507 1 horizontal.go:201] failed to compute desired number of replicas based on listed metrics for Deployment/default/fibonacci: failed to get cpu utilization: unable to get metrics for resource cpu: failed to get pod resource metrics: the server could not find the requested resource (get services http:heapster:)\n","stream":"stderr","time":"2017-05-14T17:59:01.096896254Z"}
</code></pre>
| 0 | 6,053 |
iOS crash libobjc.A.dylib objc_msgSend
|
<p>I am getting the crash shown below in Crashlytics.</p>
<p>I am unable to understand where this is coming form within the app. Unfortunately I have never been able to generate this crash myself, but it is occurring in the wild.</p>
<p>There is only one reference to the app name, and there is nothing that leads to show where in the app this is coming from.</p>
<p>Is the fact that there is no data as to where in the app this occurs, an indication of an issue occurring during didFinishLaunchingWithOptionsand thus not actually getting far enough to show any further detail? Or is there some other reason that the log is lacking in data to show where the issue is?</p>
<p>Could anyone advise how I may be able to track this down?</p>
<pre><code> Thread : Crashed: com.apple.main-thread
0 libobjc.A.dylib 0x0000000195de3bd0 objc_msgSend + 16
1 CoreFoundation 0x0000000183fd9458 CFRelease + 524
2 CoreFoundation 0x0000000183fe5a18 -[__NSArrayM dealloc] + 152
3 libobjc.A.dylib 0x0000000195de9724 (anonymous namespace)::AutoreleasePoolPage::pop(void*) + 564
4 CoreFoundation 0x0000000183fdd074 _CFAutoreleasePoolPop + 28
5 Foundation 0x0000000184f0e588 -[NSAutoreleasePool release] + 148
6 UIKit 0x0000000188be03f4 -[UIApplication _run] + 588
7 UIKit 0x0000000188bdaf40 UIApplicationMain + 1488
8 _THE_APP_NAME_ 0x0000000100031e20 main (main.m:16)
9 libdyld.dylib 0x000000019647aa08 start + 4
Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x00000000f5b2beb8
</code></pre>
<hr>
<p>I am adding the following in relation the comments placed on this thread. This code was the main UI related change, other than usual label setting etc, which I can't see an issue with. </p>
<p>The code below was added to the AppDelegate.m, DidFinishLaunchingWithOptions.</p>
<p>I am wondering, as the crash is not something I have been able to re-produce, and whilst happening daily is only in a handful of cases, if it could be a timing issue, and the UI not being available to receive the messages.</p>
<p>I welcome any thoughts, and if you agree, if I should instead move the code to the ViewDidLoad in the ViewController instead.</p>
<pre><code>[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor lightGrayColor], NSForegroundColorAttributeName,
[UIFont fontWithName:@"Helvetica Neue" size:16],
NSFontAttributeName, nil] forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor darkGrayColor], NSForegroundColorAttributeName,
[UIFont fontWithName:@"Helvetica Neue" size:16],
NSFontAttributeName,
nil] forState:UIControlStateSelected];
[[UITabBar appearance] setBarTintColor:[UIColor colorWithRed:0.44 green:0.99 blue:0.45 alpha:1]];
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:0.44 green:0.99 blue:0.45 alpha:1]];
[[UINavigationBar appearance] setTintColor:[UIColor darkGrayColor]];
[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor darkGrayColor], NSFontAttributeName : [UIFont fontWithName:@"Helvetica Neue" size:22]}];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
</code></pre>
| 0 | 1,680 |
How can I implement a fixed sidebar?
|
<p>I have a situation like this:</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<title>test</title>
</head>
<style>
#wrapper { width: 1100px; margin: 0px auto; }
#wrapper #stream { width: 790px; float: left; border: 1px solid red; }
#wrapper aside { width: 270px; float: left; border: 1px solid red; }
</style>
<body>
<section id="wrapper">
<section id="stream">
some text...
</section>
<aside>
<ul>
<li>something</li>
<li>something</li>
<li>something</li>
<li>something</li>
</ul>
</aside>
</section>
</body>
</html>
</code></pre>
<p>and I don't want the sidebar to move even if the page scrolls down.</p>
<p>I tried setting the aside's position to fixed but so I can't set properly the distance from left.</p>
<p>I found a solution with jQuery:</p>
<pre><code>$(document).ready(function () {
$(window).scroll(function () {
$("aside").css('top', $(window).scrollTop()+'px');
});
})
</code></pre>
<p>but with Chrome and Safari the scroll of the aside is piecewise.</p>
<p>Any help?</p>
<p>========================</p>
<p><strong>SOLUTION:</strong></p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<title>test</title>
</head>
<style>
#wrapper {
width: 1100px;
margin: 0px auto;
}
#stream {
width: 800px;
background: #ccc;
float: left;
}
#sidebar {
float: left;
border: 1px solid red;
width: 200px;
}
aside {
position: fixed;
top: 20px;
border: 1px solid red;
}
</style>
<body>
<section id="wrapper">
<section id="stream">
some text...
</section>
<section id="sidebar">
<aside>
<ul>
<li>something</li>
<li>something</li>
<li>something</li>
<li>something</li>
</ul>
</aside>
</section>
</body>
</html>
</code></pre>
| 0 | 1,412 |
General method for calculating Smooth vertex normals with 100% smoothness
|
<p>I've looked online for quite some time and can't find an answer to this.
For simplicity, let's just assume I need to fully smooth out the normals of a group of cojoined faces. <strong>I want to find the actual geometric bisector between a group of vectors, ignoring duplicate normals and maintaining accuracy with triangle soups</strong>. Basically, it needs to:</p>
<ul>
<li>Work with triangle soups - be it three, 4 or 4000 triangles, the normals still need to work together in a geometrically correct fashion without being biased towards arbitrary areas</li>
<li>Ignore overlapping (parallel) normals - if I have a cube's edge that comes together in 3 triangles, or one that comes together in one triangle for each of two sides and 2 (or more) for the last side, or one that has a million triangles on only one side, the bisector must not change</li>
</ul>
<p>The most common formula I seem to be finding for normal smoothing is, to simply average them by summing together the normal vectors and divide by three; example:</p>
<pre><code>normalize((A + B + C) / 3);
</code></pre>
<p>Of course dividing by three is useless, which already denotes the vibe of naive, off-the-top-of-your-head brute force averaging method that people propose; problems with this are also the fact that it messes up big time with even triangle soups and parallel normals.</p>
<p>Another remark I seem to find is to keep the initial "facet" normals as they come from a common cross multiply operation that generates them, as that way they are (kinda) weighted against the triangle's area. This might be something you want to do in some cases, however I need the pure bisector, so area must not influence the formula, and even accounting for it it still gets messed up by triangle soups.</p>
<p>I saw one mentioned method that says to weight against the angle between the adjacent faces, but I can't seem to implement the formula correctly - either that or it's not doing what I want. However that's hard for me to say, since I can't find a concise explanation for it and my mind is becoming numb from all this wasted brainstorming.</p>
<p>Anybody knows of a general formula?
If it is of any help, I'm working with C++ and DirectX11.</p>
<hr>
<p><strong>Edit</strong>: Here's some similar questions that describe some of the methods;</p>
<ul>
<li><a href="https://stackoverflow.com/questions/21766605/how-to-achieve-smooth-tangent-space-normals">How to achieve smooth tangent space normals?</a></li>
<li><a href="https://stackoverflow.com/questions/16340931/calculating-vertex-normals-of-a-mesh">Calculating Vertex Normals of a mesh</a></li>
<li><a href="https://stackoverflow.com/questions/6656358/calculating-normals-in-a-triangle-mesh">Calculating normals in a triangle mesh</a></li>
<li><a href="https://stackoverflow.com/questions/25100120/how-does-blender-calculate-vertex-normals">How does Blender calculate vertex normals?</a></li>
<li><a href="https://stackoverflow.com/questions/13205226/most-efficient-algorithm-to-calculate-vertex-normals-from-set-of-triangles-for-g">Most efficient algorithm to calculate vertex normals from set of triangles for Gouraud shading</a></li>
</ul>
<p>Also this article:
<a href="http://www.bytehazard.com/articles/vertnorm.html" rel="noreferrer">http://www.bytehazard.com/articles/vertnorm.html</a></p>
<p>Unfortunately, the implementations I tried didn't work and I couldn't find a clear, concise statement about which formula was actually the one that I needed. After some trial and error I finally figured out that weighting by angle was the correct way to do it, only I wasn't able to implement it correctly; as it seems to be working now, I'll add my implementation as an answer below.</p>
| 0 | 1,040 |
Object with id was not of the specified subclass
|
<p>I'm getting a weird error on my application.<br>
I'm trying to retrieve an list of entity from database (MySQL) with <code>session.createCriteria().list()</code> but I'm getting this <code>org.hibernate.WrongClassException</code>.</p>
<p>I have looked up this error and I know what it means, but I don't know how to solve it on my context.</p>
<p>I have the following database structure:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE vtiger_crmentity (
`crmid` int(19) NOT NULL
)
CREATE TABLE vtiger_account (
`accountid` int(19) NOT NULL DEFAULT 0
)
CREATE TABLE vtiger_accountscf (
`accountid` int(19) NOT NULL DEFAULT 0
)
CREATE TABLE vtiger_accoutshipads (
`accountaddressid` int(19) NOT NULL DEFAULT 0
)
CREATE TABLE vtiger_accountbillads (
`accountaddressid` int(19) NOT NULL DEFAULT 0
)
</code></pre>
<p>So, quickly explaining, all the tables are linked by the these id columns, and in the last level, the <code>vtiger_accountscf</code> table has 1 <code>vtiger_accountshipads</code> and 1 <code>vtiger_accountbillads</code>. All the tables have the same PK.<br>
So I made my classes like this (stubs):</p>
<pre class="lang-java prettyprint-override"><code>@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "vtiger_crmentity")
public class VtigerCrmentity {
@Id
@Basic(optional = false)
@Column(name = "crmid", nullable = false)
public Integer getId() {
return this.id;
}
}
@Entity
@PrimaryKeyJoinColumn(name = "accountid")
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "vtiger_account")
public class VtigerAccount extends VtigerCrmentity {
}
@Entity
@PrimaryKeyJoinColumn(name = "accountid")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "vtiger_accountscf")
public class VtigerAccountscf extends VtigerAccount {
}
@Entity
@PrimaryKeyJoinColumn(name = "accountaddressid")
@Table(name = "vtiger_accountbillads")
public class VtigerAccountbillads extends VtigerAccountscf {
}
@Entity
@PrimaryKeyJoinColumn(name = "accountaddressid")
@Table(name = "vtiger_accountshipads")
public class VtigerAccountshipads extends VtigerAccountscf {
}
</code></pre>
<p>And here's my problem. When I do:</p>
<pre class="lang-java prettyprint-override"><code>getSession().createCriteria(VtigerAccountbillads.class).list();
</code></pre>
<p>I'm getting the exception:</p>
<pre><code>org.hibernate.WrongClassException: Object with id: 11952 was not of the specified subclass: VtigerAccountbillads (loaded object was of wrong class class VtigerAccountshipads)
at org.hibernate.loader.Loader.instanceAlreadyLoaded(Loader.java:1391)
at org.hibernate.loader.Loader.getRow(Loader.java:1344)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:611)
at org.hibernate.loader.Loader.doQuery(Loader.java:829)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2533)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
</code></pre>
<p>By project limitations, I'm not using spring or nothing similar to configure the Hibernate and create the session.</p>
<p>Is my mapping wrong?</p>
| 0 | 1,229 |
Mongo aggregation cursor & counting
|
<p>According to the <a href="http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#aggregate">mongodb node driver docs</a> the aggregate function now returns a cursor (from 2.6).</p>
<p>I hoped that I could use this to get a count of items pre limit & skipping but there doesn't seem to be any count function on the created cursor. If I run the same queries in the mongo shell the cursor has an itcount function that I can call to get what I want.</p>
<p>I saw that the created cursor has an on data event (does that mean it's a <a href="http://mongodb.github.io/node-mongodb-native/api-generated/cursorstream.html">CursorStream</a>?) which seemed to get triggered the expected number of times, but if I use it in combination with cursor.get no results get passed into the callback function.</p>
<p>Can the new cursor feature be used to count an aggregation query?</p>
<p>Edit for code:</p>
<p>In mongo shell:</p>
<pre><code>> db.SentMessages.find({Type : 'Foo'})
{ "_id" : ObjectId("53ea19af9834184ad6d3675a"), "Name" : "123", "Type" : "Foo" }
{ "_id" : ObjectId("53ea19dd9834184ad6d3675c"), "Name" : "789", "Type" : "Foo" }
{ "_id" : ObjectId("53ea19d29834184ad6d3675b"), "Name" : "456", "Type" : "Foo" }
> db.SentMessages.find({Type : 'Foo'}).count()
3
> db.SentMessages.find({Type : 'Foo'}).limit(1)
{ "_id" : ObjectId("53ea19af9834184ad6d3675a"), "Name" : "123", "Type" : "Foo" }
> db.SentMessages.find({Type : 'Foo'}).limit(1).count();
3
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}} ])
{ "_id" : ObjectId("53ea19af9834184ad6d3675a"), "Name" : "123", "Type" : "Foo" }
{ "_id" : ObjectId("53ea19dd9834184ad6d3675c"), "Name" : "789", "Type" : "Foo" }
{ "_id" : ObjectId("53ea19d29834184ad6d3675b"), "Name" : "456", "Type" : "Foo" }
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}} ]).count()
2014-08-12T14:47:12.488+0100 TypeError: Object #<Object> has no method 'count'
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}} ]).itcount()
3
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}}, {$limit : 1} ])
{ "_id" : ObjectId("53ea19af9834184ad6d3675a"), "Name" : "123", "Type" : "Foo" }
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}}, {$limit : 1} ]).itcount()
1
> exit
bye
</code></pre>
<p>In Node:</p>
<pre><code>var cursor = collection.aggregate([ { $match : { Type : 'Foo'}}, {$limit : 1} ], { cursor : {}});
cursor.get(function(err, res){
// res is as expected (1 doc)
});
</code></pre>
<p>cursor.count() does not exist</p>
<p>cursor.itcount() does not exist</p>
<p>The on data event exists:</p>
<pre><code>cursor.on('data', function(){
totalItems++;
});
</code></pre>
<p>but when used in combination with cursor.get, the .get callback function now contains 0 docs</p>
<p>Edit 2: The cursor returned appears to be an <a href="https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/aggregation_cursor.js">aggregation cursor</a> rather than one of the cursors listed in the docs</p>
| 0 | 1,175 |
Updating SQL Database from DataGridView in C#
|
<p>There's a few tutorials out there on this, but I'm assuming I must have implemented something wrong, because the code I followed from combined tutorials is not working as it should.</p>
<p>These are the tutorials: <a href="https://youtu.be/_i4mYXSaD4w" rel="nofollow">https://youtu.be/_i4mYXSaD4w</a> , <a href="https://youtu.be/_sB0A6FIhUM" rel="nofollow">https://youtu.be/_sB0A6FIhUM</a></p>
<p>I'm trying to create a DataGridView that displays some basic data, just 4 columns of information. I want the user to be able to add, update and delete rows of information. I've manually created 1 row of information in the SQL database just to avoid in 'catches' when the program is loaded.</p>
<p>I've got the 1 line of my SQL Database information loading just fine, but when I edit the information, and click my update button it doesn't seem to work on the SQL side, even though the program side works. By this I mean, I have a messagebox that confirms it's been updated, but when I close the App and the run it again, it loads the old data, and when I double check the database, it hasn't been updated. If someone could help me adjust this so when I add rows of information to the DataGridView or edit the rows, and have the SQL file actually receive the changes/updates, I'd appreciate it. Here is my code:</p>
<pre><code>public partial class Form1 : Form
{
SqlConnection con;
SqlDataAdapter sda;
DataTable dt;
SqlCommandBuilder scb;
private int rowIndex = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection(Properties.Settings.Default.SchoolConnectionString);
con.Open();
sda = new SqlDataAdapter("SELECT * FROM School", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpButton_Click(object sender, EventArgs e)
{
try
{
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//button to refresh the data without need to close the app
private void RefButton_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection(Properties.Settings.Default.SchoolConnectionString);
con.Open();
sda = new SqlDataAdapter("SELECT * FROM School", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CloseButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
//BROKEN - supposed to bring up a menu item to delete the row
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.dataGridView1.Rows[e.RowIndex].Selected = true;
this.rowIndex = e.RowIndex;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[1];
this.contextMenuStrip1.Show(this.dataGridView1, e.Location);
contextMenuStrip1.Show(Cursor.Position);
}
}
private void contextMenuStrip1_Click(object sender, CancelEventArgs e)
{
if (!this.dataGridView1.Rows[this.rowIndex].IsNewRow)
{
this.dataGridView1.Rows.RemoveAt(this.rowIndex);
}
}
}
</code></pre>
<p>Now, what I'm not sure about is 1 thing I changed from one of the tutorials, was that they used a dataset rather than a datatable, but as I understand it, other than a dataset being able to hold multiple table structures, there's no differences in pulling the data or updating it. For the fact that I didn't have mounds of data and different tables to use, I felt DataTable was sufficient for my use of this program.</p>
<p>Additionally, in my database, I have a primary key that's an integer, and 4 columns of text. I'd prefer to avoid the stupid column of integers like line numbers and just make my first text column the primary key, but when I try to do this and update the database, it throws errors. If there's a way to do this, I'd appreciate the explanation of how, or if there's a way to hide the first line number column the pulls the integer value for the primary key, and have it automatically increment and/or adjust this value according to editing, changes and new rows being added that'd be great. Just to clear up, if I add rows 2, 3 and 4, I want these values to be autogenerated and just make that column not visible. As it stands, I have to manually type the integer in there. </p>
<p>Thanks for any help and advice.</p>
<p>Update #1:</p>
<p>Okay, so taking some recommendations, I have tried using DataSet in the following format:</p>
<pre><code>private void Form1_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection(Properties.Settings.Default.SchoolConnectionString);
con.Open();
sda = new SqlDataAdapter("SELECT * FROM School", con);
ds = new DataSet();
sda.Fill(ds, "e");
dataGridView1.DataSource = ds.Tables["e"];
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpButton_Click(object sender, EventArgs e)
{
try
{
scb = new SqlCommandBuilder(sda);
sda.Update(ds, "e");
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
</code></pre>
<p>I've tried using DataTable again in the format given in the first answer provided using the following format but in 2 ways: 1 without a new instance of the SqlCommandBuilder, and one with:
WITH:</p>
<pre><code>private void Form1_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection(Properties.Settings.Default.SchoolConnectionString);
con.Open();
sda = new SqlDataAdapter("SELECT * FROM School", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpButton_Click(object sender, EventArgs e)
{
try
{
scb = new SqlCommandBuilder(sda);
newDT = dt.GetChanges();
if (newDT != null)
{
sda.Update(newDT);
}
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
</code></pre>
<p>WITHOUT: This version produces an error that says: "Update requires a valid UpdateCommand when passed DataRow collection with modified rows."</p>
<pre><code>private void Form1_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection(Properties.Settings.Default.SchoolConnectionString);
con.Open();
sda = new SqlDataAdapter("SELECT * FROM School", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpButton_Click(object sender, EventArgs e)
{
try
{
newDT = dt.GetChanges();
if (newDT != null)
{
sda.Update(newDT);
}
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
</code></pre>
<p>Sooooo, I'm stumped. All except the one without SqlCommandBuilder trigger the Updated Message Box, but none of them actually save the changes to the sql database.</p>
| 0 | 3,650 |
Docker port forwarding not working
|
<p>I have setup Docker container for access my machine docker container to another machine in local.</p>
<p>Create a container below command:</p>
<pre><code> docker run -it -d --name containerName -h www.myhost.net -v /var/www/html -p 7000:8000 --net mynetwork --ip 172.11.0.10 --privileged myimagename bash
</code></pre>
<p>After Create A Container Details:</p>
<pre><code> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1e1e5e9b74b4 myimgaename "bash" 21 minutes ago Up 6 minutes 0.0.0.0:7000->8000/tcp containername
</code></pre>
<p>NetWork Details:</p>
<pre><code> "NetworkSettings": {
"Bridge": "",
"SandboxID": "fe357c54c816fff0f9d642037dc9a173be7f7e42a80776d006572f6a1395969e",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"8000/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "7000"
}
]
}
</code></pre>
<p>if I access docker ipaddr(172.11.0.10) or hostname(www.myhost.net) in mymachine(hostmachine) it working </p>
<p>But if I access with <strong>Port</strong> doesn't work: hostmachine ip: 192.168.1.1</p>
<pre><code> go to the browser 192.168.1.1:7000 hostmachine and locally connected anoter machine also.
</code></pre>
<p>But My 7000 port are listen in hostmachine: </p>
<pre><code> # ps aux | grep 7000
root 10437 0.0 0.2 194792 24572 pts/0 Sl+ 12:33 0:00 docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 7000 -container-ip 172.11.0.10 -container-port 8000
root 10941 0.0 0.0 118492 2324 pts/3 R+ 12:44 0:00 grep --color=auto 7000
</code></pre>
<p><strong>update 1:</strong></p>
<pre><code> $ docker version
Client:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 21:39:21 2016
OS/Arch: linux/amd64
Server:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 21:39:21 2016
OS/Arch: linux/amd64
</code></pre>
<p>Suggest me Why Cannot access my Container to another machine. How to Resolve this Problem</p>
| 0 | 1,275 |
parsing json into an array in swift 3
|
<p>I am new on swift and I am getting a json back from a request but I can not parse. I am trying to get the json info and create coordinates to use on mapkit with annotations as well</p>
<p>Below is the json I get back</p>
<pre><code>{
coord = [
{
islocationactive = 1;
latitude = "37.8037522";
locationid = 1;
locationsubtitle = Danville;
locationtitle = "Schreiner's Home";
longitude = "121.9871216";
},
{
islocationactive = 1;
latitude = "37.8191921";
locationid = 2;
locationsubtitle = "Elementary School";
locationtitle = Montair;
longitude = "-122.0071005";
},
{
islocationactive = 1;
latitude = "37.8186077";
locationid = 3;
locationsubtitle = "Americas Eats";
locationtitle = "Chaus Restaurant";
longitude = "-121.999046";
},
{
islocationactive = 1;
latitude = "37.7789669";
locationid = 4;
locationsubtitle = "Cheer & Dance";
locationtitle = Valley;
longitude = "-121.9829908";
}
] }
</code></pre>
<p>and my code to try to parse is this</p>
<pre><code> let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
//exiting if there is some error
if error != nil{
print("error is \(error)")
return;
}
//parsing the response
do {
//converting resonse to NSDictionary
var teamJSON: NSDictionary!
teamJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print(teamJSON)
//getting the JSON array teams from the response
let liquidLocations: NSArray = teamJSON["coord"] as! NSArray
//looping through all the json objects in the array teams
for i in 0 ..< liquidLocations.count{
//getting the data at each index
// let teamId:Int = liquidLocations[i]["locationid"] as! Int!
}
} catch {
print(error)
}
}
//executing the task
task.resume()
</code></pre>
<p>but not that I try works. I want to get the latitude, longitude and create an annotationn on the map</p>
<p>Thanks for the help</p>
| 0 | 1,316 |
maven-surefire-report-plugin not generating surefire-report.html
|
<p>I'm unable to get the <strong>maven-surefire-report-plugin</strong> to generate the <strong>surefire-report.html</strong> when I run:</p>
<pre><code>mvn clean deploy site
mvn clean site
mvn site
mvn clean install site
</code></pre>
<p>The only time I've been able to get the report generated is when I run:</p>
<pre><code>mvn surefire-report:report
</code></pre>
<p>Here is a look at my <strong>pom.xml</strong></p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>blah.blah</groupId>
<artifactId>build</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>build</name>
<description>build</description>
<properties>
...
</properties>
<modules>
<module>../report</module>
</modules>
<dependencyManagement>
<dependencies>
...
<!-- Custom local repository dependencies -->
<dependency>
<groupId>asm</groupId>
<artifactId>asm-commons</artifactId>
<version>3.1</version>
</dependency>
...
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
...
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Xmx1024m -XX:MaxPermSize=256m -XX:-UseGCOverheadLimit -Dsun.lang.ClassLoader.allowArraySyntax=true</argLine>
<includes>
<include>**/*Test.java</include>
<include>**/*_UT.java</include>
</includes>
<excludes>
<exclude>**/*_IT.java</exclude>
<exclude>**/*_DIT.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.7.2</version>
</plugin>
</plugins>
</reporting>
</project>
</code></pre>
<p>There are 2 tests in my project and <strong>TEST-*.xml</strong> files are generated in <strong>surefire-reports</strong><br>
Also, the <em>site</em> folder is generated with a <em>css</em> and <em>images</em> folder and contents, but no report.</p>
| 0 | 1,773 |
Run Selenium WebDriver test on a linux server
|
<p>I'm trying to run a test implemented with selenium webdriver on a Linux server with chrome and no display
this my java code</p>
<pre><code> System.setProperty("webdriver.chrome.driver","/home/exploit/Bureau/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
WebElement element = driver .findElement(By.id("lst-ib"));
</code></pre>
<p>to run this program (jar) a start the Xvfb with the command</p>
<pre><code>Xvfb :1 -screen 5 1024x768x8 &
export DISPLAY=:1.5
</code></pre>
<p>when I run the program I got this Exception after a bit long waiting </p>
<pre><code>12:39:53.483 [Forwarding newSession on session null to remote] DEBUG o.a.h.i.conn.DefaultClientConnection - Connection 0.0.0.0:51411<->127.0.0.1:9069 closed
12:39:53.483 [Forwarding newSession on session null to remote] DEBUG o.a.h.i.conn.tsccm.ConnPoolByRoute - Notifying no-one, there are no waiting threads
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.9.248304,platform=Linux 3.10.0-123.13.2.el7.x86_64 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 60.69 seconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0- 123.13.2.el7.x86_64', java.version: '1.7.0_79'
Driver info: driver.version: ChromeDriver
Session ID: 6c811fab5c809544094e1f9e1d96ef6a
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:188)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:531)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:215)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:110)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:114)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:161)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:107)
at com.atos.esope.Extractor.extTest(Extractor.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:201)
at com.sun.proxy.$Proxy27.extTest(Unknown Source)
at com.atos.esope.Program.main(Program.java:32)
</code></pre>
<p>and when I try to run chrome separately a got this problem</p>
<pre><code>Xlib: extension "RANDR" missing on display ":1.5".
Xlib: extension "RANDR" missing on display ":1.5".
Xlib: extension "RANDR" missing on display ":1.5".
Xlib: extension "RANDR" missing on display ":1.5".
Xlib: extension "RANDR" missing on display ":1.5".
Xlib: extension "RANDR" missing on display ":1.5".
Xlib: extension "RANDR" missing on display ":1.5".
[3207:3207:0505/171255:ERROR:url_pattern_set.cc(240)] Invalid url pattern: chrome://print/*
libGL error: failed to load driver: swrast
libGL error: Try again with LIBGL_DEBUG=verbose for more details.
libGL error: failed to load driver: swrast
libGL error: Try again with LIBGL_DEBUG=verbose for more details.
libGL error: failed to load driver: swrast
libGL error: Try again with LIBGL_DEBUG=verbose for more details.
libGL error: failed to load driver: swrast
libGL error: Try again with LIBGL_DEBUG=verbose for more details.
libGL error: failed to load driver: swrast
libGL error: Try again with LIBGL_DEBUG=verbose for more details.
libGL error: failed to load driver: swrast
libGL error: Try again with LIBGL_DEBUG=verbose for more details.
</code></pre>
<p>the questions are :</p>
<p>is the problem in locating the driver or in chrome or I need some additional configuration ?</p>
| 0 | 1,640 |
Unknown tag (c:foreach). in eclipse
|
<p>I have jstl code and it builds by maven well... But Eclipse had compilation error "Unknown tag (c:foreach)."</p>
<p>code are here:</p>
<pre><code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<ul>
<c:forEach items="${listOfMyFriends}" var="friend">
<c:out value="${friend}"></c:out>
</c:forEach>
</ul>
</body>
</html>
</code></pre>
<p>could someone help me to avoid this promlem?</p>
<p>There are full pom: `
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0</p>
<pre><code><groupId>com.godzevych</groupId>
<artifactId>springInActionMVCTemplate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springInActionMVCTemplate</name>
<url>http://maven.apache.org</url>
<properties>
<java.version>1.6</java.version>
<spring.version>3.1.0.RELEASE</spring.version>
<cglib.version>2.2.2</cglib.version>
</properties>
<dependencies>
<!-- Spring core & mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<!-- CGLib for @Configuration -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Servlet Spec -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<!-- JSR 330 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>springsource-milestones</id>
<name>SpringSource Milestones Proxy</name>
<url>https://oss.sonatype.org/content/repositories/springsource-milestones</url>
</repository>
</repositories>
<build>
<finalName>springInActionMVCTemplate</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>`</p>
| 0 | 2,404 |
Running daemon with exec-maven-plugin avoiding `IllegalThreadStateException`
|
<p>I would like to run a daemon thread which should start on maven package phase. This is what I have in pom.xml:</p>
<pre><code><build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.test.Startup</mainClass>
<cleanupDaemonThreads>true</cleanupDaemonThreads>
</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>And here is the content of the class Startup:</p>
<pre><code>public class Startup {
public static class Testing extends Thread {
@Override
public void run() {
while(true) {
System.out.println("testing..");
}
}
}
public static void main(String[] list) throws Exception {
Testing t = new Testing();
t.setDaemon(true);
t.start();
}
}
</code></pre>
<p>The thread starts to run but the compile stops while the thread is running. After some time (timeout or something) the thread stops and the compilation continues. Is there anyway I can get this thread to start on the background and make the compilation continue on its own?</p>
<p>Some output from the maven:</p>
<pre><code>[WARNING] thread Thread[Thread-1,5,com.test.Startup] was interrupted but is still alive after waiting at least 15000msecs
[WARNING] thread Thread[Thread-1,5,com.test.Startup] will linger despite being asked to die via interruption
[WARNING] NOTE: 1 thread(s) did not finish despite being asked to via interruption. This is not a problem with exec:java, it is a problem with the running code. Although not serious, it should be remedied.
[WARNING] Couldn't destroy threadgroup org.codehaus.mojo.exec.ExecJavaMojo$IsolatedThreadGroup[name=com.test.Startup,maxpri=10]
java.lang.IllegalThreadStateException
at java.lang.ThreadGroup.destroy(ThreadGroup.java:754)
at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:334)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
</code></pre>
<p>I am planning to create a socket listener to this thread and let it live in the background as long as the maven shuts the JVM down but currently it seems the socket will be on only for some time during the compilation.</p>
| 0 | 1,832 |
TypeError: callback is not a function in nodejs
|
<p>I am trying learn nodejs and stumble upon this error </p>
<p><em>TypeError: callback is not a function</em></p>
<p>when I am trying to call the server using this command.</p>
<p><em>curl <a href="http://localhost:8090/albums.json" rel="noreferrer">http://localhost:8090/albums.json</a></em></p>
<p>and here is the code for my server.js</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>var http = require('http'),
fs = require('fs');
function load_album(album_name, callback) {
fs.readdir("albums/", +album_name, (err, files) => {
if (err) {
if (err.code == "ENOENT") {
callback(make_error("no_such_album", "That album doesn't exist"));
} else {
callback(make_error("can't load album", "The server is broken"));
}
} else {
//callback(null, files);
var only_files = [];
var path = 'albums/${album_name}/';
var iterator = (index) => {
if (index == files.length) {
var obj = {
short_name: album_name,
photos: only_files
};
callback(null, obj);
return;
}
fs.stat(path + files[index], (err, stats) => {
if (!err && stats.isFile()) {
only_files.push(files[index]);
}
iterator(index + 1);
});
};
iterator(0);
}
});
}
function handle_incoming_request(req, res) {
console.log("incoming request: " + req.method + " " + req.url);
if (req.url == '/albums.json') {
load_album((err, albums) => {
if (err) {
res.writeHead(500, {
"Content-Type": "application/json "
});
res.end(JSON.stringify({
code: "cant_load_albums",
message: err.message
}));
} else {
var output = {
error: null,
data: {
albums: albums
}
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(output) + "\n");
}
});
} else if (req.url.substr(0, 7) == '/albums' && req.url.substr(req.url.length - 5) == '.json') {
//user is requesting contents of album
load_album(req.url.substr(7, req.url.length - 12), (err, photos) => {
if (err) {
res.writeHead(500, {
"Content-type": "application/json"
});
res.end(JSON.stringify(err));
} else {
var output = {
error: null,
data: {
photos: photos
}
};
res.writeHead(200, {
"Content-Type": application / json
});
res.end(JSON.stringify(output) + "\n");
}
});
} else {
res.writeHead(404, {
"Content-type": "application/json"
});
res.end(JSON.stringify({
code: "no_such_page",
message: "No such page"
}));
}
}
var s = http.createServer(handle_incoming_request);
s.listen(8090);</code></pre>
</div>
</div>
</p>
<p>can you tell me what's wrong with my code that I got an error telling me callback isn't a function?</p>
<p>thanks though</p>
<p>for more formatted code then you can go here <a href="https://jsfiddle.net/02dbx6m9/" rel="noreferrer">https://jsfiddle.net/02dbx6m9/</a></p>
| 0 | 1,596 |
How do you pass conditional compilation symbols (DefineConstants) to msbuild
|
<p>So, both <a href="https://stackoverflow.com/questions/479979/msbuild-defining-conditional-compilation-symbols">this</a> and <a href="http://msdn.microsoft.com/en-us/library/bb629394.aspx" rel="noreferrer">this</a> are pretty clear. Simply pass <code>/p:DefineConstants="SYMBOL"</code></p>
<p>It doesn't work at all for me, even in a test project. I'm expecting that passing /p:DefineConstants="SYMBOL" will override any conditional compilation constants defined in the csproj. Not the case however...</p>
<p>Full code listing below:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DefineConstants
{
class Program
{
static void Main(string[] args)
{
#if DEV
Console.WriteLine("DEV");
#elif UAT
Console.WriteLine("UAT");
#else
Console.WriteLine("No environment provided");
#endif
}
}
}
</code></pre>
<p>.csproj file is:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{57A2E870-0547-475C-B0EB-66CF9A2FE417}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DefineConstants</RootNamespace>
<AssemblyName>DefineConstants</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
</code></pre>
<p>built using:</p>
<pre><code>C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild DefineConstants.sln /p:DefineConstants="DEV;DEBUG" /p:Configuration="Debug" /p:Platform="x86"
</code></pre>
<p>Running the program shows:</p>
<pre><code>No environment provided
</code></pre>
<p><strong>Help!</strong></p>
| 0 | 1,701 |
convert html file to pdf using dompdf
|
<p>How do I properly use dompdf to convert html files into pdf. I'm doing something like this:</p>
<pre><code><?php
require_once("lib/dompdf/dompdf_config.inc.php");
$file = "checkout.html";
$dompdf = new DOMPDF();
$dompdf->load_html_file($file);
$dompdf->render();
$dompdf->stream("sample.pdf");
?>
</code></pre>
<p>But I get this error:</p>
<pre><code>Fatal error: Call to undefined method Inline_Frame_Decorator::normalise() in C:\wamp\www\pos\php\lib\dompdf\include\table_frame_decorator.cls.php on line 252
</code></pre>
<p>How do I solve this, please enlighten me. Thanks.</p>
<p><strong>Update</strong>
Here are the contents of checkout.html</p>
<pre><code><table border="0">
<th colspan="10">Product</th>
<th>Quantity</th>
<th>Price</th>
<!--<th>Discount</th><!-- commented out jan 21-->
<th>Subtotal</th>
<!-- fetch values from reports and prod_table using the qtysoldfetcher query-->
<tr>
<td colspan="10">Boysen</td>
<td>4</td>
<td>900</td>
<!-- <td></td> --><!-- commented out jan 21-->
<td>3600</td>
</tr>
<h3 id="wyt">Sales Transaction Summary</h3><a href="pdfqtysold.php"><img id="tablez" src="../img/system/icons/Oficina-PDF-icon.png"></img></a>
<tr>
<td>Total Bill: </td>
<td colspan="8">3600</td>
<!--added jan 19 -->
</tr>
<tr>
<td>Amount paid: </td>
<td colspan="8">900</td>
</tr>
<tr>
<td>Change: </td>
<td colspan="8"></td>
</tr>
<tr>
<td>Credit: </td>
<td colspan="8">2700</td>
</tr>
<tr>
<td>Date: </td>
<td colspan="8">2011-01-28 11:13:52</td>
</tr>
<tr>
<td>Bought by: </td>
<td colspan="8">Asakura, Yoh</td>
</tr>
<!--end-->
</table>
</code></pre>
| 0 | 1,083 |
spring jndi datasource setup
|
<p>Hi i am trying to use jndi data source. below is the code</p>
<p><strong>context.xml</strong></p>
<pre><code> <Context antiJARLocking="true" path="/SpringMVCTest">
<Resource auth="Container" driverClassName="com.mysql.jdbc.Driver"
maxActive="20" maxIdle="10" maxWait="10000"
name="jdbc/pluto" password=""
type="javax.sql.DataSource"
url="jdbc:mysql://localhost:3306/spring?zeroDateTimeBehavior=convertToNull"
username="pluto"/>
</Context>
</code></pre>
<p>in spring-servlet config bean is:</p>
<pre><code><bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jdbc/pluto" value="java:comp/env/jdbc/pluto"/>
</bean>
</code></pre>
<p>i am getting this error</p>
<blockquote>
<p>org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'contactController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private app.contact.service.ContactService
app.contact.controller.ContactController.contactService; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'contactServiceImpl': Injection of
autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private app.contact.dao.ContactDAO
app.contact.service.ContactServiceImpl.contactDAO; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'contactDAOImpl': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private org.hibernate.SessionFactory
app.contact.dao.ContactDAOImpl.sessionFactory; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in ServletContext
resource [/WEB-INF/spring-servlet.xml]: Cannot resolve reference to
bean 'dataSource' while setting bean property 'dataSource'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in ServletContext
resource [/WEB-INF/spring-servlet.xml]: Error setting property values;
nested exception is
org.springframework.beans.NotWritablePropertyException: Invalid
property 'jdbc/pluto' of bean class
[org.springframework.jndi.JndiObjectFactoryBean]: Bean property
'jdbc/pluto' is not writable or has an invalid setter method. Does the
parameter type of the setter match the return type of the getter?
Related cause:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in ServletContext
resource [/WEB-INF/spring-servlet.xml]: Error setting property values;
nested exception is
org.springframework.beans.NotWritablePropertyException: Invalid
property 'jdbc/pluto' of bean class
[org.springframework.jndi.JndiObjectFactoryBean]: Bean property
'jdbc/pluto' is not writable or has an invalid setter method. Does the
parameter type of the setter match the return type of the getter?</p>
</blockquote>
| 0 | 1,095 |
Change the font color in a specific cell of a JTable?
|
<p>Before starting, I've viewed a handful of solutions as well as documentation. I can't seem to figure out why my code isn't working the way I believe it should work. I've extended DefaultTableCellRenderer but I don't believe it is being applied - that or I messed things up somewhere.</p>
<p>Here are the threads / websites I've looked into before posting this question:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/14546968/swing-is-it-possible-to-set-the-font-color-of-specific-text-within-a-jtable">Swing - Is it possible to set the font color of 'specific' text within a JTable cell?</a></li>
<li><a href="https://stackoverflow.com/questions/6644922/jtable-cell-renderer">JTable Cell Renderer</a></li>
<li><a href="http://docs.oracle.com/javase/tutorial/uiswing/components/table.html" rel="nofollow noreferrer">http://docs.oracle.com/javase/tutorial/uiswing/components/table.html</a></li>
</ul>
<p>I realize the first link uses HTML to change the font color, but I would think the way I went about it should produce the same result.</p>
<p>To make it easier on those who want to help me figure out the issues, I've created an SSCCE.</p>
<pre><code>import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class TableTest {
private static final int IMPORTANT_COLUMN = 2;
public static void createAndShowGUI() {
Object[][] data = new Object[2][4];
//create sample data
String[] realRowData = { "1", "One", "1.0.2", "compile" };
String[] fakeRowData = { "2", "Two", "1.3.2-FAKE", "compile" };
//populate sample data
for(int i = 0; i < realRowData.length; i++) {
data[0][i] = realRowData[i];
data[1][i] = fakeRowData[i];
}
//set up tableModel
JTable table = new JTable();
table.setModel(new DefaultTableModel(data,
new String[] { "ID #", "Group #", "version", "Action" })
{
Class[] types = new Class[] {
Integer.class, String.class, String.class, String.class
};
boolean[] editable = new boolean[] {
false, false, true, false
};
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return editable[columnIndex];
}
});
//set custom renderer on table
table.setDefaultRenderer(String.class, new CustomTableRenderer());
//create frame to place table
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setMinimumSize(new Dimension(400, 400));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
f.add(scrollPane);
f.pack();
f.setVisible(true);
}
//MAIN
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
//Custom DefaultTableCellRenderer
public static class CustomTableRenderer extends DefaultTableCellRenderer {
public Component getTableCellRenderer(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
String versionVal = table.getValueAt(row, IMPORTANT_COLUMN).toString();
if(versionVal.contains("FAKE")) {
//set to red bold font
c.setForeground(Color.RED);
c.setFont(new Font("Dialog", Font.BOLD, 12));
} else {
//stay at default
c.setForeground(Color.BLACK);
c.setFont(new Font("Dialog", Font.PLAIN, 12));
}
return c;
}
}
}
</code></pre>
<p>My goal is to highlight any value in the version column that contains the word <code>FAKE</code> in a red bold text.</p>
| 0 | 1,973 |
Javascript to get screen width in PHP variable
|
<p>I have a responsive site that has a <a href="http://www.red-team-design.com/simple-and-effective-dropdown-login-box" rel="noreferrer">simple drop-down login menu</a> when the site is in a "desktop" view (screen available width > 768) next to other navigational links. When the screen width drops below 768 the navigational links end up in a select option. The problem is that the drop-down login menu doesn't work from within a select option. </p>
<p>I would like to use PHP to change the drop-down login menu to a simple <code><a href></code> link when the screen width gets smaller than 768.</p>
<p>Right now I have in my page <code><head></code>:</p>
<pre><code><?
$screenWidth = '<script type="text/javascript">document.write(screen.availWidth);</script>';
?>
</code></pre>
<p>In the <code><body></code>:</p>
<pre><code><?
if($screenWidth <= "768") {
echo '<li><a href="login.php">Log in</a></li>';
} else {
?>
<div id="fancy">
<li id="login">
<a id="login-trigger" href="#">Log in <span>&#x25BC;</span></a>
<div id="login-content">
<form>
<fieldset id="inputs">
<input id="username" type="email" name="Email" placeholder="Your email address" required>
<input id="password" type="password" name="Password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="Log in">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form>
</div>
</li>
<? } ?>
</code></pre>
<p>On my desktop, I have echoed the $screenWidth, which gives 1920. Therefore I would expect the "fancy" drop-down login menu to be displayed. (And it does).</p>
<p>On my mobile, the $screenWidth echo gives 320. I would then expect the <code><a href></code> link to be displayed. (It does not - instead it displays the "fancy" menu).</p>
<p>It seems odd that the variable when echoed in the body will give a different number, but when compared in the if statement it does not change the output.</p>
<p>Is there a better way of changing the output?</p>
<p><strong>Edit: jquery responsive menu code</strong></p>
<p>jquery.responsivemenu.js:</p>
<pre><code>(function($) {
$.fn.responsiveMenu = function(options) {
var defaults = {autoArrows: false}
var options = $.extend(defaults, options);
return this.each(function() {
var $this = $(this);
var $window = $(window);
var setClass = function() {
if ($window.width() > 768) {$this.addClass('dropdown').removeClass('accordion').find('li:has(ul)').removeClass('accorChild');}
else {$this.addClass('accordion').find('li:has(ul)').addClass('accorChild').parent().removeClass('dropdown');}
}
$window.resize(function() {
setClass();
$this.find('ul').css('display', 'none');
});
setClass();
$this
.addClass('responsive-menu')
.find('li.current a')
.live('click', function(e) {
var $a = $(this);
var container = $a.next('ul,div');
if ($this.hasClass('accordion') && container.length > 0) {
container.slideToggle();
return false;
}
})
.stop()
.siblings('ul').parent('li').addClass('hasChild');
if (options.autoArrows) {
$('.hasChild > a', $this)
.find('strong').append('<span class="arrow">&nbsp;</span>');
}
});
}
})(jQuery);
</code></pre>
| 0 | 1,664 |
"Error: The shapes of the array expressions do not conform"
|
<p>This is my program to solve a problem of three dimensional cylindrical fin. But when i run this program in Fortran 6.2 this error shows up:</p>
<blockquote>
<p>Error: The shapes of the array expressions do not conform. [T]" </p>
</blockquote>
<p>Now i don't understand why this is happening. I need quick assistance. Anyone please help me. </p>
<pre><code> PROGRAM CYLINDRICAL FIN
DIMENSION T(500,500,500), OLDT(500,500,500),ERR(500,500,500)
DIMENSION R(500),Y(500),Z(500)
REAL CC,H,DR,DY,DZ,A,D,RY,YZ,ZR,B,E,TA,RL,YL,ZL
+P,AC,QF,MF,Q,EF,EFF,QMAX,AS,LC,QT,QF1,QF2
INTEGER I,J,K,M,N,L,M1,N1,L1,M2,M4,M34,N2,N4,N34,L2,L4,L34
RL=0.5
YL=6.283
ZL=0.04
M=100
N=40
L=20
M2=((M/2)+1)
M4=((M/4)+1)
M34=((3*M/4)+1)
N2=((N/2)+1)
N4=((N/4)+1)
N34=((3*N/4)+1)
L2=((L/2)+1)
L4=((L/4)+1)
L34=((3*L/4)+1)
DR=RL/M
DY=YL/N
DZ=ZL/L
CC=400.0
H=10.0
TA=25
M1=M-1
N1=N-1
L1=L-1
************VARIABLES************
A=DR*DY*DZ
D=DR+DY+DZ
RY=DR*DY
YZ=DY*DZ
ZR=DZ*DR
E=RY+YZ+ZR
************VARIABLES FOR EFFICIENCY AND EFFECTIVENESS (CROSS-SECTION AREA,PERIMETER,M,SURFACE AREA OF FIN)************
AC=3.1416*DR**2
P=2*(3.1416*DR+DZ)
MF=((H*P)/(CC*AC))**(0.5)
AS=2*3.1416*DR*DZ+3.1416*DR**2
************************************** distance discritization ******************
R(1)=0.0
Y(1)=0.0
Z(1)=0.0
R(M+1)=RL
Y(N+1)=YL
Z(L+1)=ZL
DO I=2,M
R(I)=R(I-1)+DR
END DO
DO J=2,N
Y(J)=Y(J-1)+DY
END DO
DO K=2,L
Z(K)=Z(K-1)+DZ
END DO
DO I=1,M
DO J=1,N
DO K=1,L
T(I,J,K)=0.0
END DO
END DO
END DO
DO I=1,M
DO J=1,N
T(I,J,1)=400
END DO
END DO
ITER=0.0
READ(*,*) LAST
31 CONTINUE
ITER=ITER+1
*************************************** FORMULAS**********************************
DO I=2,M1
DO J=2,N1
DO K=2,L1
T(I,J,K)=((R*DR*T(I+1,J,K)*(YZ)**2.0)-((T(I+1,J,K)+T(I-1,J,K))*
+(R*YZ)**2.0)-((T(I,J+1,K)+T(I,J-1,K))*(ZR**2.0))-((T(I,J,K+1)+
+T(I,J,K-1))*(R*RY)**2.0))/((R*DR*(YZ)**2.0)-(2.0*(R*YZ)**2.0)-
+(2.0*(ZR)**2.0)-(2.0*(R*RY)**2.0))
END DO
END DO
END DO
*************************************** END OF ITERATIONG FORMULAS****************
DO I=1,M
DO J=1,N
DO K=1,L
OLDT(I,J,K)=T(I,J,K)
END DO
END DO
END DO
DO I=1,M
DO J=1,N
DO K=1,L
ERR(I,J,K)=T(I,J,K)-OLDT(I,J,K)
END DO
END DO
END DO
EMAX=0.0
EMAX=MAX(EMAX,ERR(I,J,K))
WRITE(*,*) ITER, EMAX
IF (ITER.LT.LAST) GOTO 31
WRITE(*,*) DR,A,B,E
END PROGRAM CYLINDRICAL FIN
</code></pre>
| 0 | 1,670 |
Valgrind yells about an uninitialised bytes
|
<p>Valgrind throws me out this error:</p>
<pre><code>==11204== Syscall param write(buf) points to uninitialised byte(s)
==11204== at 0x4109033: write (in /lib/libc-2.13.so)
==11204== by 0x8049654: main (mmboxman.c:289)
==11204== Address 0xbe92f861 is on thread 1's stack
==11204==
</code></pre>
<p>What's the problem? I can't find what uninitialised byte it is yelling about.
Here are the criminal lines of code (the mentioned 289 line is the one which calls the function lockUp):</p>
<pre><code>Request request;
Response response;
fillRequest(&request, MANADDUSER, getpid(), argument1, NULL, NULL, 0, 0);
lockUp(&request, &response, NULL);
</code></pre>
<p>Here the functions prototype and structs declaration:</p>
<pre><code>void fillRequest(Request *request, char code, pid_t pid, char *name1, char *name2, char *object, int id, size_t size)
{
int k;
request->code = code;
request->pid = getpid();
if(name1) for(k=0; k<strlen(name1)+1; k++) request->name1[k] = name1[k];
else request->name1[0] = '\0';
if(name2) for(k=0; k<strlen(name2)+1; k++) request->name2[k] = name2[k];
else request->name2[0] = '\0';
if(object) for(k=0; k<strlen(name2)+1; k++) request->name2[k] = name2[k];
else request->object[0] = '\0';
request->id = id;
request->size = size;
}
void lockUp(Request *request, Response *response, void **buffer)
{
int fifofrom, fifoto, lock; /* file descriptor delle fifo e del lock */
/* locko per l'accesso alle FIFO */
if((lock = open(LOCK, O_RDONLY)) == -1) logMmboxman("error in opening LOCK\n", 1);
else logMmboxman("opened LOCK\n", 0);
if(flock(lock, LOCK_EX) == -1) logMmboxman("error in acquiring LOCK\n", 1);
else logMmboxman("acquired LOCK\n", 0);
/* apro la fifoto e scrivo la mia richiesta */
if((fifoto = open(FIFOTOMMBOXD, O_WRONLY)) == -1) logMmboxman("error in opening FIFOTO\n", 1);
else logMmboxman("opened FIFOTO\n", 0);
if((write(fifoto, request, sizeof(Request))) != sizeof(Request)) logMmboxman("error in writing FIFOTO\n", 1);
else logMmboxman("written on FIFOTO\n", 0);
close(fifoto);
/* rimango in attesa della risposta da mmboxd sulla fifofrom */
if((fifofrom = open(FIFOFROMMMBOXD, O_RDONLY)) == -1) logMmboxman("error in opening FIFOFROM\n", 1);
else logMmboxman("opened FIFOFROM\n", 0);
if((read(fifofrom, response, sizeof(Response))) != sizeof(Response)) logMmboxman("error in reading FIFOFROM\n", 1);
else logMmboxman("read from FIFOFROM\n", 0);
close(fifofrom);
/* se mi deve comunicare un buffer riapro la fifo e lo leggo */
if(response->size)
{
if((fifofrom = open(FIFOFROMMMBOXD, O_RDONLY)) == -1) logMmboxman("error in opening FIFOFROM again for the buffer\n", 1);
else logMmboxman("opened FIFOFROM again for the buffer\n", 0);
*buffer = (void*)malloc(response->size);
if(read(fifofrom, *buffer, response->size) != response->size) logMmboxman("error in reading FIFOFROM again for the buffer\n", 1);
else logMmboxman("read from FIFOFROM again for the buffer\n", 0);
close(fifofrom);
}
/* letta la risposta rilascio il lock */
if(flock(lock, LOCK_UN) == -1) logMmboxman("error in releasing LOCK\n", 1);
else logMmboxman("released LOCK\n", 0);
return;
}
typedef struct
{
char code;
pid_t pid;
char name1[41];
char name2[41];
char object[101];
int id;
size_t size;
} Request;
typedef struct
{
char result;
int num;
int num2;
size_t size;
} Response;
</code></pre>
| 0 | 2,247 |
Caused by: java.lang.IllegalStateException: No value has been specified for this provider
|
<p>I was trying to import a project from github , but it was showing this configuration issue.<br>
Can someone please suggest me what should i do?</p>
<pre><code> 2019-09-06 19:23:53,953 [ thread 10] INFO - e.project.sync.GradleSyncState - Gradle sync failed: No value has been specified for this provider. (9 m 7 s 838 ms)
2019-09-06 19:23:53,965 [ thread 10] WARN - ject.sync.ng.SyncResultHandler - Gradle sync failed
org.gradle.tooling.BuildException: Could not run phased build action using Gradle distribution 'https://services.gradle.org/distributions/gradle-5.4.1-all.zip'.
at org.gradle.tooling.internal.consumer.ExceptionTransformer.transform(ExceptionTransformer.java:51)
at org.gradle.tooling.internal.consumer.ExceptionTransformer.transform(ExceptionTransformer.java:29)
at org.gradle.tooling.internal.consumer.ResultHandlerAdapter.onFailure(ResultHandlerAdapter.java:41)
at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:57)
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)
at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
at org.gradle.tooling.internal.consumer.DefaultPhasedBuildActionExecuter.run(DefaultPhasedBuildActionExecuter.java:63)
at org.gradle.tooling.internal.consumer.DefaultPhasedBuildActionExecuter.run(DefaultPhasedBuildActionExecuter.java:31)
at com.android.tools.idea.gradle.project.sync.ng.SyncExecutor.executeFullSyncAndGenerateSources(SyncExecutor.java:281)
at com.android.tools.idea.gradle.project.sync.ng.SyncExecutor.syncProject(SyncExecutor.java:194)
at com.android.tools.idea.gradle.project.sync.ng.SyncExecutor.lambda$syncProject$1(SyncExecutor.java:137)
at org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper.execute(GradleExecutionHelper.java:227)
at com.android.tools.idea.gradle.project.sync.ng.SyncExecutor.syncProject(SyncExecutor.java:140)
at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync.sync(NewGradleSync.java:200)
at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync.access$000(NewGradleSync.java:69)
at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync$2.run(NewGradleSync.java:162)
at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:731)
at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:164)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:586)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:532)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:86)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:151)
at com.intellij.openapi.progress.impl.CoreProgressManager$4.run(CoreProgressManager.java:403)
at com.intellij.openapi.application.impl.ApplicationImpl$1.run(ApplicationImpl.java:312)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.gradle.internal.exceptions.LocationAwareException: A problem occurred configuring project ':app'.
at org.gradle.initialization.exception.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:99)
at org.gradle.initialization.exception.DefaultExceptionAnalyser.collectFailures(DefaultExceptionAnalyser.java:62)
at org.gradle.initialization.exception.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:47)
at org.gradle.initialization.exception.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:29)
at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:174)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:165)
at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:134)
at org.gradle.internal.invocation.GradleBuildController$1.execute(GradleBuildController.java:58)
at org.gradle.internal.invocation.GradleBuildController$1.execute(GradleBuildController.java:55)
at org.gradle.internal.invocation.GradleBuildController$3.create(GradleBuildController.java:82)
at org.gradle.internal.invocation.GradleBuildController$3.create(GradleBuildController.java:75)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:183)
at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:40)
at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:75)
at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:55)
at org.gradle.tooling.internal.provider.runner.ClientProvidedPhasedActionRunner.run(ClientProvidedPhasedActionRunner.java:60)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.BuildOutcomeReportingBuildActionRunner.run(BuildOutcomeReportingBuildActionRunner.java:58)
at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
at org.gradle.launcher.exec.BuildCompletionNotifyingBuildActionRunner.run(BuildCompletionNotifyingBuildActionRunner.java:39)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.call(RunAsBuildOperationBuildActionRunner.java:51)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.call(RunAsBuildOperationBuildActionRunner.java:45)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:49)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:46)
at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:78)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:46)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:31)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:42)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:28)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:78)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:52)
at org.gradle.tooling.internal.provider.SubscribableBuildActionExecuter.execute(SubscribableBuildActionExecuter.java:59)
at org.gradle.tooling.internal.provider.SubscribableBuildActionExecuter.execute(SubscribableBuildActionExecuter.java:36)
at org.gradle.tooling.internal.provider.SessionScopeBuildActionExecuter.execute(SessionScopeBuildActionExecuter.java:68)
at org.gradle.tooling.internal.provider.SessionScopeBuildActionExecuter.execute(SessionScopeBuildActionExecuter.java:38)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:37)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:26)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:60)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:32)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:41)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:48)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:32)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:81)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.
at org.gradle.configuration.project.LifecycleProjectEvaluator.wrapException(LifecycleProjectEvaluator.java:79)
at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:72)
at org.gradle.configuration.project.LifecycleProjectEvaluator.access$600(LifecycleProjectEvaluator.java:53)
at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate.run(LifecycleProjectEvaluator.java:198)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.configuration.project.LifecycleProjectEvaluator$EvaluateProject$1.run(LifecycleProjectEvaluator.java:111)
at org.gradle.internal.Factories$1.create(Factories.java:25)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:183)
at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:40)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.withProjectLock(DefaultProjectStateRegistry.java:226)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.withMutableState(DefaultProjectStateRegistry.java:220)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.withMutableState(DefaultProjectStateRegistry.java:186)
at org.gradle.configuration.project.LifecycleProjectEvaluator$EvaluateProject.run(LifecycleProjectEvaluator.java:95)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:67)
at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:695)
at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:143)
at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:62)
at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:41)
at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:302)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.initialization.DefaultGradleLauncher.configureBuild(DefaultGradleLauncher.java:210)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:151)
... 75 more
Caused by: java.lang.IllegalStateException: No value has been specified for this provider.
at org.gradle.api.internal.provider.AbstractReadOnlyProvider.get(AbstractReadOnlyProvider.java:29)
at org.gradle.api.internal.provider.AbstractMappingProvider.get(AbstractMappingProvider.java:49)
at org.gradle.util.DeferredUtil.unpack(DeferredUtil.java:42)
at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(DefaultFileCollectionResolveContext.java:122)
at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCollections(DefaultFileCollectionResolveContext.java:92)
at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext$FileCollectionConverter.convertInto(DefaultFileCollectionResolveContext.java:164)
at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(DefaultFileCollectionResolveContext.java:109)
at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCollections(DefaultFileCollectionResolveContext.java:92)
at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext$FileCollectionConverter.convertInto(DefaultFileCollectionResolveContext.java:164)
at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(DefaultFileCollectionResolveContext.java:109)
at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCollections(DefaultFileCollectionResolveContext.java:92)
at org.gradle.api.internal.file.CompositeFileCollection.getSourceCollections(CompositeFileCollection.java:192)
at org.gradle.api.internal.file.CompositeFileCollection.getFiles(CompositeFileCollection.java:54)
at com.android.build.gradle.BaseExtension.getBootClasspath(BaseExtension.java:904)
at com.android.build.gradle.internal.dsl.BaseAppModuleExtension_Decorated.getBootClasspath(Unknown Source)
at org.jetbrains.kotlin.gradle.plugin.android.AndroidGradleWrapperKt.invoke(AndroidGradleWrapper.kt:35)
at org.jetbrains.kotlin.gradle.plugin.android.AndroidGradleWrapperKt.access$invoke(AndroidGradleWrapper.kt:1)
at org.jetbrains.kotlin.gradle.plugin.android.AndroidGradleWrapper.getRuntimeJars(AndroidGradleWrapper.kt:17)
at org.jetbrains.kotlin.gradle.plugin.Android25ProjectHandler$wireKotlinTasks$1.invoke(Android25ProjectHandler.kt:75)
at org.jetbrains.kotlin.gradle.plugin.Android25ProjectHandler$wireKotlinTasks$1.invoke(Android25ProjectHandler.kt:29)
at org.jetbrains.kotlin.gradle.plugin.GradleUtilsKt$sam$java_util_concurrent_Callable$0.call(gradleUtils.kt)
at org.gradle.util.GUtil.uncheckedCall(GUtil.java:459)
at org.gradle.internal.extensibility.ConventionAwareHelper$2.doGetValue(ConventionAwareHelper.java:77)
at org.gradle.internal.extensibility.ConventionAwareHelper$MappedPropertyImpl.getValue(ConventionAwareHelper.java:121)
at org.gradle.internal.extensibility.ConventionAwareHelper.getConventionValue(ConventionAwareHelper.java:104)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile_Decorated.getClasspath(Unknown Source)
at org.jetbrains.kotlin.gradle.internal.Kapt3KotlinGradleSubplugin.createKaptKotlinTask(Kapt3KotlinGradleSubplugin.kt:402)
at org.jetbrains.kotlin.gradle.internal.Kapt3KotlinGradleSubplugin.apply(Kapt3KotlinGradleSubplugin.kt:240)
at org.jetbrains.kotlin.gradle.internal.Kapt3KotlinGradleSubplugin.apply(Kapt3KotlinGradleSubplugin.kt:90)
at org.jetbrains.kotlin.gradle.plugin.SubpluginEnvironment.addSubpluginOptions(SubpluginEnvironment.kt:86)
at org.jetbrains.kotlin.gradle.plugin.SubpluginEnvironment.addSubpluginOptions(SubpluginEnvironment.kt:51)
at org.jetbrains.kotlin.gradle.plugin.AbstractAndroidProjectHandler.applySubplugins(KotlinPlugin.kt:960)
at org.jetbrains.kotlin.gradle.plugin.AbstractAndroidProjectHandler.access$applySubplugins(KotlinPlugin.kt:693)
at org.jetbrains.kotlin.gradle.plugin.AbstractAndroidProjectHandler$configureTarget$4$1.invoke(KotlinPlugin.kt:797)
at org.jetbrains.kotlin.gradle.plugin.AbstractAndroidProjectHandler$configureTarget$4$1.invoke(KotlinPlugin.kt:693)
at org.jetbrains.kotlin.gradle.plugin.Android25ProjectHandler$sam$org_gradle_api_Action$0.execute(Android25ProjectHandler.kt)
at org.gradle.api.internal.DefaultDomainObjectCollection.all(DefaultDomainObjectCollection.java:158)
at org.jetbrains.kotlin.gradle.plugin.Android25ProjectHandler.forEachVariant(Android25ProjectHandler.kt:36)
at org.jetbrains.kotlin.gradle.plugin.AbstractAndroidProjectHandler$configureTarget$4.invoke(KotlinPlugin.kt:792)
at org.jetbrains.kotlin.gradle.plugin.AbstractAndroidProjectHandler$configureTarget$4.invoke(KotlinPlugin.kt:693)
at org.jetbrains.kotlin.gradle.plugin.KotlinMultiplatformPluginKt$whenEvaluated$1.execute(KotlinMultiplatformPlugin.kt:209)
at org.jetbrains.kotlin.gradle.plugin.KotlinMultiplatformPluginKt$whenEvaluated$1.execute(KotlinMultiplatformPlugin.kt)
at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1$1.run(DefaultListenerBuildOperationDecorator.java:150)
at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.reapply(DefaultUserCodeApplicationContext.java:58)
at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1.run(DefaultListenerBuildOperationDecorator.java:147)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction.execute(DefaultListenerBuildOperationDecorator.java:144)
at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy32.afterEvaluate(Unknown Source)
at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate$1.execute(LifecycleProjectEvaluator.java:190)
at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate$1.execute(LifecycleProjectEvaluator.java:187)
at org.gradle.api.internal.project.DefaultProject.stepEvaluationListener(DefaultProject.java:1424)
at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate.run(LifecycleProjectEvaluator.java:196)
... 113 more
</code></pre>
| 0 | 8,687 |
Working POST Multipart Request with Volley and without HttpEntity
|
<p>This is not really a question, however, I would like to share some of my working code here for your reference when you need.</p>
<p>As we know that <code>HttpEntity</code> is deprecated from API22 and comletely removed since API23. At the moment, we cannot access <a href="http://developer.android.com/reference/org/apache/http/HttpEntity.html?is-external=true" rel="noreferrer">HttpEntity Reference on Android Developer</a> anymore (404). So, the following is my working sample code for <strong>POST Multipart Request with Volley and without HttpEntity</strong>. It's working, tested with <code>Asp.Net Web API</code>. Of course, the code perhaps is just a basic sample that posts two existed drawable files, also is not the best solution for all cases, and not good tuning.</p>
<p><strong>MultipartActivity.java:</strong></p>
<pre><code>package com.example.multipartvolley;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class MultipartActivity extends Activity {
private final Context context = this;
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "apiclient-" + System.currentTimeMillis();
private final String mimeType = "multipart/form-data;boundary=" + boundary;
private byte[] multipartBody;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multipart);
byte[] fileData1 = getFileDataFromDrawable(context, R.drawable.ic_action_android);
byte[] fileData2 = getFileDataFromDrawable(context, R.drawable.ic_action_book);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// the first file
buildPart(dos, fileData1, "ic_action_android.png");
// the second file
buildPart(dos, fileData2, "ic_action_book.png");
// send multipart form data necesssary after file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// pass to multipart body
multipartBody = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
String url = "http://192.168.1.100/api/postfile";
MultipartRequest multipartRequest = new MultipartRequest(url, null, mimeType, multipartBody, new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
Toast.makeText(context, "Upload successfully!", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Upload failed!\r\n" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
VolleySingleton.getInstance(context).addToRequestQueue(multipartRequest);
}
@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_multipart, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void buildPart(DataOutputStream dataOutputStream, byte[] fileData, String fileName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
+ fileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(fileData);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
}
private byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
</code></pre>
<p><strong>MultipartRequest.java:</strong></p>
<pre><code>package com.example.multipartvolley;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import java.util.Map;
class MultipartRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
private final Map<String, String> mHeaders;
private final String mMimeType;
private final byte[] mMultipartBody;
public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = multipartBody;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
@Override
public String getBodyContentType() {
return mMimeType;
}
@Override
public byte[] getBody() throws AuthFailureError {
return mMultipartBody;
}
@Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
@Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>For text part, please refer to @Oscar's answer below.</p>
| 0 | 2,974 |
How to use "next" and "previous" button instead of numbers in list.js pagination?
|
<p>I have a table with many rows. Therefore I decided to use <code>list.js</code> (pagination). However I don't want numbers as pages but a <code>next</code> and <code>previous</code> button which I can style individually (or let bootstrap to the job).</p>
<pre><code><ul class="pager">
<li>
<a class="" href="#">Previous</a>
</li>
<li>
<a class="" href="#">Next</a>
</li>
</ul>
var list = new List('item-table', {
valueNames: ['item'],
page: 10,
plugins: [ListPagination({})]
});
</code></pre>
<p>Is this possible with the library (I haven't found anything useful in the documentation) or do I have to use something else?</p>
<p>I tried the solution from roll. I get an error now saying <code>Cannot read property 'childNodes' of undefined</code>. This error disappers when I add <code><ul class="pagination"></ul></code>. However when trying to access the show method of the list I get an error again: <code>Cannot read property 'show' of undefined</code></p>
<p>New JS-code</p>
<pre><code>$(document).ready(function() {
//var options = {
// valueNames: ['einheit'],
// page: 13,
// plugins: [ListPagination({})]
//}
var list = new List('item-table', {
valueNames: ['item'],
page: 10,
plugins: [ListPagination({})]
});
var i = 1;
$('.next').on('click', function () {
console.log("next");
i++;
list.show(i, 10);
});
$('.prev').on('click', function () {
console.log("prev");
i--;
list.show(i, 10);
});
});
</code></pre>
<p>HTML Code</p>
<pre><code><div id="item-table">
<table class="table">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody class="list">
<tr class="item">
</tr>
<!-- loads of items here -->
</tbody>
</table>
<ul class="pager">
<li class="next">
<a href="#">Next</a>
</li>
<li class="prev">
<a href="#">Previous</a>
</li>
</ul>
</div>
</code></pre>
| 0 | 1,481 |
How to use UdpClient.BeginReceive in a loop
|
<p>I want to do this</p>
<pre><code>for (int i = 0; i < 100; i++ )
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
}
</code></pre>
<p>But instead of using <code>UdpClient.Receive</code>, I have to use <code>UdpClient.BeginReceive</code>. The problem is, how do I do that? There aren't a lot of samples using <code>BeginReceive</code>, and the MSDN example is not helping at all. Should I use <code>BeginReceive</code>, or just create it under a separate thread?</p>
<p>I consistently get <code>ObjectDisposedException</code> exception. I only get the first data sent. The next data will throw exception.</p>
<pre><code>public class UdpReceiver
{
private UdpClient _client;
public System.Net.Sockets.UdpClient Client
{
get { return _client; }
set { _client = value; }
}
private IPEndPoint _endPoint;
public System.Net.IPEndPoint EndPoint
{
get { return _endPoint; }
set { _endPoint = value; }
}
private int _packetCount;
public int PacketCount
{
get { return _packetCount; }
set { _packetCount = value; }
}
private string _buffers;
public string Buffers
{
get { return _buffers; }
set { _buffers = value; }
}
private Int32 _counter;
public System.Int32 Counter
{
get { return _counter; }
set { _counter = value; }
}
private Int32 _maxTransmission;
public System.Int32 MaxTransmission
{
get { return _maxTransmission; }
set { _maxTransmission = value; }
}
public UdpReceiver(UdpClient udpClient, IPEndPoint ipEndPoint, string buffers, Int32 counter, Int32 maxTransmission)
{
_client = udpClient;
_endPoint = ipEndPoint;
_buffers = buffers;
_counter = counter;
_maxTransmission = maxTransmission;
}
public void StartReceive()
{
_packetCount = 0;
_client.BeginReceive(new AsyncCallback(Callback), null);
}
private void Callback(IAsyncResult result)
{
try
{
byte[] buffer = _client.EndReceive(result, ref _endPoint);
// Process buffer
MainWindow.Log(Encoding.ASCII.GetString(buffer));
_packetCount += 1;
if (_packetCount < _maxTransmission)
{
_client.BeginReceive(new AsyncCallback(Callback), null);
}
}
catch (ObjectDisposedException ex)
{
MainWindow.Log(ex.ToString());
}
catch (SocketException ex)
{
MainWindow.Log(ex.ToString());
}
catch (System.Exception ex)
{
MainWindow.Log(ex.ToString());
}
}
}
</code></pre>
<p>What gives?</p>
<p>By the way, the general idea is:</p>
<ol>
<li>Create tcpclient manager.</li>
<li>Start sending/receiving data using udpclient.</li>
<li>When all data has been sent, tcpclient manager will signal receiver that all data has been sent, and udpclient connection should be closed.</li>
</ol>
| 0 | 1,312 |
c++ "error: invalid conversion from ‘const char*’ to ‘char*’"
|
<p>I'm fairly new to C++ programming and I've been getting an error that I can't seem to figure out. I've tried it many different ways and just get variations of the same error. here is the error and my code:</p>
<pre><code> account.cxx: In member function ‘char* account::get_name() const’:
account.cxx:26: error: invalid conversion from ‘const char*’ to ‘char*’
//File: account.h
68 class account
69 {
70 public:
71 typedef char* string;
72 static const size_t MAX_NAME_SIZE = 15;
73 // CONSTRUCTOR
74 account (char* i_name, size_t i_acnum, size_t i_hsize);
75 account (const account& ac);
76 // DESTRUCTOR
77 ~account ( );
78 // MODIFICATION MEMBER FUNCTIONS
79 void set_name(char* new_name);
80 void set_account_number(size_t new_acnum);
81 void set_balance(double new_balance);
82 void add_history(char* new_history);
83 // CONSTANT MEMBER FUNCTIONS
84 char* get_name ( ) const;
85 size_t get_account_number ( ) const;
86 double get_balance( ) const;
87 size_t get_max_history_size( ) const;
88 size_t get_current_history_size ( ) const;
89 string* get_history( ) const;
90 friend ostream& operator <<(ostream& outs, const account& target);
91 private:
92 char name[MAX_NAME_SIZE+1]; //name of the account holder
93 size_t ac_number; //account number
94 double balance; //current account balance
95 string *history; //Array to store history of transactions
96 size_t history_size; //Maximum size of transaction history
97 size_t history_count; //Current size of transaction history
98 };
1 // File: account.cxx
2 // Author: Mike Travis
3 // Last Modified: Feb, 26, 2012
4 // Description: implementation of Account class as prescribed by the file account.h
5
6 #include <stdio.h>
7 #include <iostream>
8 #include "account.h"
9
10 using namespace std;
11 //Constructor
12
13 account::account(char* i_name, size_t i_acnum, size_t i_hsize){
14 string *d_history = NULL;
15 d_history = new string[i_hsize];
16
17 for(int i = 0; i<MAX_NAME_SIZE +1; i++){
18 name[i] = i_name[i];
19 }
20 ac_number = i_acnum;
21 history_size = i_hsize;
22 history_count = 0;
23 }
24
25 char* account::get_name() const {
26 return &name;
27 }
</code></pre>
<p>I haven't yet written the rest of the implementation file since I can't get around this error. </p>
<p>In line 26 of account.cxx I have tried several variations with no success.</p>
| 0 | 1,151 |
C++ 11 threads with clang
|
<p>I wanted to learn use of C++11 threads to speed up compilation of my language (yes I'm building a compiler :x). The first sample I tried threw several errors with clang (3.3 SVN). It compiled fine under GCC (4.6.3).</p>
<p>I downloaded clang and libc++ from llvm.org's SVN. clang was compiled with GCC (4.6.3) and libc++ was compiled with clang. Both makefiles were generated with CMake.</p>
<p>For clang I followed this guide: <a href="http://llvm.org/docs/GettingStarted.html#checkout" rel="nofollow">http://llvm.org/docs/GettingStarted.html#checkout</a></p>
<p>For libc++ I followed this guide: <a href="http://libcxx.llvm.org/" rel="nofollow">http://libcxx.llvm.org/</a></p>
<p>The piece of code I want to compile (<code>foobar.cpp</code>):</p>
<pre><code>#include <iostream>
#include <thread>
using namespace std;
int main(void) {
thread t1([](void)->void {
cout << "foobar" << endl;
});
}
</code></pre>
<p>It compiles fine with <code>clang --std=c++0x -stdlib=libc++ -lpthread foobar.cpp</code> but I get a lot of linker errors:</p>
<pre><code>/tmp/foobar-59W5DR.o: In function `main':
foobar.cpp:(.text+0x21): undefined reference to `std::__1::thread::~thread()'
/tmp/foobar-59W5DR.o: In function `_ZNSt3__16threadC2IZ4mainE3$_0JEvEEOT_DpOT0_':
foobar.cpp:(.text+0x5c): undefined reference to `operator new(unsigned long)'
foobar.cpp:(.text+0x186): undefined reference to `operator delete(void*)'
foobar.cpp:(.text+0x19b): undefined reference to `std::__1::__throw_system_error(int, char const*)'
/tmp/foobar-59W5DR.o: In function `_ZNSt3__114__thread_proxyINS_5tupleIJZ4mainE3$_0EEEEEPvS4_':
foobar.cpp:(.text+0x200): undefined reference to `std::__1::__thread_local_data()'
foobar.cpp:(.text+0x211): undefined reference to `operator new(unsigned long)'
foobar.cpp:(.text+0x23b): undefined reference to `std::__1::__thread_struct::__thread_struct()'
foobar.cpp:(.text+0x31b): undefined reference to `operator delete(void*)'
/tmp/foobar-59W5DR.o: In function `_ZNSt3__110unique_ptrINS_5tupleIJZ4mainE3$_0EEENS_14default_deleteIS3_EEED2Ev':
foobar.cpp:(.text+0x3dd): undefined reference to `operator delete(void*)'
/tmp/foobar-59W5DR.o: In function `main::$_0::operator()() const':
foobar.cpp:(.text+0x3fc): undefined reference to `std::__1::cout'
/tmp/foobar-59W5DR.o: In function `_ZNSt3__110unique_ptrINS_5tupleIJZ4mainE3$_0EEENS_14default_deleteIS3_EEEC2EPS3_':
foobar.cpp:(.text+0x4e9): undefined reference to `std::terminate()'
/tmp/foobar-59W5DR.o: In function `std::__1::__thread_specific_ptr<std::__1::__thread_struct>::reset(std::__1::__thread_struct*)':
foobar.cpp:(.text._ZNSt3__121__thread_specific_ptrINS_15__thread_structEE5resetEPS1_[_ZNSt3__121__thread_specific_ptrINS_15__thread_structEE5resetEPS1_]+0x57): undefined reference to `std::__1::__thread_struct::~__thread_struct()'
foobar.cpp:(.text._ZNSt3__121__thread_specific_ptrINS_15__thread_structEE5resetEPS1_[_ZNSt3__121__thread_specific_ptrINS_15__thread_structEE5resetEPS1_]+0x60): undefined reference to `operator delete(void*)'
/tmp/foobar-59W5DR.o: In function `std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::operator<< <std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*)':
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x28): undefined reference to `std::__1::basic_ostream<char, std::__1::char_traits<char> >::sentry::sentry(std::__1::basic_ostream<char, std::__1::char_traits<char> >&)'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x1ec): undefined reference to `std::__1::ios_base::getloc() const'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x1fe): undefined reference to `std::__1::ctype<char>::id'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x206): undefined reference to `std::__1::locale::use_facet(std::__1::locale::id&) const'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x272): undefined reference to `std::__1::locale::~locale()'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x294): undefined reference to `std::__1::locale::~locale()'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x378): undefined reference to `std::__1::ios_base::clear(unsigned int)'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x3d0): undefined reference to `std::__1::basic_ostream<char, std::__1::char_traits<char> >::sentry::~sentry()'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x3dc): undefined reference to `__cxa_begin_catch'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x3f9): undefined reference to `std::__1::ios_base::__set_badbit_and_consider_rethrow()'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x403): undefined reference to `__cxa_end_catch'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x424): undefined reference to `std::__1::basic_ostream<char, std::__1::char_traits<char> >::sentry::~sentry()'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x43d): undefined reference to `__cxa_end_catch'
foobar.cpp:(.text._ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc[_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc]+0x466): undefined reference to `std::terminate()'
/tmp/foobar-59W5DR.o: In function `std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&)':
foobar.cpp:(.text._ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_[_ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_]+0x38): undefined reference to `std::__1::ios_base::getloc() const'
foobar.cpp:(.text._ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_[_ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_]+0x49): undefined reference to `std::__1::ctype<char>::id'
foobar.cpp:(.text._ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_[_ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_]+0x55): undefined reference to `std::__1::locale::use_facet(std::__1::locale::id&) const'
foobar.cpp:(.text._ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_[_ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_]+0xac): undefined reference to `std::__1::locale::~locale()'
foobar.cpp:(.text._ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_[_ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_]+0xbe): undefined reference to `std::__1::locale::~locale()'
foobar.cpp:(.text._ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_[_ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_]+0xcd): undefined reference to `std::__1::basic_ostream<char, std::__1::char_traits<char> >::put(char)'
foobar.cpp:(.text._ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_[_ZNSt3__14endlIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_]+0xdd): undefined reference to `std::__1::basic_ostream<char, std::__1::char_traits<char> >::flush()'
/tmp/foobar-59W5DR.o: In function `std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> > std::__1::__pad_and_output<char, std::__1::char_traits<char> >(std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> >, char const*, char const*, char const*, std::__1::ios_base&, char)':
foobar.cpp:(.text._ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_[_ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_]+0x215): undefined reference to `std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::__init(unsigned long, char)'
foobar.cpp:(.text._ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_[_ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_]+0x389): undefined reference to `std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::~basic_string()'
foobar.cpp:(.text._ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_[_ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_]+0x3a4): undefined reference to `std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::~basic_string()'
/tmp/foobar-59W5DR.o:(.eh_frame+0x47): undefined reference to `__gxx_personality_v0'
clang-3: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre>
<p>Here are the standard search directories under the two standard libraries.
As result of 'clang -Wp,-v -x c++ - -fsyntax-only' I got this:</p>
<p>I tried <code>clang --std=c++11 -stdlib=libc++ -llibc++ -lpthread -o foobar foobar.cpp</code> but the linker failed again, it does not find libc++. Do I fail on linking to libc++ or is it something more difficult?</p>
| 0 | 4,758 |
Saving blob image in laravel's controller
|
<p>In my Laravel 5/vuejs 2.6 I upload an image with the vue-upload-component and am sending a requested image blob
I try to save it with the controller code like :</p>
<pre><code> if ( !empty($requestData['avatar_filename']) and !empty($requestData['avatar_blob']) ) {
$dest_image = 'public/' . Customer::getUserAvatarPath($newCustomer->id, $requestData['avatar_filename']);
$requestData['avatar_blob']= str_replace('blob:','',$requestData['avatar_blob']);
Storage::disk('local')->put($dest_image, file_get_contents($requestData['avatar_blob']));
ImageOptimizer::optimize( storage_path().'/app/'.$dest_image, null );
} // if ( !empty($page_content_image) ) {
</code></pre>
<p>As result, I have an image uploaded, but it is not readable.
The source file has 5 Kib, the resulting file has 5.8 Kib and in the browser's console I see the blobs path as</p>
<pre><code>avatar_blob: "blob:http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af"
</code></pre>
<p>Have do I convert my blob to save it correctly?</p>
<p><strong>MODIFIED</strong> :
a bit more detailed :
In vue file I send request using axios :</p>
<pre><code> let customerRegisterArray =
{
username: this.previewCustomerRegister.username,
email: this.previewCustomerRegister.email,
first_name: this.previewCustomerRegister.first_name,
last_name: this.previewCustomerRegister.last_name,
account_type: this.previewCustomerRegister.account_type,
phone: this.previewCustomerRegister.phone,
website: this.previewCustomerRegister.website,
notes: this.previewCustomerRegister.notes,
avatar_filename: this.previewCustomerRegister.avatarFile.name,
avatar_blob: this.previewCustomerRegister.avatarFile.blob,
};
console.log("customerRegisterArray::")
console.log(customerRegisterArray)
axios({
method: ('post'),
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
}).then((response) => {
this.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::"+var_dump() )
}).catch((error) => {
});
</code></pre>
<p>and this.previewCustomerRegister.avatarFile.blob has value: "blob:<a href="http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af" rel="nofollow noreferrer">http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af</a>"
where <a href="http://local-hostels2.com" rel="nofollow noreferrer">http://local-hostels2.com</a> is my hosting...
I set this value to preview image defined as :</p>
<pre><code> <img
class="img-preview-wrapper"
:src="previewCustomerRegister.avatarFile.blob"
alt="Your avatar"
v-show="previewCustomerRegister.avatarFile.blob"
width="256"
height="auto"
id="preview_avatar_file"
>
</code></pre>
<p>and when previewCustomerRegister.avatarFile.blob is assigned with uploaded file I see it in preview image.
I show control with saving function in first topic but when I tried to opened my generated file with kate, I found that it
has content of my container file resources/views/index.blade.php...</p>
<p>What I did wrong and which is the valid way ?</p>
<p><strong>MODIFIED BLOCK #2 :</strong>
I added 'Content-Type' in request </p>
<pre><code>axios({
method: ('post'),
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
headers: {
'Content-Type': 'multipart/form-data'
}
</code></pre>
<p>but with it I got validation errors in my control, as I define control action with request:</p>
<pre><code>public function store(CustomerRegisterRequest $request)
{
</code></pre>
<p>and in app/Http/Requests/CustomerRegisterRequest.php :</p>
<pre><code><?php
namespace App\Http\Requests;
use App\Http\Traits\funcsTrait;
use Illuminate\Foundation\Http\FormRequest;
use App\Customer;
class CustomerRegisterRequest extends FormRequest
{
use funcsTrait;
public function authorize()
{
return true;
}
public function rules()
{
$request= Request();
$requestData= $request->all();
$this->debToFile(print_r( $requestData,true),' getCustomerValidationRulesArray $requestData::');
/* My debugging method to write data to text file
and with Content-Type defined above I see that $requestData is always empty
and I got validations errors
*/
// Validations rules
$customerValidationRulesArray= Customer::getCustomerValidationRulesArray( $request->get('id'), ['status'] );
return $customerValidationRulesArray;
}
}
</code></pre>
<p>In routes/api.php defined :</p>
<pre><code>Route::post('customer_register_store', 'CustomerRegisterController@store');
</code></pre>
<p>In the console of my bhrowser I see : <a href="https://imgur.com/a/0vsPIsa" rel="nofollow noreferrer">https://imgur.com/a/0vsPIsa</a>, <a href="https://imgur.com/a/wJEbBnP" rel="nofollow noreferrer">https://imgur.com/a/wJEbBnP</a></p>
<p>I suppose that something is wrong in axios header ? without 'Content-Type' defined my validation rules work ok...</p>
<p><strong>MODIFIED BLOCK #3</strong></p>
<p>I managed to make fetch of blob with metod like :</p>
<pre><code> var self = this;
fetch(this.previewCustomerRegister.avatarFile.blob) .then(function(response) {
console.log("fetch response::")
console.log( response )
if (response.ok) {
return response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
// myImage.src = objectURL;
console.log("objectURL::")
console.log( objectURL )
console.log("self::")
console.log( self )
let customerRegisterArray =
{
username: self.previewCustomerRegister.username,
email: self.previewCustomerRegister.email,
first_name: self.previewCustomerRegister.first_name,
last_name: self.previewCustomerRegister.last_name,
account_type: self.previewCustomerRegister.account_type,
phone: self.previewCustomerRegister.phone,
website: self.previewCustomerRegister.website,
notes: self.previewCustomerRegister.notes,
avatar_filename: self.previewCustomerRegister.avatarFile.name,
avatar: objectURL,
};
console.log("customerRegisterArray::")
console.log(customerRegisterArray)
axios({
method: 'POST',
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
// headers: {
// 'Content-Type': 'multipart/form-data' // multipart/form-data - as we need to upload with image
// }
}).then((response) => {
self.is_page_updating = false
self.message = ''
self.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::")
}).catch((error) => {
self.$setLaravelValidationErrorsFromResponse(error.response.data);
self.is_page_updating = false
self.showRunTimeError(error, this);
self.showPopupMessage("Customer Register", 'Error adding customer ! Check Details fields !', 'warn');
// window.grecaptcha.reset()
self.is_recaptcha_verified = false;
self.$refs.customer_register_wizard.changeTab(3,0)
});
});
} else {
return response.json().then(function(jsonError) {
// ...
});
}
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
</code></pre>
<p>In objectURL and self I see proper values : <a href="https://imgur.com/a/4YvhbFz" rel="nofollow noreferrer">https://imgur.com/a/4YvhbFz</a></p>
<p>1) But checking data on server in laravel's control I see the same values I had at start of my attemps to upload image:</p>
<p>[avatar_filename] => patlongred.jpg
[avatar] => blob:<a href="http://local-hostels2.com/d9bf4b66-42b9-4990-9325-a72dc8c3a392" rel="nofollow noreferrer">http://local-hostels2.com/d9bf4b66-42b9-4990-9325-a72dc8c3a392</a></p>
<p>Have To manipulate with fetched bnlob in some other way ?</p>
<p>2) If I set :</p>
<pre><code> headers: {
'Content-Type': 'multipart/form-data'
}
</code></pre>
<p>I got validation errors that my data were not correctly requested...</p>
<p>?</p>
| 0 | 4,717 |
How to display data using openlayers with OpenStreetMap in geodjango?
|
<p>I've got geodjango running using <a href="http://openlayers.org/" rel="noreferrer">openlayers</a> and <a href="http://www.openstreetmap.org/" rel="noreferrer">OpenStreetMaps</a> with the admin app.</p>
<p>Now I want to write some views to display the data. Basically, I just want to add a list of points (seen in the admin) to the map.</p>
<p>Geodjango appears to use a <em>special</em> <a href="http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/contrib/gis/templates/gis/admin/openlayers.js" rel="noreferrer">openlayers.js</a> file to do it's magic in the admin. Is there a good way to interface with this?</p>
<p>How can I write a view/template to display the geodjango data on a open street map window, as is seen in the admin?</p>
<p>At the moment, I'm digging into the <a href="http://openlayers.org/" rel="noreferrer">openlayers.js</a> file and api looking for an 'easy' solution. (I don't have js experience so this is taking some time.) </p>
<p>The current way I can see to do this is add the following as a template, and use django to add the code needed to display the points. (Based on the example <a href="http://openlayers.org/dev/examples/vector-features.html" rel="noreferrer">here</a>)</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Draw Feature Example</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init(){
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(layer);
/*
* Layer style
*/
// we want opaque external graphics and non-opaque internal graphics
var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
layer_style.fillOpacity = 0.2;
layer_style.graphicOpacity = 1;
/*
* Blue style
*/
var style_blue = OpenLayers.Util.extend({}, layer_style);
style_blue.strokeColor = "blue";
style_blue.fillColor = "blue";
style_blue.graphicName = "star";
style_blue.pointRadius = 10;
style_blue.strokeWidth = 3;
style_blue.rotation = 45;
style_blue.strokeLinecap = "butt";
var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style: layer_style});
// create a point feature
var point = new OpenLayers.Geometry.Point(-111.04, 45.68);
var pointFeature = new OpenLayers.Feature.Vector(point,null,style_blue);
// Add additional points/features here via django
map.addLayer(vectorLayer);
map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5);
vectorLayer.addFeatures([pointFeature]);
}
</script>
</head>
<body onload="init()">
<div id="map" class="smallmap"></div>
</body>
</html>
</code></pre>
<p>Is this how it's done, or is there a better way?</p>
| 0 | 1,576 |
laravel passing errors to views through controllers
|
<p>I am trying to validate in an action within my controller. once it fails, I send the messages resulting from the validator to the other function in the same controller to pass it to the view. The only problem is I don't see anything displaying in the view and the url changes to a weird format once I click submit and errors occurs. </p>
<p>Controller:</p>
<pre><code><?php
class MembersController extends BaseController {
protected $layout = 'layouts.master';
public function loadRegisterView($input = null)
{
if($input == null)
return View::make('members.register');
else
return View::make('members.register', $input);
}
public function loadLoginView()
{
return View::make('members.login');
}
public function register()
{
$rules = array(
'first_name' => 'Required|Min:3|Max:88|Alpha',
'last_name' => 'Required|Min:3|Max:88|Alpha',
'password' => 'Required|Min:3|Max:88|Alpha|Confirmed',
'email' => 'Required|email|unique:users',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
$messages = $validator->messages();
return Redirect::action('MembersController@loadRegisterView', $messages);
}else{
return "Thank you!";
}
}
}
</code></pre>
<p>Routes:</p>
<pre><code>Route::get('login', array('as' => 'login', 'uses' => 'MembersController@loadLoginView'));
Route::get('signup', array('as' => 'signup', 'uses' => 'MembersController@loadRegisterView'));
Route::get('/', 'MainController@index');
Route::post('processRegistration', array('as' => 'processRegistration', 'uses' => 'MembersController@register'));
</code></pre>
<p>in the View:</p>
<pre><code>@if ( $errors->count() > 0 )
<p>The following errors have occurred:</p>
<ul>
@foreach( $errors->all() as $message )
<li>{{ $message }}</li>
@endforeach
</ul>
@endif
</code></pre>
<p>and the URL looks like: </p>
<pre><code>http://localhost:8888/store/index.php/signup?%00%2A%00messages%5Bfirst_name%5D%5B0%5D=The+first+name+field+is+required.&%00%2A%00messages%5Blast_name%5D%5B0%5D=The+last+name+field+is+required.&%00%2A%00messages%5Bpassword%5D%5B0%5D=The+password+field+is+required.&%00%2A%00messages%5Bemail%5D%5B0%5D=The+email+field+is+required.&%00%2A%00format=%3Amessage
</code></pre>
<p>Thanks in advance </p>
| 0 | 1,118 |
Warning: Mapping new ns to old ns and emulator stopping abruptly
|
<p>After upgrading to Arctic Fox , I am getting the following errors, even though the emulator is running but sometimes stopping abruptly.
What is this error ?
How can I get rid of this ?</p>
<p>I am using the following as copied from <code>cmd</code> :</p>
<pre><code> > C:\Users\Debasis>flutter doctor Doctor summary (to see all details,
> run flutter doctor -v): [√] Flutter (Channel stable, 2.2.3, on
> Microsoft Windows [Version 10.0.19042.1165], locale en-IN) [√] Android
> toolchain - develop for Android devices (Android SDK version 31.0.0)
> [√] Chrome - develop for the web [√] Android Studio [√] Connected
> device (2 available)
• No issues found!
</code></pre>
<p>The Error :</p>
<blockquote>
<p>Launching lib\main.dart on sdk gphone x86 in debug mode... Running
Gradle task 'assembleDebug'... Warning: Mapping new ns
<a href="http://schemas.android.com/repository/android/common/02" rel="noreferrer">http://schemas.android.com/repository/android/common/02</a> to old ns
<a href="http://schemas.android.com/repository/android/common/01" rel="noreferrer">http://schemas.android.com/repository/android/common/01</a> Warning:
Mapping new ns
<a href="http://schemas.android.com/repository/android/generic/02" rel="noreferrer">http://schemas.android.com/repository/android/generic/02</a> to old ns
<a href="http://schemas.android.com/repository/android/generic/01" rel="noreferrer">http://schemas.android.com/repository/android/generic/01</a> Warning:
Mapping new ns <a href="http://schemas.android.com/sdk/android/repo/addon2/02" rel="noreferrer">http://schemas.android.com/sdk/android/repo/addon2/02</a>
to old ns <a href="http://schemas.android.com/sdk/android/repo/addon2/01" rel="noreferrer">http://schemas.android.com/sdk/android/repo/addon2/01</a>
Warning: Mapping new ns
<a href="http://schemas.android.com/sdk/android/repo/repository2/02" rel="noreferrer">http://schemas.android.com/sdk/android/repo/repository2/02</a> to old ns
<a href="http://schemas.android.com/sdk/android/repo/repository2/01" rel="noreferrer">http://schemas.android.com/sdk/android/repo/repository2/01</a> Warning:
Mapping new ns <a href="http://schemas.android.com/sdk/android/repo/sys-img2/02" rel="noreferrer">http://schemas.android.com/sdk/android/repo/sys-img2/02</a>
to old ns <a href="http://schemas.android.com/sdk/android/repo/sys-img2/01" rel="noreferrer">http://schemas.android.com/sdk/android/repo/sys-img2/01</a> √
Built build\app\outputs\flutter-apk\app-debug.apk. Installing
build\app\outputs\flutter-apk\app.apk... Debug service listening on
ws://127.0.0.1:57467/XzCZTOeqyQs=/ws Syncing files to device sdk
gphone x86...</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/ALHPM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ALHPM.png" alt="The Issue" /></a></p>
<p><a href="https://i.stack.imgur.com/l49lG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/l49lG.png" alt="SDK Platforms" /></a></p>
<p><a href="https://i.stack.imgur.com/Ghbst.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ghbst.png" alt="SDK Tools" /></a></p>
| 0 | 1,222 |
Getting Bootstrap's modal content from another page
|
<p>I have an anchor in a page called <code>menu.html</code> and I'm having trouble getting a Bootstrap modal to display data from another page called <code>Lab6.html</code>.</p>
<p><strong>menu.html</strong></p>
<pre><code><div class="collapse navbar-collapse navbar-exl-collapse">
<ul class="nav navbar-nav" id="menu">
<li><a href="/emplookup.html">Lookup</a></li>
<li><a href="/modalexample.html">Modals</a></li>
<li><a href="/Lab6.html#theModal" data-toggle="modal">Lab 6</a></li><!-- this one -->
</ul>
</div>
</code></pre>
<p><strong>Lab6.html</strong></p>
<pre><code><div class="modal fade text-center" id="theModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">X</button>
<h1>Lab 6</h1>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading text-center">
Employee Information
</div>
<div class="panel-body">
<div class="row">
<div class="text-right col-xs-2">Title:</div>
<div class="text-left col-xs-3" id="title"></div>
<div class="text-right col-xs-2">First:</div>
<div class="text-left col-xs-3" id="firstname"></div>
</div>
<div class="row">
<div class="text-right col-xs-2">Phone#</div>
<div class="text-left col-xs-3" id="phone"></div>
<div class="text-right col-xs-2">Email</div>
<div class="text-left col-xs-3" id="email"></div>
</div>
<div class="row">
<div class="text-right col-xs-2">Dept:</div>
<div class="text-left col-xs-3" id="departmentname"></div>
<div class="text-left col-xs-2">Surname:</div>
<div class="text-left col-xs-4">
<input type="text" placeholder="enter last name" id="TextBoxLastName" class="form-control" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="panel-footer">
<input type="button" value="Find Employee" id="empbutton" />
<div class="col-xs-10" id="lblstatus"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</code></pre>
<p>Am I doing anything wrong?</p>
| 0 | 1,636 |
How To Reload A iframe Using jQuery
|
<p>I've created a basic browser within a browser window using an iframe:</p>
<p>The purpose is to allow mouse-over styling of elements using jquery ie/ highlight all links red etc... change font etc..</p>
<p>I've created two files:</p>
<p><strong>browser.php</strong></p>
<pre><code><html>
<head>
<title></title>
<style>
#netframe {
float:right;
height: 100%;
width: 80%;
}
#sidebar {
float:left;
height: 100%;
width: 20%;
}
</style>
</head>
<body>
<div id="container">
<div id="sidebar">
Enter A URL:
<input type="text" name="url" id="url">
<input type="button" value="load" id="load">
<br><br>
</div>
<div id="netframe">
<iframe height="100%" width="100%" class="netframe" src="pullsite.php" id="main_frame"></iframe>
</div>
</div>
</body>
</html>
</code></pre>
<p>And <strong>pullsite.php</strong></p>
<pre><code><html>
<head>
<title></title>
<link href="css/reset.css" rel="stylesheet" type="text/css">
<style>
.highlight {
outline-color: -moz-use-text-color !important;
outline-style: dashed !important;
outline-width: 2px !important;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="contents">
<?php echo file_get_contents('http://www.google.com/webhp?hl=en&tab=iw'); ?>
</div>
<script>
$("#contents").contents().find("a").addClass("highlight");
</script>
</body>
</html>
</code></pre>
<p>Can someone please help with the jquery code I could use allow a user to enter a new url in the input field and reload the iframe.</p>
<p>Thanks!!!</p>
| 0 | 1,124 |
BeanCreationException: Error creating bean with name 'configurationPropertiesBeans' defined in class path resource
|
<p>I'm writing a small program for circuit breaker, When running the application it throws exceptions.<br> springboot versin 2.5.4, Hystrix Version using <strong>2.2.6</strong><br>
<strong>BeanCreationException: Error creating bean with name 'configurationPropertiesBeans' defined in class path resource [org/springframework/cloud/autoconfigure/ConfigurationPropertiesRebinderAutoConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.context.properties.ConfigurationPropertiesBeans] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@659e0bfd]</strong></p>
<h2><strong>Pom.xml</strong></h2>
<pre><code><parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.ramgovindhare</groupId>
<artifactId>cricuitbreakerhystrix</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>CricuitBreakerHystrix</name>
<description>firstMicroserviceProject</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.8.RELEASE</version> <--- **See this**
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</code></pre>
<h2><strong>CricuitBreakerHystrixApplication.java</strong></h2>
<pre><code>@SpringBootApplication
@EnableCircuitBreaker
public class CricuitBreakerHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(CricuitBreakerHystrixApplication.class, args);
}
}
</code></pre>
<h2><strong>Controller class</strong></h2>
<pre><code>@RestController
public class CricutiBreakerHystrixController {
@GetMapping("/process")
@HystrixCommand(fallbackMethod = "doWork")
public String doProcess() {
String response = "This msg come for processes";
int i = 10 / 0;
return response;
}
public String doWork() {
return "This msg coming from doWork()...!!";
}
}
</code></pre>
| 0 | 1,601 |
C# DynamicObject dynamic properties
|
<p>Assuming I cannot use an ExpandoObject and have to roll my own like so :-</p>
<pre><code>class MyObject : DynamicObject {
dictionary<string, object> _properties = dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result) {
string name = binder.Name.ToLower();
return _properties.TryGetValue(name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value) {
_properties[binder.Name.ToLower()] = value;
return true;
}
}
</code></pre>
<p>and further down the class hierarchy I have</p>
<pre><code>class MyNewObject : MyObject {
public string Name {
get {
// do some funky stuff
}
set {
// ditto
}
}
}
</code></pre>
<p>which is quite nice as now I can do the follow :-</p>
<pre><code>dynamic o = MyNewObject();
o.Age = 87; // dynamic property, handled by TrySetMember in MyObject
o.Name = "Sam"; // non dynamic property, handled by the setter defined in MyNewObject
</code></pre>
<p>But the above assumes I know the properties (e.g. Age, Name) at compile time.</p>
<p>Suppose I don't know what they will be until run time.</p>
<p>How can I change the above to support properties I will only know at run time? </p>
<p>Basically I think I am asking is how I can call the code that calls TrySetMember directly so that it will either create a new property or use a getter/setter if one has been defined.</p>
<p><strong>Final Solution as follows :-</strong></p>
<pre><code>using System.Dynamic;
using Microsoft.CSharp.RuntimeBinder;
using System.Runtime.CompilerServices;
class MyObject : DynamicObject {
Dictionary<string, object> _properties = new Dictionary<string, object>();
public object GetMember(string propName) {
var binder = Binder.GetMember(CSharpBinderFlags.None,
propName, this.GetType(),
new List<CSharpArgumentInfo>{
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
var callsite = CallSite<Func<CallSite, object, object>>.Create(binder);
return callsite.Target(callsite, this);
}
public void SetMember(string propName, object val) {
var binder = Binder.SetMember(CSharpBinderFlags.None,
propName, this.GetType(),
new List<CSharpArgumentInfo>{
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
var callsite = CallSite<Func<CallSite, object, object, object>>.Create(binder);
callsite.Target(callsite, this, val);
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
string name = binder.Name.ToLower();
return _properties.TryGetValue(name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value) {
_properties[binder.Name.ToLower()] = value;
return true;
}
}
</code></pre>
| 0 | 1,216 |
How can I have a popup Google Map appear when the user hovers over an address?
|
<p>I want to set up my site so that whenever a user hovers over an address, a small google map of that address pops up. I've been reading through the Google Maps API documentation, but I'm having a hard time finding a simple way to implement this. It seems I have to use what google calls "geocoding" to find the latitude and longitude based on the address... This is the test page I have so far:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var geocoder;
var map;
function codeAddress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 20,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body>
<div onMouseOver="codeAddress('1405 Harrison Street, Oakland, CA')">
1405 Harrison Street, Oakland, CA
</div>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
</code></pre>
<p>This, however, causes the map to show up in the map_canvas div... What I really want is to make the map show up as a little popup, sort of like a tooltip. How can I accomplish this? Also, how can I set it up so that when the user mouses-out, the map disappears?</p>
<p>I'm using html and javascript so far, and my website is in coldfusion.</p>
| 0 | 1,080 |
Syntax error, unexpected T_SL
|
<p>I'm fairly new to php and I'm using a script that creates a function called the "mime_mailer" which essentially allows me to use PHP to send emails that are able to be designed with CSS instead of being merely plain text. </p>
<p>Yet, in my registration script, I try to write some code that sends a CSS email, but I get an error saying that there's a syntax error. Could someone please fill me in on this?</p>
<pre><code> $subject = "Your Red-line Account";
$css = "body{ color: #090127; background-color: #f0f0f0; }";
$to = $usercheck;
//Message
$message =<<<END
<html>
<head>
<title>
Red-line
</title>
</head>
<body>
<p>
Hi $first_name,
</p>
<p>
Your Red-line account is almost complete. To finish, go to <a href='www.thered-line.com'>The Red-line</a> and enter your eight digit confirmation code.
</p>
<p>
Your confirmation code is: <b>$code</b>
</p>
<p>
Sincerely,
</p> <br />
<p>
The Red-line Operator
</p>
</body>
</html>
END;
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= "From: The Red-line <messages@theredline.com>\r\n";
$headers .= "To: $first_name $last_name <$usercheck>\r\n";
// Mail it
require_once("function_mime_mailer.php");
mime_mailer($to, $subject, $message, $headers, NULL, $css);
}
</code></pre>
<p>Here is the code for the "function_mime_mailer.php" file.</p>
<pre><code> if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404(); // stop http access to this file
function mime_mailer($to, $subject, $message, $headers = NULL, $attachments = NULL, $css = NULL)
{
if(!preg_match('/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a- z]{2,6})$/', $to)) return FALSE;
if(preg_match('/<(html|head|body|div|a|h|p|table|br|img|b|hr|ol|ul|span|pre|i|form)[^>]*[^>]*>/i', $message)) $html = TRUE;
if(stristr($message, '<body')) $message = stristr($message, '<body');
$message = delete_local_links($message);
if(empty($headers)){
$headers = "MIME-Version: 1.0\n";
}else{
$headers.= "\nMIME-Version: 1.0\n";
}
if(empty($html)){
$result = plain_text($message);
}elseif(isset($html) and $html == TRUE){
if(!isset($css)) $css = NULL;
if(preg_match('/<img[^>]+>/i', $message)){
$result = multipart_related($message, $css);
}else{
$result = multipart_alternative($message, $css);
}
}
$result['message'] = delete_non_cid_images($result['message']);
if(!empty($attachments)){
$parts = attachments($attachments);
array_unshift($parts, implode('', $result));
$result = multipart_mixed($parts);
}
$headers = $headers.$result['headers'];
//print '<pre>'.htmlspecialchars($headers.$result['message']).'</pre>';exit;
if(mail($to, $subject, $result['message'], $headers)) return TRUE;
return FALSE;
}
?>
</code></pre>
| 0 | 2,033 |
Adding a SessionStore (ITicketStore) to my application cookie makes my Data Protection Provider fail to work
|
<p>tl;dr</p>
<ul>
<li>Have .NET Core 2.0 application which uses a Data Protection Provider which persists a key file across all of the sites on my domain.</li>
<li>Worked fine, however, application cookie became too big.</li>
<li>Implemented a SessionStore on the cookie using ITicketStore</li>
<li>Cookie size is greatly reduced, however, the key from the DPP no longer persists across my sites.</li>
</ul>
<p>Is there something I'm supposed to do in my ITicketStore implementation to fix this? I'm assuming so, since this is where the problem arises, however, I could not figure it out.</p>
<p>Some snippets:</p>
<hr>
<p><strong>Startup.cs --> ConfigureServices()</strong> </p>
<pre><code>var keysFolder = $@"c:\temp\_WebAppKeys\{_env.EnvironmentName.ToLower()}";
var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(keysFolder));
var dataProtector = protectionProvider.CreateProtector(
"Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
"Cookies",
"v2");
--snip--
services.AddSingleton<ITicketStore, TicketStore>();
--snip--
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(keysFolder))
.SetApplicationName("app_auth");
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = ".XAUTH";
options.Cookie.Domain = ".domain.com";
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.LoginPath = "/Account/Login";
options.DataProtectionProvider = protectionProvider;
options.TicketDataFormat = new TicketDataFormat(dataProtector);
options.CookieManager = new ChunkingCookieManager();
options.SessionStore = services.BuildServiceProvider().GetService<ITicketStore>();
});
</code></pre>
<hr>
<p><strong>TicketStore.cs</strong></p>
<pre><code>public class TicketStore : ITicketStore
{
private IMemoryCache _cache;
private const string KeyPrefix = "AuthSessionStore-";
public TicketStore(IMemoryCache cache)
{
_cache = cache;
}
public Task RemoveAsync(string key)
{
_cache.Remove(key);
return Task.FromResult(0);
}
public Task RenewAsync(string key, AuthenticationTicket ticket)
{
var options = new MemoryCacheEntryOptions
{
Priority = CacheItemPriority.NeverRemove
};
var expiresUtc = ticket.Properties.ExpiresUtc;
if (expiresUtc.HasValue)
{
options.SetAbsoluteExpiration(expiresUtc.Value);
}
options.SetSlidingExpiration(TimeSpan.FromMinutes(60));
_cache.Set(key, ticket, options);
return Task.FromResult(0);
}
public Task<AuthenticationTicket> RetrieveAsync(string key)
{
AuthenticationTicket ticket;
_cache.TryGetValue(key, out ticket);
return Task.FromResult(ticket);
}
public async Task<string> StoreAsync(AuthenticationTicket ticket)
{
var key = KeyPrefix + Guid.NewGuid();
await RenewAsync(key, ticket);
return key;
}
</code></pre>
| 0 | 1,039 |
Unsupported or unrecognized ssl-message exception at startHandshake after issuing STARTTLS command in a java program
|
<p>I have written a simple e-mail client in java without using the JavaMail API, as by what I read from the documentation it seems necessary to split the messages up into head and body and in the single MIME-parts for sending which would make my application a lot more complicated. Everything worked fine for a SSL port (465) but now I'm trying to use the client with a different provider that only supports STARTTLS on port 587. The following code is of a class I wrote to test the access to the server.</p>
<pre><code>private static DataOutputStream dos; //Streams to communicate with the server
private static DataInputStream dis;
public static void main(String[] args) {
try {
Socket socket = new Socket("mail.arcor.de", 587);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
new Thread(() -> {readInputRun();}).start(); //see below, every input from the server is printed to the standard output.
dos.write(("EHLO " + InetAddress.getLocalHost().getHostAddress() + "\r\n").getBytes());
dos.write("STARTTLS\r\n".getBytes());
SSLSocket sslSocket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(socket, "mail.arcor.de", 587, true);
dos = new DataOutputStream(sslSocket.getOutputStream());
dis = new DataInputStream(sslSocket.getInputStream());
sslSocket.startHandshake();
dos.write(("EHLO " + InetAddress.getLocalHost().getHostAddress() + "\r\n").getBytes());
dos.write("QUIT\r\n".getBytes());
Thread.sleep(5000);
dis.close();
dos.close();
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
private static void readInputRun() {
try {
int input;
while((input = dis.read()) >= 0) {
System.out.print((char) input);
}
} catch(Exception e) {
e.printStackTrace();
}
}
</code></pre>
<p>Every time I execute it, I get the following exception:</p>
<pre><code>javax.net.ssl.SSLException: Unsupported or unrecognized SSL message
at java.base/sun.security.ssl.SSLSocketInputRecord.handleUnknownRecord(SSLSocketInputRecord.java:416)
at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:173)
at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1031)
at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at java.base/sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1402)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1429)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
at accessTest.AccessTestSTARTTLS.main(AccessTestSTARTTLS.java:31)
</code></pre>
<p>It is thrown at line 31, which is 'sslSocket.startHandshake();', so somehow the handshake does not work out. Do I initiate it at the wrong point or in the wrong way?</p>
<p>Thanks in advance for any help.</p>
<p>EDIT: As suggested in the comment, I enabled the logs and found the following:
<a href="https://i.stack.imgur.com/IitSc.png" rel="nofollow noreferrer">httpslog</a>. In the fifth but last line there is an unreadable character, obviously as part of the client hello, so my computer sends it. Why is this the case and how can I stop that?</p>
| 0 | 1,192 |
matrix inversion in boost
|
<p>I am trying to do a simple matrix inversion operation using boost. But I
am getting an error.
Basically what I am trying to find is inversted_matrix =
inverse(trans(matrix) * matrix)
But I am getting an error </p>
<pre><code>Check failed in file boost_1_53_0/boost/numeric/ublas/lu.hpp at line 299:
detail::expression_type_check (prod (triangular_adaptor<const_matrix_type,
upper> (m), e), cm2)
terminate called after throwing an instance of
'boost::numeric::ublas::internal_logic'
what(): internal logic
Aborted (core dumped)
</code></pre>
<p>My attempt: </p>
<pre><code>#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/lu.hpp>
namespace ublas = boost::numeric::ublas;
template<class T>
bool InvertMatrix (const ublas::matrix<T>& input, ublas::matrix<T>& inverse) {
using namespace boost::numeric::ublas;
typedef permutation_matrix<std::size_t> pmatrix;
// create a working copy of the input
matrix<T> A(input);
// create a permutation matrix for the LU-factorization
pmatrix pm(A.size1());
// perform LU-factorization
int res = lu_factorize(A,pm);
if( res != 0 )
return false;
// create identity matrix of "inverse"
inverse.assign(ublas::identity_matrix<T>(A.size1()));
// backsubstitute to get the inverse
lu_substitute(A, pm, inverse);
return true;
}
int main(){
using namespace boost::numeric::ublas;
matrix<double> m(4,5);
vector<double> v(4);
vector<double> thetas;
m(0,0) = 1; m(0,1) = 2104; m(0,2) = 5; m(0,3) = 1;m(0,4) = 45;
m(1,0) = 1; m(1,1) = 1416; m(1,2) = 3; m(1,3) = 2;m(1,4) = 40;
m(2,0) = 1; m(2,1) = 1534; m(2,2) = 3; m(2,3) = 2;m(2,4) = 30;
m(3,0) = 1; m(3,1) = 852; m(3,2) = 2; m(3,3) = 1;m(3,4) = 36;
std::cout<<m<<std::endl;
matrix<double> product = prod(trans(m), m);
std::cout<<product<<std::endl;
matrix<double> inversion(5,5);
bool inverted;
inverted = InvertMatrix(product, inversion);
std::cout << inversion << std::endl;
}
</code></pre>
| 0 | 1,125 |
Kubernetes pod never gets ready
|
<p>I am setting up a small Kubernetes cluster using a VM (master) and 3 bare metal servers (all running Ubuntu 14.04). I followed the Kubernetes <a href="https://github.com/kubernetes/kubernetes/blob/release-1.0/docs/getting-started-guides/ubuntu.md" rel="noreferrer">install tutorial for Ubuntu</a>. Each bare metal server also has 2T of disk space exported using <a href="http://docs.ceph.com/docs/v0.94.5/start/" rel="noreferrer">Ceph 0.94.5</a>. Everything is working fine, but when I try to start a Replication Controller I get the following (kubectl get pods):</p>
<pre><code>NAME READY STATUS RESTARTS AGE
site2-zecnf 0/1 Image: site-img is ready, container is creating 0 12m
</code></pre>
<p>The pod will be in this Not Ready state forever, but, if I kill it and start it again, it will run fine (sometimes I have to repeat this operation a few times though). Once the pod is running, everything works just fine.</p>
<p>If, for some reason, the pod dies, it's restarted by Kubernetes, but can enter in this Not Ready state again. Running:</p>
<pre><code>kubectl describe pod java-site2-crctv
</code></pre>
<p>I get (some fields deleted):</p>
<pre><code>Namespace: default
Status: Pending
Replication Controllers: java-site2 (1/1 replicas created)
Containers:
java-site:
Image: javasite-img
State: Waiting
Reason: Image: javasite-img is ready, container is creating
Ready: False
Restart Count: 0
Conditions:
Type Status
Ready False
Events:
FirstSeen LastSeen Count From SubobjectPath Reason Message
Sat, 14 Nov 2015 12:37:56 -0200 Sat, 14 Nov 2015 12:37:56 -0200 1 {scheduler } scheduled Successfully assigned java-site2-crctv to 10.70.2.3
Sat, 14 Nov 2015 12:37:57 -0200 Sat, 14 Nov 2015 12:45:29 -0200 46 {kubelet 10.70.2.3} failedMount Unable to mount volumes for pod "java-site2-crctv_default": exit status 22
Sat, 14 Nov 2015 12:37:57 -0200 Sat, 14 Nov 2015 12:45:29 -0200 46 {kubelet 10.70.2.3} failedSync Error syncing pod, skipping: exit status 22
</code></pre>
<p>The pod cannot mount the volume. But, if I mount the volumes (rdb blocks) by hand in a local folder in all nodes, the problem is gone (pods start without problems). </p>
<p>It seems to me that Kubernetes isn't able to map them (<code>sudo rbd map java-site-vol</code>), only to mount them (<code>sudo mount /dev/rbd/rbd/java-site-vol /...</code>).</p>
<p>Should I map all Ceph volumes that I use or should Kubernetes do that? </p>
| 0 | 1,036 |
Android Calling Async Task in an activity
|
<p>I have an activity that selects an image from a gridview and it allows you to save the image. I'm using Async Task for all my codes. I seperated my AsyncTask from a few classes. How do i call them from my activity? How do I pass string back to my AsyncTask. </p>
<p>SingleImageView.class</p>
<pre><code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_image:
new SaveImageTask().execute(image_url,context); //<-- The method execute(String...) in the type AsyncTask<String,String,String> is not applicable for the arguments (String, Context)
return true;
default:
return false;
}
</code></pre>
<p>SaveImageTask.class</p>
<pre><code> public class SaveImageTask extends AsyncTask<String, String, String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl = null;
Bitmap bmImg = null;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context); //<<-- Couldnt Recognise
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(image_url);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
pDialog.dismiss();
}
}
</code></pre>
| 0 | 1,482 |
How do I generate a custom menu/sub-menu system using wp_get_nav_menu_items in WordPress?
|
<p>I have an html structure that requires customization of the <code>wp_nav_menu</code> code.</p>
<p>This is the html I need to generate:</p>
<pre><code><ul class="main-nav">
<li class="item">
<a href="http://example.com/?p=123" class="title">Title</a>
<a href="http://example.com/?p=123" class="desc">Description</a>
<ul class="sub-menu">
<li class="item">
<a href="http://example.com/?p=123" class="title">Title</a>
<a href="http://example.com/?p=123" class="desc">Description</a>
</li>
</ul>
</li>
<li class="item">
<a href="http://example.com/?p=123" class="title">Title</a>
<a href="http://example.com/?p=123" class="desc">Description</a>
</li>
</ul>
</code></pre>
<p>I am currently using <code>wp_get_nav_menu_items</code> to get all the items from my menu as an array.</p>
<p>Right now I am able to generate the above html <strong>without the sub-menus</strong> using the following code:</p>
<pre><code><?php
$menu_name = 'main-nav';
$locations = get_nav_menu_locations()
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
foreach ( $menuitems as $item ):
$id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$page = get_page( $id );
$link = get_page_link( $id ); ?>
<li class="item">
<a href="<?php echo $link; ?>" class="title">
<?php echo $page->post_title; ?>
</a>
<a href="<?php echo $link; ?>" class="desc">
<?php echo $page->post_excerpt; ?>
</a>
</li>
<?php endforeach; ?>
</code></pre>
<p>I would have generated the menu using the <code>wp_nav_menu</code> function but I still need the description shown using <code>$page->post_excerpt</code>.</p>
<p>I've found that there is a property for each item called <code>$item->menu_item_parent</code> which gives the ID of the parent menu item.</p>
<p>How would I generate the sub-menu in my <code>foreach</code> loop?
Or is there a really simple way using <code>wp_nav_menu</code> which Google forgot to mention?</p>
| 0 | 1,120 |
linear-gradients not working in mobile web browsers
|
<p>I am writing a mobile web-app and I was wondering if someone could help me understand and fix these linear-gradients so that they work in both <code>Safari-mobile</code> and the <code>Android-browser</code>.</p>
<p>I believe I am using every vendor-prefix properly and I even provide a fallback background-color, but whenever I view the app on a mobile device, the element whose background the gradients are applied to is transparent. In other words, the background is transparent and the gradients are not showing up on mobile devices. Meaning, even the fall-back colour is not working either.</p>
<p>The even more weird thing is that they (the gradients) show up on the mobile simulators for android and <code>iOS</code>.</p>
<p>Can someone please help me fix these gradients so they work on both desktop and mobile devices and also teach me how to do working fallback background-colors and background-images ?</p>
<p>I would really appreciate any and all help!</p>
<p>Here is what I have so far:</p>
<pre><code>background:#fff;
background:transparent -ms-linear-gradient(top, rgba(255,255,255,.65), rgba(255,255,255,.9));
background:transparent url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEwMCAxMDAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iaGF0MCIgZ3JhZGllbnRVbml0cz0ib2JqZWN0Qm91bmRpbmdCb3giIHgxPSI1MCUiIHkxPSIxMDAlIiB4Mj0iNTAlIiB5Mj0iLTEuNDIxMDg1NDcxNTIwMmUtMTQlIj4KPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmZiIgc3RvcC1vcGFjaXR5PSIwLjY1Ii8+CjxzdG9wIG9mZnNldD0iMTAwJSIgc3RvcC1jb2xvcj0iI2ZmZiIgc3RvcC1vcGFjaXR5PSIwLjkiLz4KICAgPC9saW5lYXJHcmFkaWVudD4KCjxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIiBmaWxsPSJ1cmwoI2hhdDApIiAvPgo8L3N2Zz4=);
background:transparent -o-linear-gradient(90deg, rgba(255,255,255,.65) 0%, rgba(255,255,255,.9) 100%);
background:transparent -moz-linear-gradient(90deg, rgba(255,255,255,.65) 0%, rgba(255,255,255,.9) 100%);
background:transparent -webkit-gradient(linear, 0%, 0%, 0%, 100%, from(rgba(255,255,255,.65), to(rgba(255,255,255,.9));
background:transparent -webkit-linear-gradient(90deg, rgba(255,255,255,.65) 0%, rgba(255,255,255,.9) 100%);
background:transparent linear-gradient(90deg, rgba(255,255,255,.65) 0%, rgba(255,255,255,.9) 100%);
</code></pre>
<p>Thanks in Advance!</p>
| 0 | 1,058 |
What is the fastest way to bulk load data into HBase programmatically?
|
<p>I have a Plain text file with possibly millions of lines which needs custom parsing and I want to load it into an HBase table as fast as possible (using Hadoop or HBase Java client).</p>
<p>My current solution is based on a <strong>MapReduce</strong> job without the Reduce part. I use <code>FileInputFormat</code> to read the text file so that each line is passed to the <code>map</code> method of my <code>Mapper</code> class. At this point the line is parsed to form a <code>Put</code> object which is written to the <code>context</code>. Then, <code>TableOutputFormat</code> takes the <code>Put</code> object and inserts it to table.</p>
<p>This solution yields an average insertion rate of 1,000 rows per second, which is less than what I expected. <strong>My HBase setup is in pseudo distributed mode on a single server.</strong></p>
<p>One interesting thing is that during insertion of 1,000,000 rows, 25 Mappers (tasks) are spawned but they run serially (one after another); is this normal?</p>
<p>Here is the code for my current solution:</p>
<pre><code>public static class CustomMap extends Mapper<LongWritable, Text, ImmutableBytesWritable, Put> {
protected void map(LongWritable key, Text value, Context context) throws IOException {
Map<String, String> parsedLine = parseLine(value.toString());
Put row = new Put(Bytes.toBytes(parsedLine.get(keys[1])));
for (String currentKey : parsedLine.keySet()) {
row.add(Bytes.toBytes(currentKey),Bytes.toBytes(currentKey),Bytes.toBytes(parsedLine.get(currentKey)));
}
try {
context.write(new ImmutableBytesWritable(Bytes.toBytes(parsedLine.get(keys[1]))), row);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int run(String[] args) throws Exception {
if (args.length != 2) {
return -1;
}
conf.set("hbase.mapred.outputtable", args[1]);
// I got these conf parameters from a presentation about Bulk Load
conf.set("hbase.hstore.blockingStoreFiles", "25");
conf.set("hbase.hregion.memstore.block.multiplier", "8");
conf.set("hbase.regionserver.handler.count", "30");
conf.set("hbase.regions.percheckin", "30");
conf.set("hbase.regionserver.globalMemcache.upperLimit", "0.3");
conf.set("hbase.regionserver.globalMemcache.lowerLimit", "0.15");
Job job = new Job(conf);
job.setJarByClass(BulkLoadMapReduce.class);
job.setJobName(NAME);
TextInputFormat.setInputPaths(job, new Path(args[0]));
job.setInputFormatClass(TextInputFormat.class);
job.setMapperClass(CustomMap.class);
job.setOutputKeyClass(ImmutableBytesWritable.class);
job.setOutputValueClass(Put.class);
job.setNumReduceTasks(0);
job.setOutputFormatClass(TableOutputFormat.class);
job.waitForCompletion(true);
return 0;
}
public static void main(String[] args) throws Exception {
Long startTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Start time : " + startTime);
int errCode = ToolRunner.run(HBaseConfiguration.create(), new BulkLoadMapReduce(), args);
Long endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("End time : " + endTime);
System.out.println("Duration milliseconds: " + (endTime-startTime));
System.exit(errCode);
}
</code></pre>
| 0 | 1,194 |
How do I update PyQt5?
|
<p>I have an apparently older version of PyQt5 installed on my Xubuntu (Voyager). When I print the <code>PYQT_VERSION_STR</code>, it displays: <code>'5.2.1'</code>. I downloaded the latest PyQt5 release form here: <a href="http://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.4/" rel="nofollow">http://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.4/</a>
I configured it, make and make installed it, everything went according to plan. However, if I print the <code>PYQT_VERSION_STR</code> again, it still outputs <code>'5.2.1'</code>.</p>
<p>How do I tell my python3.4 to use the updated version?</p>
<p>(Shouldn't the reinstall of the new version overwrite the other one? I don't understand why it is still showing 5.2.1 as version string.)</p>
<p><strong>EDIT #1:</strong></p>
<p><code>sys.path</code>:
['', '/home/user/.pythonbrew/lib', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']</p>
<p><code>PyQt5.__file__</code>
'/usr/lib/python3/dist-packages/PyQt5/<strong>init</strong>.py'</p>
<p>So it seems my python is using the version from the repositories, except if that's where it got installed when make installing.</p>
<p><strong>EDIT #2:</strong></p>
<p>It seems that the <code>PYQT_VERSION_STR</code> returns the version of Qt (!) which the PyQt5 configuration before making and make installing found. So the actual issue seems to be with my Qt5 version, which is <code>5.2.1</code> according to the output of <code>python configure</code> of PyQt5:</p>
<pre><code>Querying qmake about your Qt installation...
Determining the details of your Qt installation...
This is the GPL version of PyQt 5.4 (licensed under the GNU General Public License) for Python 3.4.0 on linux.
Type 'L' to view the license.
Type 'yes' to accept the terms of the license.
Type 'no' to decline the terms of the license.
Do you accept the terms of the license? yes
Found the license file pyqt-gpl.sip.
Checking [...]
DBus v1 does not seem to be installed.
Qt v5.2.1 (Open Source) is being used.
The qmake executable is /usr/bin/qmake.
Qt is built as a shared library.
SIP 4.16.5 is being used.
The sip executable is /usr/bin/sip.
These PyQt5 modules will be built: QtCore, QtGui, QtNetwork, QtOpenGL,
QtPrintSupport, QtQml, QtQuick, QtSql, QtTest, QtWidgets, QtXml, QtDBus, _QOpenGLFunctions_2_0.
The PyQt5 Python package will be installed in /usr/lib/python3.4/site-packages.
PyQt5 is being built with generated docstrings.
PyQt5 is being built with 'protected' redefined as 'public'.
The Designer plugin will be installed in
/usr/lib/x86_64-linux-gnu/qt5/plugins/designer.
The qmlscene plugin will be installed in
/usr/lib/x86_64-linux-gnu/qt5/plugins/PyQt5.
The PyQt5 .sip files will be installed in /usr/share/sip/PyQt5.
pyuic5, pyrcc5 and pylupdate5 will be installed in /usr/bin.
The interpreter used by pyuic5 is /usr/bin/python3.
Generating the C++ source for the QtCore module...
Embedding sip flags...
Generating [...]
Re-writing
/home/xiaolong/Downloads/PyQt-gpl-5.4/examples/quick/tutorials/extending/chapter6-plugins/Charts/qmldir...
Generating the top-level .pro file...
Making the pyuic5 wrapper executable...
Generating the Makefiles...
</code></pre>
<p>So the PyQt5 is going into the correct directory, but the actual version of Qt5 is older than 5.4. Now the question seems turns into "How do I update my Qt5 version?" unless I misunderstood something here.</p>
<p><strong>EDIT #3:</strong></p>
<p>Output of <code>sys.executable</code>:</p>
<pre><code>Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'/usr/bin/python3'
>>>
</code></pre>
<p><strong>EDIT #4:</strong></p>
<p>Contents of my <code>.bash_aliases</code> file:
<code>
alias python=python3
alias pip=pip3
</code></p>
| 0 | 1,418 |
Proguard and error
|
<p>I use this proguard file:</p>
<pre><code> -dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
!code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*
-optimizationpasses 10
-allowaccessmodification
-mergeinterfacesaggressively
-overloadaggressively
-assumenosideeffects class android.util.Log {
*;
}
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgent
-keep public class * extends android.preference.Preference
-keep public class * extends android.support.v4.app.Fragment
-keep public class * extends android.support.v4.app.DialogFragment
-keep public class * extends com.actionbarsherlock.app.SherlockListFragment
-keep public class * extends com.actionbarsherlock.app.SherlockFragment
-keep public class * extends com.actionbarsherlock.app.SherlockFragmentActivity
-keep public class * extends android.app.Fragment
-keep public class com.android.vending.licensing.ILicensingService
-keep public class org.jsoup.** {
public *;
}
-keep public class * extends android.view.View {
public <init>(android.content.Context);
public <init>(android.content.Context, android.util.AttributeSet);
public <init>(android.content.Context, android.util.AttributeSet, int);
public void set*(...);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
-keepclassmembers class **.R$* {
public static <fields>;
}
-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep class com.actionbarsherlock.** { *; }
-keep interface com.actionbarsherlock.** { *; }
-keep class com.google.ads.** {*;}
-keep class com.google.ads.internal.** {*;}
-keep class com.google.ads.mediation.** {*;}
-keep class com.google.ads.mediation.adfonic.** {*;}
-keep class com.google.ads.mediation.admob.** {*;}
-keep class com.google.ads.mediation.adfonic.util.** {*;}
-keep class com.google.ads.mediation.customevent.** {*;}
-keep class com.google.ads.searchads.** {*;}
-keep class com.google.ads.util.** {*;}
-dontwarn android.support.**
-dontwarn com.google.ads.**
</code></pre>
<p>But after some update on the code, I have the following errors:</p>
<pre><code>Warning:com.google.android.gms.internal.zzw$zza: can't find superclass or interface org.apache.http.client.methods.HttpEntityEnclosingRequestBase
Warning:com.google.android.gms.analytics.internal.zzam: can't find referenced class org.apache.http.NameValuePair
Warning:com.google.android.gms.analytics.internal.zzam: can't find referenced class org.apache.http.client.utils.URLEncodedUtils
Warning:com.google.android.gms.analytics.internal.zzam: can't find referenced class org.apache.http.NameValuePair
Warning:com.google.android.gms.analytics.internal.zzj: can't find referenced class org.apache.http.NameValuePair
Warning:com.google.android.gms.analytics.internal.zzj: can't find referenced class org.apache.http.client.utils.URLEncodedUtils
Warning:com.google.android.gms.analytics.internal.zzj: can't find referenced class org.apache.http.NameValuePair
Warning:com.google.android.gms.internal.zzac: can't find referenced class android.net.http.AndroidHttpClient
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.HttpEntity
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.StatusLine
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.client.methods.HttpGet
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.conn.ClientConnectionManager
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.impl.client.DefaultHttpClient
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.params.BasicHttpParams
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.client.methods.HttpGet
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.impl.client.DefaultHttpClient
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.params.BasicHttpParams
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.HttpEntity
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.StatusLine
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.conn.ClientConnectionManager
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.internal.zzqt: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.Header
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.HttpEntity
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.StatusLine
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.impl.cookie.DateUtils
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.Header
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.HttpEntity
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.StatusLine
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.HttpEntity
Warning:com.google.android.gms.internal.zzt: can't find referenced class org.apache.http.Header
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpDelete
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpEntityEnclosingRequestBase
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpGet
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpHead
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpOptions
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpPost
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpPut
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpTrace
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpUriRequest
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.entity.ByteArrayEntity
Warning:com.google.android.gms.internal.zzw: can't find referenced method 'void addHeader(java.lang.String,java.lang.String)' in program class com.google.android.gms.internal.zzw$zza
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpDelete
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpEntityEnclosingRequestBase
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpGet
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpHead
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpOptions
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpPost
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpPut
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpTrace
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.entity.ByteArrayEntity
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpUriRequest
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpUriRequest
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpUriRequest
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpEntityEnclosingRequestBase
Warning:com.google.android.gms.internal.zzw: can't find referenced class org.apache.http.client.methods.HttpUriRequest
Warning:com.google.android.gms.internal.zzw$zza: can't find referenced class org.apache.http.client.methods.HttpEntityEnclosingRequestBase
Warning:com.google.android.gms.internal.zzw$zza: can't find referenced method 'void setURI(java.net.URI)' in program class com.google.android.gms.internal.zzw$zza
Warning:com.google.android.gms.internal.zzw$zza: can't find referenced class org.apache.http.client.methods.HttpEntityEnclosingRequestBase
Warning:com.google.android.gms.internal.zzx: can't find referenced class org.apache.http.impl.cookie.DateParseException
Warning:com.google.android.gms.internal.zzx: can't find referenced class org.apache.http.impl.cookie.DateUtils
Warning:com.google.android.gms.internal.zzy: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.ProtocolVersion
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.entity.BasicHttpEntity
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.message.BasicHeader
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.message.BasicHttpResponse
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.message.BasicStatusLine
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.ProtocolVersion
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.entity.BasicHttpEntity
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.message.BasicHeader
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.message.BasicHttpResponse
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.message.BasicStatusLine
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.internal.zzz: can't find referenced class org.apache.http.HttpEntity
Warning:com.google.android.gms.tagmanager.zzby: can't find referenced class org.apache.http.impl.client.DefaultHttpClient
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.Header
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpEntity
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpEntityEnclosingRequest
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpHost
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.StatusLine
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.client.ClientProtocolException
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.message.BasicHttpEntityEnclosingRequest
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpHost
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.message.BasicHttpEntityEnclosingRequest
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpEntity
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpEntityEnclosingRequest
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpResponse
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.StatusLine
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.client.HttpClient
Warning:com.google.android.gms.tagmanager.zzcx: can't find referenced class org.apache.http.HttpEntityEnclosingRequest
</code></pre>
<p>I tried with:</p>
<pre><code>-keep class org.apache.http.**
-keep interface org.apache.http.**
-dontwarn org.apache.**
</code></pre>
<p>But still doesn't works, what's wrong? I really don't understand what can I do.
PS do you have any suggestions in order to optimize my file?
Thanks in advance.</p>
| 0 | 4,556 |
HTTP Request using Netty
|
<p>I have just started netty and I am really disappointed with the documentation present on
their website. </p>
<p>I am trying to connect to an URL using Netty.. I took the time client example from their website and changed it as per my requirement.. </p>
<p>Code :</p>
<pre><code>public class NettyClient {
public static void main(String[] args) throws Exception {
String host = "myUrl.com/v1/parma?param1=value";
int port = 443;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientHandler());
ch.pipeline().addLast("encoder", new HttpRequestEncoder());
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
</code></pre>
<p>But the problem is that that it expects only the url without the query parameters.. How can I pass query parameters with the URL?
and please provide me some link of a good documentation for Netty 4..</p>
<p>EDIT</p>
<p>Client code after referring the example mentioned in the answer :</p>
<pre><code>URI uri = new URI("myUrl.com/v1/parma?param1=value");
String scheme = uri.getScheme() == null? "http" : uri.getScheme();
String host = "myUrl.com";
int port = 443;
boolean ssl = "https".equalsIgnoreCase(scheme);
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new NettyClientInitializer(ssl));
// Make the connection attempt.
Channel ch = b.connect(host, port).sync().channel();
// Prepare the HTTP request.
HttpRequest request = new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
request.headers().set(HttpHeaders.Names.HOST, host);
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
//request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
/*// Set some example cookies.
request.headers().set(
HttpHeaders.Names.COOKIE,
ClientCookieEncoder.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar")));
*/
// Send the HTTP request.
ch.writeAndFlush(request);
// Wait for the server to close the connection.
ch.closeFuture().sync();
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
}
</code></pre>
<p>handler code :</p>
<pre><code>public class ClientHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
System.out.println("STATUS: " + response.getStatus());
System.out.println("VERSION: " + response.getProtocolVersion());
System.out.println();
if (!response.headers().isEmpty()) {
for (String name: response.headers().names()) {
for (String value: response.headers().getAll(name)) {
System.out.println("HEADER: " + name + " = " + value);
}
}
System.out.println();
}
if (HttpHeaders.isTransferEncodingChunked(response)) {
System.out.println("CHUNKED CONTENT {");
} else {
System.out.println("CONTENT {");
}
}
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
System.out.print(content.content().toString(CharsetUtil.UTF_8));
System.out.flush();
if (content instanceof LastHttpContent) {
System.out.println("} END OF CONTENT");
}
}
}
@Override
public void exceptionCaught(
ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
</code></pre>
<p>initializer code :</p>
<pre><code>public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {
private final boolean ssl;
public NettyClientInitializer(boolean ssl) {
this.ssl = ssl;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
// Create a default pipeline implementation.
ChannelPipeline p = ch.pipeline();
p.addLast("log", new LoggingHandler(LogLevel.INFO));
// Enable HTTPS if necessary.
/*
if (ssl) {
SSLEngine engine =
SecureChatSslContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);
p.addLast("ssl", new SslHandler(engine));
}
*/
p.addLast("codec", new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
// p.addLast("inflater", new HttpContentDecompressor());
// Uncomment the following line if you don't want to handle HttpChunks.
p.addLast("aggregator", new HttpObjectAggregator(1048576));
p.addLast("handler", new ClientHandler());
}
}
</code></pre>
| 0 | 2,953 |
Angular combining parallel and chained requests with $http.then() and $q.all()
|
<p>I have a rather complicated set of API calls to make and I'm attempting to do it as elegantly and performant as possible. I understand how to use the promise api of the <code>$http</code> service to chain requests, and how to use the <code>$q</code> service to make requests in parallel. But for this specific API workflow I need to do both.</p>
<p>Here is an example of the high-level API flow:</p>
<ul>
<li><code>/dog/<dog_id></code>
<ul>
<li><code>/breed/<breed_id></code>
<ul>
<li><code>/food/<food_id></code></li>
</ul></li>
</ul></li>
<li><code>/cat/<cat_id></code></li>
<li><code>/turkey/<turkey_id></code></li>
<li><code>/fish/<fish_id></code></li>
</ul>
<p>The first tier of requests all have known ids. However the <code><breed_id></code> required to make the <code>/breed</code> call must be parsed from the <code>/dog</code> response, and the <code><food_id></code> required to make the <code>/food</code> call must be parsed from the <code>/breed</code> response. So <code>/dog</code>, <code>/breed</code>, and <code>/food</code> all need to be chained. However <code>/cat</code>, <code>/turkey</code>, and <code>/fish</code> can be made in parallel with the entire <code>/dog</code> chain.</p>
<p>What I've got now (and it is working fine) are two separate sets of requests. How do I improve on this flow? Is there a way to combine the two stacks in a way that results in a single promise execution of <code>.then()</code>?</p>
<pre><code>var dogId = '472053',
catId = '840385',
turkeyId = '240987',
fishId = '510412';
var myData = {};
var firstSetComplete = false,
secondSetComplete = false,
returnData = function() {
if (firstSetComplete && secondSetComplete) {
console.log("myData.dog", myData.dog);
console.log("myData.dog.breed", myData.dog.breed);
console.log("myData.dog.food", myData.dog.food);
console.log("myData.cat", myData.cat);
console.log("myData.turkey", myData.turkey);
console.log("myData.fish", myData.fish);
}
};
// first call set
$http.get('http://example.com/dog/' + dogId)
.then(function(response) {
myData.dog = response.data;
return $http.get('http://example.com/breed/' + response.data.breed_id);
})
.then(function(response) {
myData.dog.breed = response.data;
return $http.get('http://example.com/food/' + response.data.food_id);
})
.then(function(response) {
myData.dog.food = response.data;
firstSetComplete = true;
returnData();
});
// second call set
$q.all([
$http.get('http://example.com/cat/' + catId),
$http.get('http://example.com/turkey/' + turkeyId),
$http.get('http://example.com/fish/' + fishId)
])
.then(function(responses) {
myData.cat = responses[0].data;
myData.turkey = responses[1].data;
myData.fish = responses[2].data;
secondSetComplete = true;
returnData();
});
</code></pre>
| 0 | 1,179 |
React-Native FlatList- Warning: Each child in an array or iterator should have a unique "key" prop, even after giving key={index}
|
<p>I am building the photo-feed application, <a href="https://github.com/ganesh-deshmukh/exchange-o-gram/commits/master" rel="noreferrer">project-repo-here</a> , in the comments section after clicking on show-comments, it shows comment page on a device, but in a terminal, it breaks with error as,</p>
<p>error is in comments.js file.</p>
<pre><code>Warning: Each child in an array or iterator should have a unique "key" prop.%s%s See documentationOfREact/react-warning-keys for more information.%s,
Check the render method of `VirtualizedList`., ,
in CellRenderer (at VirtualizedList.js:687)
in VirtualizedList (at FlatList.js:662)
in FlatList (at comments.js:212)
in RCTView (at View.js:44)
in comments (created by SceneView)
in SceneView (at StackViewLayout.js:795)
in RCTView (at View.js:44)
in AnimatedComponent (at StackViewCard.js:69)
in RCTView (at View.js:44)
in AnimatedComponent (at screens.native.js:59)
in Screen (at StackViewCard.js:57)
in Card (at createPointerEventsContainer.js:27)
in Container (at StackViewLayout.js:860)
in RCTView (at View.js:44)
in ScreenContainer (at StackViewLayout.js:311)
in RCTView (at View.js:44)
in AnimatedComponent (at StackViewLayout.js:307)
in Handler (at StackViewLayout.js:300)
in StackViewLayout (at withOrientation.js:30)
in withOrientation (at StackView.js:79)
in RCTView (at View.js:44)
in Transitioner (at StackView.js:22)
in StackView (created by Navigator)
in Navigator (at createKeyboardAwareNavigator.js:12)
in KeyboardAwareNavigator (at createAppContainer.js:388)
in NavigationContainer (at App.js:70)
in App (at withExpoRoot.js:22)
in RootErrorBoundary (at withExpoRoot.js:21)
in ExpoRootComponent (at renderApplication.js:34)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in AppContainer (at renderApplication.js:33)
- node_modules/react/cjs/react.development.js:217:39 in warningWithoutStack
- node_modules/react/cjs/react.development.js:617:32 in warning
- node_modules/react/cjs/react.development.js:1429:14 in validateExplicitKey
- node_modules/react/cjs/react.development.js:1451:28 in validateChildKeys
- node_modules/react/cjs/react.development.js:1619:22 in cloneElementWithValidation
- node_modules/react-native/Libraries/Lists/VirtualizedList.js:947:6 in render
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:10563:21 in finishClassComponent
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14091:21 in performUnitOfWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14129:41 in workLoop
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14226:15 in renderRoot
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15193:17 in performWorkOnRoot
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15090:24 in performWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15047:14 in performSyncWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14925:19 in requestWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14711:16 in scheduleWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:7700:17 in enqueueSetState
- node_modules/react/cjs/react.development.js:364:31 in setState
* app/screens/comments.js:66:22 in <unknown>
- node_modules/promise/setimmediate/core.js:37:14 in tryCallOne
- node_modules/promise/setimmediate/core.js:123:25 in <unknown>
- ... 8 more stack frames from framework internals
</code></pre>
<p>I am displaying comments-array using flatList and gave </p>
<p><code>keyExtractor={(item, index) => {
item.id;
}}</code></p>
<p>also, I tried giving key={index}, but same error.
I gave unique key as index to , but error occurs,</p>
<p>flatList component is </p>
<pre><code> <FlatList
refreshing={this.state.refresh}
data={this.state.comments_list}
keyExtractor={(item, index) => {
item.id;
}}
style={{ flex: 1, backgroundColor: "#eee" }}
renderItem={({ item, index }) => (
<View
key={item.id}
style={{
width: "100%",
overflow: "hidden",
marginBottom: 5,
justifyContent: "space-between",
borderColor: "grey"
}}
>
<View style={{ padding: 5 }}>
<Text>time: {item.timestamp}</Text>
<TouchableOpacity>
<Text>{item.author}</Text>
</TouchableOpacity>
</View>
<View>
<Text>{item.comment}</Text>
</View>
</View>
)}
/>
</code></pre>
<p>firebase structure is this
<a href="https://i.stack.imgur.com/pLbeT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pLbeT.png" alt="structureOfDB"></a> </p>
| 0 | 2,172 |
Setting up a subdomain with Apache on Linux
|
<p>I can't believe that I haven't done this before, but I would like a definitive answer so I'm all set going forward.</p>
<p>I have an apache config file at <code>/etc/apache2/sites-available/mysite</code> which looks like this:</p>
<pre><code><VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /home/sam/public_html
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
<Directory /home/sam/public_html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code></pre>
<p>So this serves html and php files from <code>~/public_html</code> all fine. But I have multiple projects there so would like to start using subdomains. What I want to do is serve files from <code>~/public_html/myproject/</code> as the root directory for <code>myproject.localhost</code>.</p>
<p>I have tried adding the following to the bottom of my apache file:</p>
<pre><code><VirtualHost myproject.localhost>
DocumentRoot ~/public_html/myproject/
ServerName myproject.localhost
ServerAdmin admin@myproject.localhost
<Directory ~/public_html/myproject>
Options Indexes FollowSymLinks
AllowOverride FileInfo
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
</code></pre>
<p>but apache complains:</p>
<pre><code>Restarting web server: apache2[Tue Aug 20 11:06:19 2013] [error] (EAI 2)Name or service not known: Could not resolve host name myproject.localhost -- ignoring!
... waiting [Tue Aug 20 11:06:20 2013] [error] (EAI 2)Name or service not known: Could not resolve host name myproject.localhost -- ignoring!
</code></pre>
<p>I know I'm committing a fundamental error, but I'm not sure what it is. </p>
<h2>Edit</h2>
<p>This is my complete file now:</p>
<pre><code><VirtualHost *:80>
DocumentRoot /home/sam/public_html/ryua1226-magento/
ServerName mydomain.localhost
ServerAdmin admin@mydomain.localhost
<Directory /home/sam/public_html/ryua1226-magento>
Options Indexes FollowSymLinks
AllowOverride FileInfo
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /home/sam/public_html
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
<Directory /home/sam/public_html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code></pre>
| 0 | 1,493 |
The name ViewModelLocator does not exist in the namespace
|
<p>I'm learning WPF with MVVM Light and i've an issue with my Portable Class Library.
I follow this tutorial: <a href="http://www.codeproject.com/Articles/536494/Portable-MVVM-Light-Move-Your-View-Models" rel="noreferrer">http://www.codeproject.com/Articles/536494/Portable-MVVM-Light-Move-Your-View-Models</a></p>
<p>I created a portal class library and a WPF mvvm light 4.5 with reference of MVVM Light.
I've added the reference of my PCL in my wpf project.
So in my PCL, i've added a folder ModelView and inside my ModelViewLocator</p>
<pre><code>using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
using EasyDevis.EasyDevisPCL.Model;
using EasyDevis.EasyDevisPCL.ViewModel.MainPage;
namespace EasyDevis.EasyDevisPCL.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainPageViewModel>();
}
/// <summary>
/// Gets the Main property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainPageViewModel MainPageViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MainPageViewModel>();
}
}
/// <summary>
/// Cleans up all the resources.
/// </summary>
public static void Cleanup()
{
}
}
}
</code></pre>
<p>The issue come in my app.xaml and the namespace is correct because of intelisense propose me the path.</p>
<pre><code><Application x:Class="EasyDevis.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:EasyDevis.EasyDevisPCL.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
StartupUri="Content/MainPage/View/MainPageView.xaml"
mc:Ignorable="d">
<Application.Resources>
<!--i've the error on this line-->
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</Application.Resources>
</Application>
</code></pre>
<p>Do you have an idea of what i did wrong?</p>
| 0 | 1,087 |
Vuejs 3 emit event from child to parent component
|
<p>I've recently started working with VueJS, I'm using v3 and seem to be having an issue calling a method on a parent. The emit function in the child doesn't seem to be emitting the event and nothing is getting picked up in the parent.</p>
<p>I've included the parent and child to show how I have it set up</p>
<p><strong>Parent</strong></p>
<pre><code><template>
<First/>
< Child v-bind:sample="sample" @enlarge-text="onEnlargeText"/>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import axios from 'axios';
import First from './First.vue';
import Child from './Child.vue';
export default defineComponent({
name: 'Container',
components: {
First,
Child,
},
methods: {
onEnlargeText() {
console.log('enlargeText');
},
},
data: () => ({
sample: [],
parentmessage: '',
}),
created() {
axios.get('http://localhost:8080/getData')
.then((response) => {
console.log(response);
this.sample = response.data;
})
.catch((error) => {
console.log(error);
});
},
});
</script>
</code></pre>
<p><strong>Child</strong></p>
<pre><code><template>
<div id="add">
<form id="signup-form" @submit.prevent="submit">
<label for="text">Text:</label>
<input type="text" v-model="text" required>
<p class="error" >{{ error }}</p>
<div class="field has-text-right">
<button type="submit" class="button is-danger">Submit</button>
</div>
</form>
<button v-on:click="tryThis">
Enlarge text
</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import axios from 'axios';
interface SampleInterface {
text: string;
error: string;
}
export default defineComponent({
name: 'Add',
data: (): AddInterface => ({
text: '',
error: '',
}),
methods: {
tryThis() {
this.$emit('enlarge-text');
},
submit() {
this.$emit('enlarge-text');
},
},
});
</script>
</code></pre>
<p>How should this be done? Is there something I've missed?</p>
<p>I was wondering can I still use <code>$emit</code> here?</p>
| 0 | 1,073 |
PrimeFaces nested form inside p:dialog with appendTo="@(body)
|
<p>I have this fragment:</p>
<pre><code><h:form id="form">
<!-- other content -->
<p:panel id="panel" header="test">
<p:inputText id="input1" value="#{viewScope.prop1}" required="true" />
<p:commandButton id="button1" process="@form" update="@form @widgetVar(dialog)"
oncomplete="PF('dialog').show()" value="ok" />
</p:panel>
<!-- other content -->
</h:form>
<p:dialog id="dialog" header="dialog" widgetVar="dialog" modal="true">
<h:form id="form2">
<p:inputText id="input2" value="#{viewScope.prop1}" required="true" />
<p:commandButton id="button2" process="@form" update="@form" value="ok" />
</h:form>
</p:dialog>
</code></pre>
<p>and all is working as expected.</p>
<p>What I'd like to achieve is this:</p>
<pre><code><h:form id="form">
<!-- other content -->
<!-- fragment start -->
<!-- this fragment will be on its own file and included via ui:include (or inside composite component) -->
<p:panel id="panel" header="test">
<p:inputText id="input1" value="#{viewScope.prop1}" required="true" />
<p:commandButton id="button1" process="@form" update="@form @widgetVar(dialog)"
oncomplete="PF('dialog').show()" value="ok" />
</p:panel>
<p:dialog id="dialog" header="dialog" widgetVar="dialog" modal="true" appendTo="@(body)">
<h:form id="form2">
<p:inputText id="input2" value="#{viewScope.prop1}" required="true" />
<p:commandButton id="button2" process="@form" update="@form" value="ok" />
</h:form>
</p:dialog>
<!-- fragment end -->
<!-- other content -->
</h:form>
</code></pre>
<p>but I unsuccessfully tried some combination of <code>process</code> and <code>update</code> for <code>button1</code> resulting in process anything... <code>input1</code> is even resetting...</p>
<p>So, how to build a <code>p:dialog</code> that can be shipped inside a fragment or a composite comp and that is excluded from outside <code>form</code>?</p>
<p>Note that using:</p>
<pre><code><h:form id="form">
<!-- other content -->
<ui:include src="panel.xhtml" />
<!-- other content -->
</h:form>
<ui:include src="dialog.xhtml" />
</code></pre>
<p>is not an acceptable solution.</p>
<p>I'm on JSF 2.2.8 (mojarra) and PF 5.1</p>
| 0 | 1,129 |
Kernel install gives missing module error
|
<p>I'm installing a linux kernel from 3.14 to 3.19 and when I run the command:</p>
<pre><code>make O=$BUILD install
</code></pre>
<p>I get the several error messages saying that there is no lib/module directory. Before this I already compiled the kernel and copied the bzImage that was created into boot, along with system.map and .config.</p>
<pre><code> update-initramfs: Generating /boot/initrd.img-3.19.0
WARNING: missing /lib/modules/3.19.0
Device driver support needs thus be built-in linux image!
depmod: ERROR: could not open directory /lib/modules/3.19.0: No such file or directory
depmod: FATAL: could not search modules: No such file or directory
depmod: WARNING: could not open /tmp/mkinitramfs_6tPRIQ/lib/modules /3.19.0/modules.order: No such file or directory
depmod: WARNING: could not open /tmp/mkinitramfs_6tPRIQ/lib/modules /3.19.0/modules.builtin: No such file or directory
run-parts: executing /etc/kernel/postinst.d/pm-utils 3.19.0 /boot/vmlinuz-3.19.0
run-parts: executing /etc/kernel/postinst.d/update-notifier 3.19.0 /boot/vmlinuz-3.19.0
run-parts: executing /etc/kernel/postinst.d/zz-update-grub 3.19.0 /boot/vmlinuz-3.19.0
Generating grub configuration file ...
Warning: Setting GRUB_TIMEOUT to a non-zero value when GRUB_HIDDEN_TIMEOUT is set is no longer supported.
</code></pre>
<p>How can I fix it? </p>
<p>EDIT: ls /</p>
<pre><code>bin dev initrd.img lost+found opt run sys var
boot etc lib media proc sbin tmp vmlinuz
cdrom home lib64 mnt root srv usr
</code></pre>
<p>EDIT 2:</p>
<pre><code>ls -l /lib/
total 296
drwxr-xr-x 2 root root 4096 feb 21 10:41 apparmor
drwxr-xr-x 2 root root 4096 jul 23 2014 brltty
lrwxrwxrwx 1 root root 21 feb 20 13:04 cpp -> /etc/alternatives/cpp
drwxr-xr-x 3 root root 4096 jul 23 2014 crda
drwxr-xr-x 61 root root 20480 feb 21 10:43 firmware
drwxr-xr-x 2 root root 4096 jul 23 2014 hdparm
drwxr-xr-x 2 root root 4096 jul 23 2014 ifupdown
drwxr-xr-x 2 root root 4096 jul 23 2014 init
-rwxr-xr-x 1 root root 71512 dec 24 2013 klibc-P2s_k- gf23VtrGgO2_4pGkQgwMY.so
lrwxrwxrwx 1 root root 17 feb 20 13:04 libip4tc.so.0 -> libip4tc.so.0.1.0
-rw-r--r-- 1 root root 27392 jan 8 2014 libip4tc.so.0.1.0
lrwxrwxrwx 1 root root 17 feb 20 13:04 libip6tc.so.0 -> libip6tc.so.0.1.0
-rw-r--r-- 1 root root 31520 jan 8 2014 libip6tc.so.0.1.0
lrwxrwxrwx 1 root root 16 feb 20 13:04 libiptc.so.0 -> libiptc.so.0.0.0
-rw-r--r-- 1 root root 5816 jan 8 2014 libiptc.so.0.0.0
lrwxrwxrwx 1 root root 20 feb 20 13:04 libxtables.so.10 -> libxtables.so.10.0.0
-rw-r--r-- 1 root root 47712 jan 8 2014 libxtables.so.10.0.0
drwxr-xr-x 2 root root 4096 jul 23 2014 linux-sound-base
drwxr-xr-x 3 root root 4096 jul 22 2014 lsb
drwxr-xr-x 2 root root 4096 apr 10 2014 modprobe.d
drwxr-xr-x 3 root root 4096 jul 23 2014 modules
drwxr-xr-x 2 root root 4096 jul 23 2014 modules-load.d
drwxr-xr-x 3 root root 4096 feb 21 10:41 plymouth
drwxr-xr-x 3 root root 4096 jul 23 2014 recovery-mode
drwxr-xr-x 2 root root 4096 jul 23 2014 resolvconf
drwxr-xr-x 4 root root 4096 feb 21 10:41 systemd
drwxr-xr-x 15 root root 4096 mar 22 2014 terminfo
drwxr-xr-x 4 root root 4096 feb 21 10:45 udev
drwxr-xr-x 2 root root 4096 jul 23 2014 ufw
drwxr-xr-x 4 root root 12288 feb 21 10:42 x86_64-linux-gnu
drwxr-xr-x 2 root root 4096 jul 23 2014 xtables
</code></pre>
| 0 | 1,517 |
PyTorch: Add validation error in training
|
<p>I am using PyTorch to train a cnn model. Here is my Network architecture:</p>
<pre><code>import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 5)
self.pool = nn.MaxPool2d(2,2)
self.conv1_bn = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 64, 5)
self.conv2_drop = nn.Dropout2d()
self.conv2_bn = nn.BatchNorm2d(64)
self.fc1 = torch.nn.Linear(53*53*64, 256)
self.fc2 = nn.Linear(256, 136)
def forward(self, x):
x = F.relu(self.conv1_bn(self.pool(self.conv1(x))))
x = F.relu(self.conv2_bn(self.pool(self.conv2_drop(self.conv2(x)))))
x = x.view(-1, 53*53*64)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return x
</code></pre>
<p>Then I train the model like below:</p>
<pre><code># prepare the net for training
net.train()
for epoch in range(n_epochs): # loop over the dataset multiple times
running_loss = 0.0
# train on batches of data, assumes you already have train_loader
for batch_i, data in enumerate(train_loader):
# get the input images and their corresponding labels
images = data['image']
key_pts = data['keypoints']
# flatten pts
key_pts = key_pts.view(key_pts.size(0), -1)
# wrap them in a torch Variable
images, key_pts = Variable(images), Variable(key_pts)
# convert variables to floats for regression loss
key_pts = key_pts.type(torch.FloatTensor)
images = images.type(torch.FloatTensor)
# forward pass to get outputs
output_pts = net(images)
# calculate the loss between predicted and target keypoints
loss = criterion(output_pts, key_pts)
# zero the parameter (weight) gradients
optimizer.zero_grad()
# backward pass to calculate the weight gradients
loss.backward()
# update the weights
optimizer.step()
# print loss statistics
running_loss += loss.data[0]
</code></pre>
<p>I am wondering if it is possible to add the validation error in the training? I mean something like this (validation split) in <code>Keras</code>:</p>
<pre><code>myModel.fit(trainX, trainY, epochs=50, batch_size=1, verbose=2, validation_split = 0.1)
</code></pre>
| 0 | 1,272 |
Using the switch statement in a Windows Forms application
|
<p>And I'm doing some exercises about switch. I just did it from console application and I would like to do it in window forms applications. I'm looking for syntax on how to do switch in window forms.
In console it's usually like this:</p>
<pre><code>switch (wordValue)
{
case 1:
Console.WriteLine("You have entered numbered two");
break;
default:
break;
</code></pre>
<p>how can I do this in my window forms, if I would like to display this cases in listbox1?</p>
<p>Thanks</p>
<p>=======</p>
<p>Thank you. I tried this one but I'm getting an error. This is what I've tried:</p>
<pre><code> public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listbox.Items.Add("You have entered number one");
break;
}
}
</code></pre>
<p>========</p>
<p>This is the code I'm trying to do:</p>
<pre><code> private void btnOk_Click(object sender, EventArgs e)
{
string strUserInputNumber;
strUserInputNumber = textBox1.Text.Trim();
Int32 intNumber;
if (Int32.TryParse(textBox1.Text, out intNumber))
{
listBox1.Items.Add(intNumber.ToString());
}
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
this.listBox1.Items.Add("You have entered numbered one");
break;
}
}
</code></pre>
<p>====</p>
<p>This is the new code:</p>
<pre><code> private void btnOk_Click(object sender, EventArgs e)
{
string strUserInputNumber;
strUserInputNumber = textBox1.Text.Trim();
Int32 intNumber;
if (Int32.TryParse(textBox1.Text, out intNumber))
{
listBox1.Items.Add(intNumber.ToString());
WriteNumber(intNumber);
}
else
{
MessageBox.Show("Please enter an integer not a character");
}
}
public void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listBox2.Items.Add("You have entered numbered one");
break;
case 2:
listBox2.Items.Add("You have entered numbered two");
break;
case 3:
listBox2.Items.Add("You have entered numbered three");
break;
default:
listBox2.Items.Add("You have exceeded the range of 1-3. Please enter the number between 1-3");
break;
}
</code></pre>
| 0 | 1,216 |
Apply Style to Android ListView
|
<p>I want to style the lisview in my application as seen is this image </p>
<p><img src="https://i.stack.imgur.com/CEaJK.jpg" alt="Expected Output"></p>
<p>I have tried to develop it by applying gradient :</p>
<p>code for list_item_normal is :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:centerColor="#E6E6E6"
android:endColor="#CCCCCC"
android:startColor="#FFFFFF"
android:angle="270"/>
<!--
<gradient
android:startColor="#FF7500"
android:centerColor="#FFCC00"
android:endColor="#FF7500"
android:angle="270"/>
-->
<stroke
android:width="1dp"
android:color="#A0000000" />
<padding
android:bottom="8dp"
android:left="5dp"
android:right="5dp"
android:top="8dp" />
<corners android:radius="5dp" />
</shape>
</code></pre>
<p>code for list_item_pressed.xml is :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:centerColor="#E6E6E6"
android:endColor="#CCCCCC"
android:startColor="#FFFFFF" android:angle="270"/>
<!--
<gradient android:startColor="#FF66CFE6" android:centerColor="#FF207FB9"
android:endColor="#FF0060B8" android:angle="270"/>
-->
<stroke
android:width="2dp"
android:color="#80000000" />
<padding
android:bottom="8dp"
android:left="5dp"
android:right="5dp"
android:top="8dp" />
<corners android:radius="7dp" />
</shape>
</code></pre>
<p>code for list_item_pressed.xml :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:centerColor="#E6E6E6"
android:endColor="#CCCCCC"
android:startColor="#FFFFFF" android:angle="270"/>
<!--
<gradient android:startColor="#FF66CFE6" android:centerColor="#FF207FB9"
android:endColor="#FF0060B8" android:angle="270"/>
-->
<stroke
android:width="2dp"
android:color="#80000000" />
<padding
android:bottom="8dp"
android:left="5dp"
android:right="5dp"
android:top="8dp" />
<corners android:radius="7dp" />
</shape>
</code></pre>
<p>and list_gradient.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/list_item_pressed" />
<item android:state_focused="true"
android:drawable="@drawable/list_item_selected" />
<item android:drawable="@drawable/list_item_normal" />
</selector>
</code></pre>
<p>and i have applied this style on <code>custom listitem</code> like :</p>
<p>
</p>
<pre><code><TextView
.../>
<ImageView
... />
</code></pre>
<p></p>
<p>and the main.xml in which i have lisview is :</p>
<p>
</p>
<pre><code><ListView
android:id="@+id/List"
style="@style/list_item_gradient"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:clickable="true" >
</ListView>
</code></pre>
<p></p>
<p>and i am getting output as shown below :</p>
<p><img src="https://i.stack.imgur.com/wR2as.png" alt="current output"></p>
<p>Please help me by telling what i am doing wrong..</p>
<p>Thanks
Shruti</p>
| 0 | 1,788 |
Updating Node & NPM VS Cordova update 5
|
<p>I just download the VS Apache Cordova Tools Update 5 and I'm running into problems with Node and NPM. I am using the default blank cordova project for testing.</p>
<p><strong>Versions</strong></p>
<p>If I run a gulp check for Node and NPM within my VS Project I get: <code>Node version = v0.10.31</code> and <code>NPM version = 1.4.9</code>. However, I also have installed <code>Node version = v5.4.1</code> and <code>NPM version = 3.3.6</code></p>
<p><strong>Problem</strong></p>
<p>When I publish using Cordova CLI 5.3.3 I get the following error
<a href="https://i.stack.imgur.com/AZkcd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AZkcd.png" alt="enter image description here"></a>
When I change the Cordova CLI to 5.4.1 I get the following error:
<a href="https://i.stack.imgur.com/ynY64.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ynY64.png" alt="enter image description here"></a></p>
<p>If I change the Tools > Options > Projects and Solutions > External Web Tools and add the path <code>C:\Program Files (x86)\nodejs</code> I get the following warning and an <code>npm install failed</code> error. </p>
<pre><code>npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm
</code></pre>
<p><strong>Other</strong></p>
<p>If I select <code>use global installed version</code> I get 5.2.0.
<a href="https://i.stack.imgur.com/77Dac.png" rel="noreferrer"><img src="https://i.stack.imgur.com/77Dac.png" alt="enter image description here"></a></p>
<p>Any help is greatly appreciated!</p>
<p>Download location and update info for VS Cordova Tools 5
<a href="http://microsoft.github.io/vstacoblog/2016/01/13/annoucing-update-5.html" rel="noreferrer">http://microsoft.github.io/vstacoblog/2016/01/13/annoucing-update-5.html</a></p>
<p>---------------------------Update 1/15/2015 4:50PMEST--------------------------</p>
<p>Here's the build log when publishing blank cordova project with node = <code>5.4.1</code> using <code>node-v5.4.1-x86.msi</code> and NPM = <code>3.5.3</code> installed using package.json.</p>
<pre><code>1>------ Build started: Project: BlankCordovaApp4, Configuration: Debug Android ------
1> Your environment has been set up for using Node.js 5.4.1 (ia32) and npm.
1> ------ Ensuring correct global installation of package from source package directory: C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\EXTENSIONS\APACHECORDOVATOOLS\packages\vs-tac
1> ------ Name from source package.json: vs-tac
1> ------ Version from source package.json: 1.0.28
1> ------ Package already installed globally at correct version.
1> ------ Installing Cordova tools cordova@5.4.1 for project from npm. This could take a few minutes...
1> Each package is licensed to you by its owner. Microsoft is not responsible for, nor does it grant any licenses to, third-party packages. Some packages may include dependencies which are governed by additional licenses. Follow the package source (feed) URL to determine any dependencies.
1> npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm
1> npm ERR! Windows_NT 6.3.9600
1> npm ERR! argv "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Users\\DBiele\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" "cordova@5.4.1" "--loglevel" "warn"
1> npm ERR! node v5.4.1
1> npm ERR! npm v3.3.6
1>
1> npm ERR! Cannot read property 'localeCompare' of undefined
1> npm ERR!
1>MDAVSCLI : npm ERR! If you need help, you may report this error at:
1> npm ERR! <https://github.com/npm/npm/issues>
1>
1> npm ERR! Please include the following file with any support request:
1> npm ERR! C:\Users\DBiele\AppData\Roaming\npm\node_modules\vs-tac\node_modules\cordova\5.4.1\npm-debug.log
1> [Error: ------ npm install failed. Exit code: 1]
1> C:\Users\DBiele\AppData\Roaming\npm\node_modules\vs-tac\node_modules\q\q.js:126
1> throw e;
1> ^
1>
1>MDAVSCLI : error : ------ npm install failed. Exit code: 1
1> at ChildProcess.<anonymous> (C:\Users\DBiele\AppData\Roaming\npm\node_modules\vs-tac\lib\util.js:655:29)
1> at emitTwo (events.js:87:13)
1> at ChildProcess.emit (events.js:172:7)
1> at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
</code></pre>
<p>Here's another build log after removing <code>NPM 3.5.3</code> , <code>clearing cordova cache</code> and <code>npm cache clean</code></p>
<pre><code>1>------ Build started: Project: BlankCordovaApp4, Configuration: Debug Android ------
1> Your environment has been set up for using Node.js 5.4.1 (ia32) and npm.
1> ------ Ensuring correct global installation of package from source package directory: C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\EXTENSIONS\APACHECORDOVATOOLS\packages\vs-tac
1> ------ Name from source package.json: vs-tac
1> ------ Version from source package.json: 1.0.28
1> ------ Package not currently installed globally.
1> ------ Installing globally from source package. This could take a few minutes...
1> Each package is licensed to you by its owner. Microsoft is not responsible for, nor does it grant any licenses to, third-party packages. Some packages may include dependencies which are governed by additional licenses. Follow the package source (feed) URL to determine any dependencies.
1> npm WARN deprecated npmconf@0.1.16: this package has been reintegrated into npm and is now out of date with respect to npm
1> npm WARN engine npm@1.3.4: wanted: {"node":">=0.6","npm":"1"} (current: {"node":"5.4.1","npm":"3.3.6"})
1> C:\Users\DBiele\AppData\Roaming\npm\vs-tac-cli -> C:\Users\DBiele\AppData\Roaming\npm\node_modules\vs-tac\vs-tac-cli.cmd
1> > edge@4.0.0 install C:\Users\DBiele\AppData\Roaming\npm\node_modules\vs-tac\node_modules\edge
1> > node tools/install.js
1> ***************************************
1> [Error: The edge module has not been pre-compiled for node.js version v5.4.1. You must build a custom version of edge.node. Please refer to https://github.com/tjanczuk/edge for building instructions.]
1> ***************************************
1> Success: platform check for edge.js: node.js ia32 v5.4.1
1> C:\Users\DBiele\AppData\Roaming\npm
1> └─┬ vs-tac@1.0.28
1> ├── adm-zip@0.4.4
1> ├─┬ edge@4.0.0
1> │ ├── edge-cs@0.2.7
1> │ └── nan@2.2.0
1> ├─┬ elementtree@0.1.6
1> │ └── sax@0.3.5
1> ├─┬ fstream@0.1.28
1> │ ├── graceful-fs@3.0.8
1> │ └── inherits@2.0.1
1> ├── mkdirp@0.3.5
1> ├── ncp@0.5.1
1> ├─┬ optimist@0.6.1
1> │ ├── minimist@0.0.10
1> │ └── wordwrap@0.0.3
1> ├─┬ plugman@0.22.4
1> │ ├─┬ cordova-lib@0.21.6
1> │ │ ├── bplist-parser@0.0.5
1> │ │ ├─┬ cordova-js@3.6.2
1> │ │ │ ├─┬ browserify@3.46.0
1> │ │ │ │ ├─┬ assert@1.1.1
1> │ │ │ │ │ └── util@0.10.2
1> │ │ │ │ ├─┬ browser-pack@2.0.1
1> │ │ │ │ │ ├─┬ combine-source-map@0.3.0
1> │ │ │ │ │ │ ├── convert-source-map@0.3.4
1> │ │ │ │ │ │ ├── inline-source-map@0.3.0
1> │ │ │ │ │ │ └─┬ source-map@0.1.34
1> │ │ │ │ │ │ └── amdefine@0.1.0
1> │ │ │ │ │ └─┬ JSONStream@0.6.4
1> │ │ │ │ │ ├── jsonparse@0.0.5
1> │ │ │ │ │ └── through@2.2.7
1> │ │ │ │ ├── browser-resolve@1.2.4
1> │ │ │ │ ├─┬ browserify-zlib@0.1.4
1> │ │ │ │ │ └── pako@0.2.3
1> │ │ │ │ ├─┬ buffer@2.1.13
1> │ │ │ │ │ ├── base64-js@0.0.7
1> │ │ │ │ │ └── ieee754@1.1.3
1> │ │ │ │ ├── builtins@0.0.4
1> │ │ │ │ ├── commondir@0.0.1
1> │ │ │ │ ├─┬ concat-stream@1.4.6
1> │ │ │ │ │ ├─┬ readable-stream@1.1.13-1
1> │ │ │ │ │ │ ├── core-util-is@1.0.1
1> │ │ │ │ │ │ ├── isarray@0.0.1
1> │ │ │ │ │ │ └── string_decoder@0.10.25-1
1> │ │ │ │ │ └── typedarray@0.0.6
1> │ │ │ │ ├── console-browserify@1.0.3
1> │ │ │ │ ├── constants-browserify@0.0.1
1> │ │ │ │ ├── crypto-browserify@1.0.9
1> │ │ │ │ ├── deep-equal@0.1.2
1> │ │ │ │ ├── defined@0.0.0
1> │ │ │ │ ├─┬ deps-sort@0.1.2
1> │ │ │ │ │ ├─┬ JSONStream@0.6.4
1> │ │ │ │ │ │ ├── jsonparse@0.0.5
1> │ │ │ │ │ │ └── through@2.2.7
1> │ │ │ │ │ └── minimist@0.0.10
1> │ │ │ │ ├─┬ derequire@0.8.0
1> │ │ │ │ │ ├── esprima-fb@3001.1.0-dev-harmony-fb
1> │ │ │ │ │ ├─┬ esrefactor@0.1.0
1> │ │ │ │ │ │ ├── escope@0.0.16
1> │ │ │ │ │ │ ├── esprima@1.0.4
1> │ │ │ │ │ │ └── estraverse@0.0.4
1> │ │ │ │ │ └── estraverse@1.5.0
1> │ │ │ │ ├── domain-browser@1.1.2
1> │ │ │ │ ├── duplexer@0.1.1
1> │ │ │ │ ├── events@1.0.1
1> │ │ │ │ ├─┬ glob@3.2.11
1> │ │ │ │ │ └─┬ minimatch@0.3.0
1> │ │ │ │ │ ├── lru-cache@2.5.0
1> │ │ │ │ │ └── sigmund@1.0.0
1> │ │ │ │ ├─┬ http-browserify@1.3.2
1> │ │ │ │ │ └── Base64@0.2.1
1> │ │ │ │ ├── https-browserify@0.0.0
1> │ │ │ │ ├── inherits@2.0.1
1> │ │ │ │ ├─┬ insert-module-globals@5.0.1
1> │ │ │ │ │ ├─┬ lexical-scope@1.1.0
1> │ │ │ │ │ │ └─┬ astw@1.1.0
1> │ │ │ │ │ │ └── esprima-fb@3001.1.0-dev-harmony-fb
1> │ │ │ │ │ └── process@0.6.0
1> │ │ │ │ ├─┬ JSONStream@0.7.4
1> │ │ │ │ │ └── jsonparse@0.0.5
1> │ │ │ │ ├─┬ module-deps@1.10.0
1> │ │ │ │ │ ├─┬ detective@3.1.0
1> │ │ │ │ │ │ ├─┬ escodegen@1.1.0
1> │ │ │ │ │ │ │ ├── esprima@1.0.4
1> │ │ │ │ │ │ │ ├── estraverse@1.5.0
1> │ │ │ │ │ │ │ ├── esutils@1.0.0
1> │ │ │ │ │ │ │ └─┬ source-map@0.1.34
1> │ │ │ │ │ │ │ └── amdefine@0.1.0
1> │ │ │ │ │ │ └── esprima-fb@3001.1.0-dev-harmony-fb
1> │ │ │ │ │ └── minimist@0.0.10
1> │ │ │ │ ├── os-browserify@0.1.2
1> │ │ │ │ ├── parents@0.0.2
1> │ │ │ │ ├── path-browserify@0.0.0
1> │ │ │ │ ├── punycode@1.2.4
1> │ │ │ │ ├── querystring-es3@0.2.0
1> │ │ │ │ ├── resolve@0.6.3
1> │ │ │ │ ├── shallow-copy@0.0.1
1> │ │ │ │ ├── shell-quote@0.0.1
1> │ │ │ │ ├─┬ stream-browserify@0.1.3
1> │ │ │ │ │ └── process@0.5.2
1> │ │ │ │ ├── stream-combiner@0.0.4
1> │ │ │ │ ├── string_decoder@0.0.1
1> │ │ │ │ ├─┬ subarg@0.0.1
1> │ │ │ │ │ └── minimist@0.0.10
1> │ │ │ │ ├─┬ syntax-error@1.1.0
1> │ │ │ │ │ └── esprima-fb@3001.1.0-dev-harmony-fb
1> │ │ │ │ ├─┬ through2@0.4.2
1> │ │ │ │ │ ├─┬ readable-stream@1.0.27-1
1> │ │ │ │ │ │ ├── core-util-is@1.0.1
1> │ │ │ │ │ │ ├── isarray@0.0.1
1> │ │ │ │ │ │ └── string_decoder@0.10.25-1
1> │ │ │ │ │ └─┬ xtend@2.1.2
1> │ │ │ │ │ └── object-keys@0.4.0
1> │ │ │ │ ├─┬ timers-browserify@1.0.1
1> │ │ │ │ │ └── process@0.5.2
1> │ │ │ │ ├── tty-browserify@0.0.0
1> │ │ │ │ ├─┬ umd@2.0.0
1> │ │ │ │ │ ├─┬ rfile@1.0.0
1> │ │ │ │ │ │ ├── callsite@1.0.0
1> │ │ │ │ │ │ └── resolve@0.3.1
1> │ │ │ │ │ └─┬ ruglify@1.0.0
1> │ │ │ │ │ └─┬ uglify-js@2.2.5
1> │ │ │ │ │ ├─┬ optimist@0.3.7
1> │ │ │ │ │ │ └── wordwrap@0.0.2
1> │ │ │ │ │ └─┬ source-map@0.1.34
1> │ │ │ │ │ └── amdefine@0.1.0
1> │ │ │ │ ├── url@0.10.1
1> │ │ │ │ ├── util@0.10.3
1> │ │ │ │ └─┬ vm-browserify@0.0.4
1> │ │ │ │ └── indexof@0.0.1
1> │ │ │ ├── through@2.3.4
1> │ │ │ └─┬ uglify-js@2.4.14
1> │ │ │ ├── async@0.2.10
1> │ │ │ ├─┬ optimist@0.3.7
1> │ │ │ │ └── wordwrap@0.0.2
1> │ │ │ ├─┬ source-map@0.1.34
1> │ │ │ │ └── amdefine@0.1.0
1> │ │ │ └── uglify-to-browserify@1.0.2
1> │ │ ├─┬ dep-graph@1.1.0
1> │ │ │ └── underscore@1.2.1
1> │ │ ├─┬ elementtree@0.1.5
1> │ │ │ └── sax@0.3.5
1> │ │ ├─┬ glob@3.2.11
1> │ │ │ ├── inherits@2.0.1
1> │ │ │ └─┬ minimatch@0.3.0
1> │ │ │ ├── lru-cache@2.5.0
1> │ │ │ └── sigmund@1.0.0
1> │ │ ├── mime@1.2.11
1> │ │ ├─┬ npm@1.3.4
1> │ │ │ ├── ini@1.1.0
1> │ │ │ ├─┬ minimatch@0.2.12
1> │ │ │ │ └── sigmund@1.0.0
1> │ │ │ ├── mkdirp@0.3.5
1> │ │ │ ├── osenv@0.0.3
1> │ │ │ └─┬ request@2.21.0
1> │ │ │ ├── aws-sign@0.3.0
1> │ │ │ ├── cookie-jar@0.3.0
1> │ │ │ ├─┬ form-data@0.0.8
1> │ │ │ │ └─┬ combined-stream@0.0.4
1> │ │ │ │ └── delayed-stream@0.0.5
1> │ │ │ ├─┬ hawk@0.13.1
1> │ │ │ │ ├─┬ boom@0.4.2
1> │ │ │ │ │ └── hoek@0.9.1
1> │ │ │ │ ├── hoek@0.8.5
1> │ │ │ │ └─┬ sntp@0.2.4
1> │ │ │ │ └── hoek@0.9.1
1> │ │ │ ├─┬ http-signature@0.9.11
1> │ │ │ │ ├── asn1@0.1.11
1> │ │ │ │ ├── assert-plus@0.1.2
1> │ │ │ │ └── ctype@0.5.2
1> │ │ │ ├── json-stringify-safe@4.0.0
1> │ │ │ ├── oauth-sign@0.3.0
1> │ │ │ └── tunnel-agent@0.3.0
1> │ │ ├─┬ npmconf@0.1.16
1> │ │ │ ├─┬ config-chain@1.1.8
1> │ │ │ │ └── proto-list@1.2.3
1> │ │ │ ├── inherits@2.0.1
1> │ │ │ ├── ini@1.1.0
1> │ │ │ ├── mkdirp@0.3.5
1> │ │ │ ├─┬ nopt@2.2.1
1> │ │ │ │ └── abbrev@1.0.5
1> │ │ │ └── once@1.3.0
1> │ │ ├── osenv@0.0.3
1> │ │ ├─┬ plist-with-patches@0.5.1
1> │ │ │ ├── xmlbuilder@0.4.3
1> │ │ │ └── xmldom@0.1.19
1> │ │ ├── properties-parser@0.2.3
1> │ │ ├── q@0.9.7
1> │ │ ├─┬ rc@0.3.0
1> │ │ │ ├── deep-extend@0.2.10
1> │ │ │ ├── ini@1.1.0
1> │ │ │ └─┬ optimist@0.3.7
1> │ │ │ └── wordwrap@0.0.2
1> │ │ ├─┬ request@2.22.0
1> │ │ │ ├── aws-sign@0.3.0
1> │ │ │ ├── cookie-jar@0.3.0
1> │ │ │ ├── forever-agent@0.5.2
1> │ │ │ ├─┬ form-data@0.0.8
1> │ │ │ │ ├── async@0.2.10
1> │ │ │ │ └─┬ combined-stream@0.0.4
1> │ │ │ │ └── delayed-stream@0.0.5
1> │ │ │ ├─┬ hawk@0.13.1
1> │ │ │ │ ├─┬ boom@0.4.2
1> │ │ │ │ │ └── hoek@0.9.1
1> │ │ │ │ ├── cryptiles@0.2.2
1> │ │ │ │ ├── hoek@0.8.5
1> │ │ │ │ └─┬ sntp@0.2.4
1> │ │ │ │ └── hoek@0.9.1
1> │ │ │ ├─┬ http-signature@0.10.0
1> │ │ │ │ ├── asn1@0.1.11
1> │ │ │ │ ├── assert-plus@0.1.2
1> │ │ │ │ └── ctype@0.5.2
1> │ │ │ ├── json-stringify-safe@4.0.0
1> │ │ │ ├── node-uuid@1.4.1
1> │ │ │ ├── oauth-sign@0.3.0
1> │ │ │ ├── qs@0.6.6
1> │ │ │ └── tunnel-agent@0.3.0
1> │ │ ├── semver@2.0.11
1> │ │ ├── shelljs@0.1.4
1> │ │ ├─┬ tar@0.1.19
1> │ │ │ ├── block-stream@0.0.7
1> │ │ │ ├─┬ fstream@0.1.27
1> │ │ │ │ ├── graceful-fs@3.0.2
1> │ │ │ │ ├── mkdirp@0.3.5
1> │ │ │ │ └── rimraf@2.2.8
1> │ │ │ └── inherits@2.0.1
1> │ │ ├── underscore@1.4.4
1> │ │ └─┬ xcode@0.6.6
1> │ │ ├── node-uuid@1.3.3
1> │ │ └── pegjs@0.6.2
1> │ ├─┬ nopt@1.0.10
1> │ │ └── abbrev@1.0.7
1> │ ├─┬ npm@1.3.4
1> │ │ ├─┬ cmd-shim@1.1.0
1> │ │ │ └── graceful-fs@1.2.3
1> │ │ ├── ini@1.1.0
1> │ │ ├─┬ minimatch@0.2.12
1> │ │ │ └── sigmund@1.0.0
1> │ │ ├── mkdirp@0.3.5
1> │ │ ├── osenv@0.0.3
1> │ │ ├─┬ read-installed@0.2.2
1> │ │ │ └── graceful-fs@1.2.3
1> │ │ ├─┬ read-package-json@1.1.0
1> │ │ │ └── graceful-fs@1.2.3
1> │ │ ├─┬ request@2.21.0
1> │ │ │ ├── aws-sign@0.3.0
1> │ │ │ ├── cookie-jar@0.3.0
1> │ │ │ ├─┬ form-data@0.0.8
1> │ │ │ │ └─┬ combined-stream@0.0.4
1> │ │ │ │ └── delayed-stream@0.0.5
1> │ │ │ ├─┬ hawk@0.13.1
1> │ │ │ │ ├─┬ boom@0.4.2
1> │ │ │ │ │ └── hoek@0.9.1
1> │ │ │ │ ├── hoek@0.8.5
1> │ │ │ │ └─┬ sntp@0.2.4
1> │ │ │ │ └── hoek@0.9.1
1> │ │ │ ├─┬ http-signature@0.9.11
1> │ │ │ │ ├── asn1@0.1.11
1> │ │ │ │ ├── assert-plus@0.1.2
1> │ │ │ │ └── ctype@0.5.2
1> │ │ │ ├── json-stringify-safe@4.0.0
1> │ │ │ ├── oauth-sign@0.3.0
1> │ │ │ └── tunnel-agent@0.3.0
1> │ │ ├─┬ rimraf@2.2.0
1> │ │ │ └── graceful-fs@1.2.3
1> │ │ └─┬ sha@1.0.1
1> │ │ └── graceful-fs@1.2.3
1> │ ├── q@0.9.7
1> │ ├─┬ rc@0.3.0
1> │ │ ├── deep-extend@0.2.11
1> │ │ ├── ini@1.1.0
1> │ │ └── optimist@0.3.7
1> │ └── underscore@1.4.4
1> ├── q@1.0.1
1> ├─┬ request@2.36.0
1> │ ├── aws-sign2@0.5.0
1> │ ├── forever-agent@0.5.2
1> │ ├─┬ form-data@0.1.4
1> │ │ ├── async@0.9.2
1> │ │ └─┬ combined-stream@0.0.7
1> │ │ └── delayed-stream@0.0.5
1> │ ├─┬ hawk@1.0.0
1> │ │ ├── boom@0.4.2
1> │ │ ├── cryptiles@0.2.2
1> │ │ ├── hoek@0.9.1
1> │ │ └── sntp@0.2.4
1> │ ├─┬ http-signature@0.10.1
1> │ │ ├── asn1@0.1.11
1> │ │ ├── assert-plus@0.1.5
1> │ │ └── ctype@0.5.3
1> │ ├── json-stringify-safe@5.0.1
1> │ ├── mime@1.2.11
1> │ ├── node-uuid@1.4.7
1> │ ├── oauth-sign@0.3.0
1> │ ├── qs@0.6.6
1> │ ├── tough-cookie@2.2.1
1> │ └── tunnel-agent@0.4.2
1> ├── rimraf@2.2.6
1> ├─┬ ripple-emulator@0.9.32
1> │ ├── accounting@0.4.1
1> │ ├── colors@0.6.0-1
1> │ ├── connect-xcors@0.5.2
1> │ ├─┬ express@3.1.0
1> │ │ ├── buffer-crc32@0.1.1
1> │ │ ├── commander@0.6.1
1> │ │ ├─┬ connect@2.7.2
1> │ │ │ ├── bytes@0.1.0
1> │ │ │ ├── formidable@1.0.11
1> │ │ │ ├── pause@0.0.1
1> │ │ │ └── qs@0.5.1
1> │ │ ├── cookie@0.0.5
1> │ │ ├── cookie-signature@0.0.1
1> │ │ ├─┬ debug@2.2.0
1> │ │ │ └── ms@0.7.1
1> │ │ ├── fresh@0.1.0
1> │ │ ├── methods@0.0.1
1> │ │ ├── mkdirp@0.3.3
1> │ │ ├── range-parser@0.0.4
1> │ │ └─┬ send@0.1.0
1> │ │ └── mime@1.2.6
1> │ ├── moment@1.7.2
1> │ ├── open@0.0.3
1> │ └─┬ request@2.12.0
1> │ └─┬ form-data@0.0.3
1> │ └─┬ combined-stream@0.0.3
1> │ └── delayed-stream@0.0.5
1> ├── semver@2.3.1
1> └─┬ tar@0.1.20
1> └── block-stream@0.0.8
1> ------ npm install of vs-tac@1.0.28 from C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\EXTENSIONS\APACHECORDOVATOOLS\packages\vs-tac completed.
1> ------ Installing Cordova tools cordova@5.4.1 for project from npm. This could take a few minutes...
1> Each package is licensed to you by its owner. Microsoft is not responsible for, nor does it grant any licenses to, third-party packages. Some packages may include dependencies which are governed by additional licenses. Follow the package source (feed) URL to determine any dependencies.
1> npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm
1> npm ERR! Windows_NT 6.3.9600
1> npm ERR! argv "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Users\\DBiele\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" "cordova@5.4.1" "--loglevel" "warn"
1> npm ERR! node v5.4.1
1> npm ERR! npm v3.3.6
1>
1> npm ERR! Cannot read property 'localeCompare' of undefined
1> npm ERR!
1>MDAVSCLI : npm ERR! If you need help, you may report this error at:
1> npm ERR! <https://github.com/npm/npm/issues>
1>
1> npm ERR! Please include the following file with any support request:
1> npm ERR! C:\Users\DBiele\AppData\Roaming\npm\node_modules\vs-tac\node_modules\cordova\5.4.1\npm-debug.log
1> [Error: ------ npm install failed. Exit code: 1]
1> C:\Users\DBiele\AppData\Roaming\npm\node_modules\vs-tac\node_modules\q\q.js:126
1> throw e;
1> ^
1>
1>MDAVSCLI : error : ------ npm install failed. Exit code: 1
1> at ChildProcess.<anonymous> (C:\Users\DBiele\AppData\Roaming\npm\node_modules\vs-tac\lib\util.js:655:29)
1> at emitTwo (events.js:87:13)
1> at ChildProcess.emit (events.js:172:7)
1> at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========
</code></pre>
<p>When I use powershell or cmd to install cordova <code>npm install -g cordova</code> I get the following error</p>
<pre><code>C:\Users\DBiele>npm install -g cordova
npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm a
nd is now out of date with respect to npm
npm WARN install:isarray ENOENT: no such file or directory, rename 'C:\Users\DBi
ele\AppData\Roaming\npm\node_modules\cordova\node_modules\buffer\node_modules\is
array' -> 'C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules
\buffer\node_modules\isarray'
npm WARN install:negotiator ENOENT: no such file or directory, rename 'C:\Users\
DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\express\node_module
s\negotiator' -> 'C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\node_
modules\express\node_modules\negotiator'
npm WARN install:vary ENOENT: no such file or directory, rename 'C:\Users\DBiele
\AppData\Roaming\npm\node_modules\cordova\node_modules\express\node_modules\vary
' -> 'C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\expr
ess\node_modules\vary'
npm WARN install:object-assign ENOENT: no such file or directory, rename 'C:\Use
rs\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\got\node_modules
\object-assign' -> 'C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\nod
e_modules\got\node_modules\object-assign'
npm WARN install:convert-source-map ENOENT: no such file or directory, rename 'C
:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\insert-modu
le-globals\node_modules\convert-source-map' -> 'C:\Users\DBiele\AppData\Roaming\
npm\node_modules\cordova\node_modules\insert-module-globals\node_modules\convert
-source-map'
npm WARN install:graceful-fs ENOENT: no such file or directory, rename 'C:\Users
\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\write-file-atomic\
node_modules\graceful-fs' -> 'C:\Users\DBiele\AppData\Roaming\npm\node_modules\c
ordova\node_modules\read-package-json\node_modules\graceful-fs'
npm WARN install:deep-extend ENOENT: no such file or directory, rename 'C:\Users
\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\registry-url\node_
modules\deep-extend' -> 'C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordov
a\node_modules\registry-url\node_modules\deep-extend'
npm WARN install:strip-json-comments ENOENT: no such file or directory, rename '
C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\registry-u
rl\node_modules\strip-json-comments' -> 'C:\Users\DBiele\AppData\Roaming\npm\nod
e_modules\cordova\node_modules\registry-url\node_modules\strip-json-comments'
npm WARN install:mime-types ENOENT: no such file or directory, rename 'C:\Users\
DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\request\node_module
s\mime-types' -> 'C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\node_
modules\request\node_modules\mime-types'
npm WARN install:qs ENOENT: no such file or directory, rename 'C:\Users\DBiele\A
ppData\Roaming\npm\node_modules\cordova\node_modules\request\node_modules\qs' ->
'C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\request\
node_modules\qs'
isarray@1.0.0 node_modules\cordova\node_modules\buffer\node_modules\isarray -> n
ode_modules\cordova\node_modules\buffer\node_modules\isarray
negotiator@0.5.3 node_modules\cordova\node_modules\express\node_modules\negotiat
or -> node_modules\cordova\node_modules\express\node_modules\negotiator
accepts@1.2.13 node_modules\cordova\node_modules\express\node_modules\accepts ->
node_modules\cordova\node_modules\express\node_modules\accepts
vary@1.0.1 node_modules\cordova\node_modules\express\node_modules\vary -> node_m
odules\cordova\node_modules\express\node_modules\vary
object-assign@3.0.0 node_modules\cordova\node_modules\got\node_modules\object-as
sign -> node_modules\cordova\node_modules\got\node_modules\object-assign
convert-source-map@1.1.3 node_modules\cordova\node_modules\insert-module-globals
\node_modules\convert-source-map -> node_modules\cordova\node_modules\insert-mod
ule-globals\node_modules\convert-source-map
graceful-fs@4.1.2 node_modules\cordova\node_modules\write-file-atomic\node_modul
es\graceful-fs -> node_modules\cordova\node_modules\read-package-json\node_modul
es\graceful-fs
deep-extend@0.4.0 node_modules\cordova\node_modules\registry-url\node_modules\de
ep-extend -> node_modules\cordova\node_modules\registry-url\node_modules\deep-ex
tend
strip-json-comments@1.0.4 node_modules\cordova\node_modules\registry-url\node_mo
dules\strip-json-comments -> node_modules\cordova\node_modules\registry-url\node
_modules\strip-json-comments
mime-types@1.0.2 node_modules\cordova\node_modules\request\node_modules\mime-typ
es -> node_modules\cordova\node_modules\request\node_modules\mime-types
qs@2.3.3 node_modules\cordova\node_modules\request\node_modules\qs -> node_modul
es\cordova\node_modules\request\node_modules\qs
readable-stream@1.0.33 node_modules\cordova\node_modules\cordova-lib\node_module
s\request\node_modules\bl\node_modules\readable-stream -> node_modules\cordova\n
ode_modules\browser-pack\node_modules\readable-stream
bl@0.9.4 node_modules\cordova\node_modules\cordova-lib\node_modules\request\node
_modules\bl -> node_modules\cordova\node_modules\bl
request@2.47.0 node_modules\cordova\node_modules\cordova-lib\node_modules\reques
t -> node_modules\cordova\node_modules\request
npmconf@2.1.2 node_modules\cordova\node_modules\cordova-lib\node_modules\npmconf
-> node_modules\cordova\node_modules\npmconf
glob@4.0.6 node_modules\cordova\node_modules\cordova-lib\node_modules\glob -> no
de_modules\cordova\node_modules\glob
tar@1.0.2 node_modules\cordova\node_modules\cordova-lib\node_modules\tar -> node
_modules\cordova\node_modules\tar
- C:\Users\DBiele\AppData\Roaming\npm\node_modules\cordova\node_modules\write-fi
le-atomic node_modules\cordova\node_modules\write-file-atomic
C:\Users\DBiele\AppData\Roaming\npm
└── (empty)
npm ERR! code 1
</code></pre>
<p>-------------------------------Update 2 1/15/2016------------------------
It now appears to be working! I used Michael Braude's comment to <code>npm -g install npm</code> and it works. </p>
<p>However, before the fix I did the following: </p>
<ol>
<li>removed Node using <code>add and remove programs</code></li>
<li>removed NPM by deleting the NPM folder in roaming. </li>
<li>Repaired VS2015</li>
</ol>
<p>After using <code>npm -g install npm</code> I updated <code>node</code> to <code>5.4.1 - 64 bit</code>, I also checked to make sure NPM 3.5.4 worked and used <code>npm -g install npm@3.5.4</code> and it worked. </p>
<p>In addition, I changed the sandboxed (I think?) version of Node and NPM by adding <code>C:\Program Files (x86)\nodejs</code> to Tools > Options > Projects and Solutions > External Web Tools <a href="https://i.stack.imgur.com/04tjv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/04tjv.png" alt="enter image description here"></a></p>
<p>I am now able to run my gulp task using <code>Task Runner Explorer</code> without getting errors. Crossing fingers that it continues to work!</p>
| 0 | 13,410 |
C - realloc error: corrupted size vs prev_size
|
<p>Could someone please explain the error?<br>
I was getting the error until, on a whim, I changed the line from:</p>
<pre><code>char *tmp = realloc(str, sizeof(char)*length);
// to added 1
char *tmp = realloc(str, sizeof(char) * length + 1);
</code></pre>
<p>I thought that multiplying <code>sizeof(char)</code> by length would reallocate a new memory area of <code>size=sizeof(char)*length</code>. I'm not understanding why adding 1 fixes the problem.</p>
<pre><code> void edit_print(char *inputStr, size_t space_size) {
size_t ch_position = 0;
size_t space_column_count = 0;
size_t num_spaces_left = 0;
while ((inputStr[ch_position] != '\0')) {
if ((inputStr[ch_position] == '\t') && (space_size !=0)) {
num_spaces_left = (space_size-(space_column_count % space_size));
if (ch_position == 0 || !(num_spaces_left)) {
for (size_t i=1; i <= space_size; i++) {
putchar(' ');
space_column_count++;
}
ch_position++;
} else {
for (size_t i=1; i <= num_spaces_left; i++) {
putchar(' ');
space_column_count++;
}
ch_position++;
}
} else {
putchar(inputStr[ch_position++]);
space_column_count++;
}
}
printf("\n");
}
int main(int argc, char *argv[]) {
size_t space_size_arg = 3;
int inputch;
size_t length = 0;
size_t size = 10;
char *str = realloc(NULL, sizeof(char) * size);
printf("Enter stuff\n");
while ((inputch = getchar()) != EOF) {
if (inputch == '\n') {
str[length++] = '\0';
//changed line below
char *tmp = realloc(str, sizeof(char) * length + 1);
if (tmp == NULL) {
exit(0);
} else {
str = tmp;
}
edit_print(str, space_size_arg);
length = 0;
} else {
str[length++] = inputch;
if (length == size) {
char *tmp = realloc(str, sizeof(char) * (size += 20));
if (tmp == NULL) {
exit(0);
} else {
str = tmp;
}
}
}
}
free(str);
return 0;
}
</code></pre>
<p>EDIT: the error message I original got was the one in the heading of this post. After making the changes suggested by chux, the error is "realloc(): invalid next size: *hexnumber**"</p>
| 0 | 1,422 |
How to make radio inputs required?
|
<p>I have radio inputs in a form for the user to select their gender. How do I make gender a required input (user must select either female or male or they get a prompt as per the usual <code>required</code>).</p>
<p>I tried adding <code>required</code> as shown below but it doesn't work (user can continue without selecting either female or male).</p>
<pre><code> <div class="form-group btn-group" data-toggle="buttons">
<label class="btn btn-default btn-lg">
<input type="radio" name="gender" value="Female" required><i class="fa fa-female"></i> Female
</label>
<label class="btn btn-default btn-lg">
<input type="radio" name="gender" value="Male" required><i class="fa fa-male"></i> Male
</label>
</div>
</code></pre>
<h2>Update 1</h2>
<p>As suggested in the answers I updated the code so that only one radio input contains <code>required</code> however it still doesn't work.</p>
<pre><code> <div class="form-group btn-group" data-toggle="buttons">
<label class="btn btn-default btn-lg">
<input type="radio" name="gender" value="Female" required><i class="fa fa-female"></i> Female
</label>
<label class="btn btn-default btn-lg">
<input type="radio" name="gender" value="Male"><i class="fa fa-male"></i> Male
</label>
</div>
</code></pre>
<h2>Update 2</h2>
<p>As requested here is the complete code:</p>
<pre><code> <form action="/client/index.php" method="post" role="form">
<fieldset>
<div class="form-group">
<input class="form-control input-lg" placeholder="Nickname" name="nickname" type="text" autofocus required>
</div>
<div class="form-group btn-group" data-toggle="buttons">
<label class="btn btn-default btn-lg">
<input type="radio" name="gender" value="Female" required><i class="fa fa-female"></i> Female
</label>
<label class="btn btn-default btn-lg">
<input type="radio" name="gender" value="Male"><i class="fa fa-male"></i> Male
</label>
</div>
<h4>Options</h4>
<div class="form-group">
<div class="row">
<div class="col-md-6">
Block private chats
</div>
<div class="col-md-6">
<input type="checkbox" name="block" data-on-text="Yes" data-off-text="No">
</div>
</div>
</div>
<button type="submit" name="submit" class="btn btn-lg btn-primary btn-block">Start</button>
</fieldset>
</form>
</code></pre>
| 0 | 1,687 |
Retrofit - I/art: Background sticky concurrent mark sweep GC freed
|
<p>I'm trying to make a simple REST request with Retrofit and i'm getting a lot of GC errors. I really don't know how to fix it. I tried to put more memory on emulator but the problem still happens. when make sync call <code>Response<List<User>> response = usersCall.execute();</code>
following exception</p>
<pre><code> java.lang.RuntimeException: An error occurred while executing doInBackground()
android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Cause by: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 2 path $
at com.google.gson.stream.JsonReader.nextString(JsonReader.java:831)
at com.google.gson.internal.bind.TypeAdapters$16.read(TypeAdapters.java:422)
at com.google.gson.internal.bind.TypeAdapters$16.read(TypeAdapters.java:410)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:116)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
</code></pre>
<p>and sync call using pojo model <code>Response<List<User>> response = usersCall.execute();</code> then</p>
<pre><code>04-09 07:37:23.897 13396-13411/? I/art: Clamp target GC heap from 111MB to 96MB
04-09 07:37:23.897 13396-13411/? I/art: Background partial concurrent mark sweep GC freed 3104(48KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 95MB/96MB, paused 7.520ms total 194.127ms
04-09 07:37:23.897 13396-13396/? I/art: WaitForGcToComplete blocked for 182.909ms for cause Alloc
04-09 07:37:23.929 13396-13411/? I/art: Background sticky concurrent mark sweep GC freed 128(5KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 95MB/96MB, paused 8.237ms total 31.761ms
04-09 07:37:23.929 13396-13396/? I/art: WaitForGcToComplete blocked for 18.171ms for cause Alloc
04-09 07:37:24.130 13396-13411/? I/art: Clamp target GC heap from 111MB to 96MB
04-09 07:37:24.130 13396-13411/? I/art: Background partial concurrent mark sweep GC freed 5784(90KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 95MB/96MB, paused 9.388ms total 200.412ms
04-09 07:37:24.130 13396-13396/? I/art: WaitForGcToComplete blocked for 200.758ms for cause Alloc
04-09 07:37:24.158 13396-13411/? I/art: Background sticky concurrent mark sweep GC freed 1710(34KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 95MB/96MB, paused 6.897ms total 27.286ms
04-09 07:37:24.158 13396-13396/? I/art: WaitForGcToComplete blocked for 18.297ms for cause Alloc
04-09 07:37:24.346 13396-13396/? I/art: Clamp target GC heap from 111MB to 96MB
04-09 07:37:24.346 13396-13396/? I/art: Alloc partial concurrent mark sweep GC freed 2092(33KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 95MB/96MB, paused 5.943ms total 188.191ms
04-09 07:37:24.370 13396-13396/? I/art: Alloc sticky concurrent mark sweep GC freed 0(0B) AllocSpace objects, 0(0B) LOS objects, 0% free, 95MB/96MB, paused 8.501ms total 23.440ms
04-09 07:37:24.566 13396-13396/? I/art: Clamp target GC heap from 111MB to 96MB
04-09 07:37:24.566 13396-13396/? I/art: Alloc concurrent mark sweep GC freed 9(12KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 95MB/96MB, paused 6.105ms total 195.296ms
04-09 07:37:24.566 13396-13411/? I/art: WaitForGcToComplete blocked for 395.241ms for cause Background
04-09 07:37:24.598 13396-13411/? I/art: Background sticky concurrent mark sweep GC freed 0(0B) AllocSpace objects, 0(0B) LOS objects, 0% free, 95MB/96MB, paused 6.138ms total 29.195ms
04-09 07:37:24.598 13396-13396/? I/art: WaitForGcToComplete blocked for 29.063ms for cause Alloc
04-09 07:37:24.775 13396-13396/? I/art: Clamp target GC heap from 111MB to 96MB
04-09 07:37:24.775 13396-13396/? I/art: Alloc partial concurrent mark sweep GC freed 16(56KB) AllocSpace objects, 1(54KB) LOS objects, 0% free, 95MB/96MB, paused 6.803ms total 177.429ms
</code></pre>
<p>My code:</p>
<pre><code>Gson gson =
new GsonBuilder()
.registerTypeAdapter(Usuario.class, new UsuarioDeserializer())
.registerTypeAdapter(Date.class, new CustomDateDeserializer())
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ConstantesUtil.URL_BASE)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
UsuariosAPI usuarioApi = retrofit.create(UsuariosAPI.class);
Usuario usuario = new Usuario(login, senha);
Call<List<Usuario>> usuarios = usuarioApi.getUsuarios(usuario);
usuarios.enqueue(new Callback<List<Usuario>>() {
@Override
public void onResponse(Call<List<Usuario>> call, Response<List<Usuario>> response) {
List<Usuario> usuarios = response.body();
for (Usuario u: usuarios) {
Log.i(TAG, u.getNome());
}
}
@Override
public void onFailure(Call<List<Usuario>> call, Throwable t) {
}
});
</code></pre>
| 0 | 2,346 |
'NSGenericException', reason: Collection <__NSArrayM: 0x7fabb400> was mutated while being enumerated
|
<p>In my iPhone app,i am trying to implement a image gallery using uicollectionView .when <20 images stores in gallery its working fine but when i am storing multiple image(greater than 20) app crashes.please help me.thanks in advance.</p>
<p>Error:</p>
<pre><code>Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x7fabb400> was mutated while being enumerated.'
*** First throw call stack:
(
0 CoreFoundation 0x042ea946 __exceptionPreprocess + 182
1 libobjc.A.dylib 0x03660a97 objc_exception_throw + 44
2 CoreFoundation 0x042ea1e6 __NSFastEnumerationMutationHandler + 166
3 CoreFoundation 0x041da052 -[NSArray containsObject:] + 178
4 AtSceneDebug 0x001ce9a9 -[GalleryCollectionViewController loadImageFromAppSupport:] + 201
5 AtSceneDebug 0x001c5de2 __73-[GalleryCollectionViewController collectionView:cellForItemAtIndexPath:]_block_invoke + 98
6 libdispatch.dylib 0x03cca30a _dispatch_call_block_and_release + 15
7 libdispatch.dylib 0x03ceae2f _dispatch_client_callout + 14
8 libdispatch.dylib 0x03cd310f _dispatch_root_queue_drain + 634
9 libdispatch.dylib 0x03cd487e _dispatch_worker_thread2 + 45
10 libsystem_pthread.dylib 0x04056dab _pthread_wqthread + 336
11 libsystem_pthread.dylib 0x0405acce start_wqthread + 30
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code></pre>
<p>Code:</p>
<pre><code>GalleryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GalleryCollectionViewCellID" forIndexPath:indexPath];
if(indexPath.row==0)
{
Photo *photo=[self.photoSource.photos objectAtIndex:indexPath.row];
cell.selectionImageView.hidden=YES;
[cell.galleryImageView setImage:[UIImage imageNamed:[photo.mURLLarge lastPathComponent]]];
return cell;
}
Photo *photo=[self.photoSource.photos objectAtIndex:indexPath.row];
if(self.mItemType==ITEM_TYPE_PHOTO)
{
NSLog(@"index of coll.......%d",indexPath.row);
UIImage *image = [_imageCache objectForKey:photo.mURLThumb];
if(image)
{
//[cell.galleryImageView setImage:[self loadImageFromAppSupport:photo.mURLLarge]];
[cell.galleryImageView setImage:image];
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = [self loadImageFromAppSupport:photo.mURLThumb];
if(image)
{
dispatch_async(dispatch_get_main_queue(), ^{
GalleryCollectionViewCell *cell =(GalleryCollectionViewCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
if(cell)
{
cell.galleryImageView.image = image;
}
});
[_imageCache setObject:image forKey:photo.mURLThumb];
}
});
}
}
else
{
[cell.galleryImageView setImage:[self loadImageFromAppSupport:photo.mURLThumb]];
}
if(indexPath.row==0)
{
cell.selectionImageView.hidden=YES;
}
else if(self.isEditing && photo.isMarkedForDeletion && indexPath.row!=0)
{
cell.selectionImageView.hidden=NO;
[cell.selectionImageView setImage:[UIImage imageNamed:@"red_led"]];
}
else if (self.isEditing && !photo.isMarkedForDeletion && indexPath.row!=0)
{
//[cell.selectionImageView setImage:[UIImage imageNamed:@"green_led"]];
cell.selectionImageView.hidden=YES;
}
else if(!self.isEditing && photo.isMarkedForDeletion && indexPath.row!=0)
{
cell.selectionImageView.hidden=YES;
}
else if(!self.isEditing && !photo.isMarkedForDeletion && indexPath.row!=0)
{
cell.selectionImageView.hidden=YES;
}
if (!self.isEditing)
{
CGFloat xx=cell.frame.origin.x;
CGFloat yy=cell.frame.origin.y;
CGRect frame = cell.frame;
frame.origin.x = 500; // new x coordinate
frame.origin.y = 0; // new y coordinate
cell.frame = frame;
[UIView animateWithDuration:0.0 animations:^{
CGRect frame = cell.frame;
frame.origin.x = xx; // new x coordinate
frame.origin.y = yy; // new y coordinate
cell.frame = frame;
}];
}
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
</code></pre>
| 0 | 2,286 |
Webview in Scrollview
|
<p>I have to place WebView into ScrollView. But I have to put some views into the same scrollview before webview. So it looks like this:</p>
<pre><code><ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:id="@+id/articleDetailPageContentLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/articleDetailRubricLine"
android:layout_width="fill_parent"
android:layout_height="3dip"
android:background="@color/fashion"/>
<ImageView
android:id="@+id/articleDetailImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitStart"
android:src="@drawable/article_detail_image_test"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:text="PUBLISH DATE"/>
<WebView
android:id="@+id/articleDetailContentView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/fashion"
android:isScrollContainer="false"/>
</LinearLayout>
</code></pre>
<p></p>
<p>I'm getting some HTML info from backend. It has no any body or head tags, just data surrounded by <code><p></code> or <code><h4></code> or some other tags. Also it has <code><img></code> tags in there. Sometimes pictures are too wide for current screen width. So I added some css in the begining of HTML. So I loads data to webview like this:</p>
<pre><code>private final static String WEBVIEW_MIME_TYPE = "text/html";
private final static String WEBVIEW_ENCODING = "utf-8";
String viewport = "<head><meta name=\"viewport\" content=\"target-densitydpi=device-dpi\" /></head>";
String css = "<style type=\"text/css\">" +
"img {width: 100%;}" +
"</style>";
articleContent.loadDataWithBaseURL("http://", viewport + css + articleDetail.getContent(), WEBVIEW_MIME_TYPE,
WEBVIEW_ENCODING, "about:blank");
</code></pre>
<p>Sometimes when page loaded, scrollview scrolls to place where webview begins. And I don't know how to fix that.</p>
<p>Also, sometimes there is huge white empty space appears after webview content. I also don't know what to do with that.</p>
<p>Sometimes scrollview's scrollbars starts twitch randomly while I scrolling...</p>
<p>I know that it's not right to place webview into scrollview, but it seems like I have no other choise. Could anyone suggest rigth way to place all views and all HTML content to webview?</p>
| 0 | 1,027 |
Fast prime factorization module
|
<p>I am looking for an <strong>implementation</strong> or <strong>clear algorithm</strong> for getting the prime factors of <em>N</em> in either python, pseudocode or anything else well-readable. There are a few requirements/constraints:</p>
<ul>
<li><em>N</em> is between 1 and ~20 digits</li>
<li>No pre-calculated lookup table, memoization is fine though</li>
<li>Need not to be mathematically proven (e.g. could rely on the Goldbach conjecture if needed)</li>
<li>Need not to be precise, is allowed to be probabilistic/deterministic if needed</li>
</ul>
<p>I need a fast prime factorization algorithm, not only for itself, but for usage in many other algorithms like calculating the Euler <em>phi(n)</em>.</p>
<p>I have tried other algorithms from Wikipedia and such but either I couldn't understand them (ECM) or I couldn't create a working implementation from the algorithm (Pollard-Brent).</p>
<p>I am really interested in the Pollard-Brent algorithm, so any more information/implementations on it would be really nice.</p>
<p>Thanks!</p>
<p><strong>EDIT</strong></p>
<p>After messing around a little I have created a pretty fast prime/factorization module. It combines an optimized trial division algorithm, the Pollard-Brent algorithm, a miller-rabin primality test and the fastest primesieve I found on the internet. gcd is a regular Euclid's GCD implementation (binary Euclid's GCD is <strong>much</strong> slower then the regular one).</p>
<h1>Bounty</h1>
<p>Oh joy, a bounty can be acquired! But how can I win it?</p>
<ul>
<li>Find an optimization or bug in my module.</li>
<li>Provide alternative/better algorithms/implementations.</li>
</ul>
<p>The answer which is the most complete/constructive gets the bounty.</p>
<p>And finally the module itself:</p>
<pre><code>import random
def primesbelow(N):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
#""" Input N>=6, Returns a list of primes, 2 <= p < N """
correction = N % 6 > 1
N = {0:N, 1:N-1, 2:N+4, 3:N+3, 4:N+2, 5:N+1}[N%6]
sieve = [True] * (N // 3)
sieve[0] = False
for i in range(int(N ** .5) // 3 + 1):
if sieve[i]:
k = (3 * i + 1) | 1
sieve[k*k // 3::2*k] = [False] * ((N//6 - (k*k)//6 - 1)//k + 1)
sieve[(k*k + 4*k - 2*k*(i%2)) // 3::2*k] = [False] * ((N // 6 - (k*k + 4*k - 2*k*(i%2))//6 - 1) // k + 1)
return [2, 3] + [(3 * i + 1) | 1 for i in range(1, N//3 - correction) if sieve[i]]
smallprimeset = set(primesbelow(100000))
_smallprimeset = 100000
def isprime(n, precision=7):
# http://en.wikipedia.org/wiki/Miller-Rabin_primality_test#Algorithm_and_running_time
if n < 1:
raise ValueError("Out of bounds, first argument must be > 0")
elif n <= 3:
return n >= 2
elif n % 2 == 0:
return False
elif n < _smallprimeset:
return n in smallprimeset
d = n - 1
s = 0
while d % 2 == 0:
d //= 2
s += 1
for repeat in range(precision):
a = random.randrange(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1: continue
for r in range(s - 1):
x = pow(x, 2, n)
if x == 1: return False
if x == n - 1: break
else: return False
return True
# https://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/
def pollard_brent(n):
if n % 2 == 0: return 2
if n % 3 == 0: return 3
y, c, m = random.randint(1, n-1), random.randint(1, n-1), random.randint(1, n-1)
g, r, q = 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = (pow(y, 2, n) + c) % n
k = 0
while k < r and g==1:
ys = y
for i in range(min(m, r-k)):
y = (pow(y, 2, n) + c) % n
q = q * abs(x-y) % n
g = gcd(q, n)
k += m
r *= 2
if g == n:
while True:
ys = (pow(ys, 2, n) + c) % n
g = gcd(abs(x - ys), n)
if g > 1:
break
return g
smallprimes = primesbelow(1000) # might seem low, but 1000*1000 = 1000000, so this will fully factor every composite < 1000000
def primefactors(n, sort=False):
factors = []
for checker in smallprimes:
while n % checker == 0:
factors.append(checker)
n //= checker
if checker > n: break
if n < 2: return factors
while n > 1:
if isprime(n):
factors.append(n)
break
factor = pollard_brent(n) # trial division did not fully factor, switch to pollard-brent
factors.extend(primefactors(factor)) # recurse to factor the not necessarily prime factor returned by pollard-brent
n //= factor
if sort: factors.sort()
return factors
def factorization(n):
factors = {}
for p1 in primefactors(n):
try:
factors[p1] += 1
except KeyError:
factors[p1] = 1
return factors
totients = {}
def totient(n):
if n == 0: return 1
try: return totients[n]
except KeyError: pass
tot = 1
for p, exp in factorization(n).items():
tot *= (p - 1) * p ** (exp - 1)
totients[n] = tot
return tot
def gcd(a, b):
if a == b: return a
while b > 0: a, b = b, a % b
return a
def lcm(a, b):
return abs((a // gcd(a, b)) * b)
</code></pre>
| 0 | 2,450 |
Post Base64 image to Mvc controller
|
<p>Consider this base64 encode image</p>
<pre><code><img src='data:image/Png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABICAYAAABhlHJbAAAABHNCSVQICAgIfAhkiAAAAAFzUkdCAK7OHOkAAAAEZ0FNQQAAsY8L/GEFAAAACXBIWXMAABVlAAAVZQGF3cVdAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABnNJREFUeF7tnFls3EQYx11ucQshClWbtb1LC4RLIARIHAXxgsQDCOWhJGs7mypIoII4BAIhsYAEWY+TlEo8FAQSQjxAuR54AnFUFHH0CQlEEWcaQhpKmx5poVWb8H3eb92Jd7Nre8a7a2d/0l9txvN99vw1HnvtGSsdqskYzu2ayb4A7dNN9oNm2E8qPW8fT5s71EOznDwYdxQ0x0s12LtXD248kaoFpFg8TisMX6Gb9t264dwHSR5PtEz7Mc10BrE92b6RnKLMLaGWulDPO+w3ryLoje8FMlG37As1094IQX/7k6RJqsl+wdNz2WDxVDXProWyGX8dv+qamFu34WQwbz1UPOIPTLec3+HfndXltQU9+P0qE1Vr9GzY+K2/MugACAfUd8q9Mslir4M+BMO+oXb52xpYaOLq1cUTyLziKVCIJvGVtmYMdlf4gTMZ4NkGpjq+NoeTwZ51k8EA+zS/AcaG5z13U0o2zy6FtoqO8ZNKpm/0AvgP350Z7SO1kHlTXJujalqB3vZApQCvSti1aT+pJGcOdUNbZZiHegtP308qBXCJfoL2k0q6+p1LYNzbwRkgoumca />
</code></pre>
<p>I would like to post this src to Mvc controller but getting null when post with ajax here is the post method.</p>
<pre><code> var file = document.getElementById("base64image").src;
var formdata = new FormData();
formdata.append("base64image", file);
$.ajax({
url: "http://localhost:26792/home/SaveImage",
type: "POST",
data: file
});
</code></pre>
<p><strong>Mvc Controller</strong></p>
<pre><code> [HttpPost]
public void SaveImage(Image file)
{
}
</code></pre>
<p>I think the datatype I am using is not valid for this please suggest me what can I do here.</p>
<p><a href="https://i.stack.imgur.com/Sy5RC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Sy5RC.png" alt="enter image description here"></a></p>
<p><strong>Full Html Code</strong></p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture &amp; display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<!-- A button for taking snaps -->
<form>
<input type=button id="takeshot" value="Take Snapshot" onClick="take_snapshot()">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
window.onload = function () {
setInterval(function () { take_snapshot() }, 5000);
}
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img id="base64image" src="' + data_uri + '"/>';
});
var file = document.getElementById("base64image").src;
var formdata = new FormData();
formdata.append("base64image", file);
$.ajax({
url: "http://localhost:26792/home/SaveImage",
type: "POST",
data: file
});
//var ajax = new XMLHttpRequest();
//ajax.addEventListener("load", function (event) { uploadcomplete(event); }, false);
//ajax.open("POST", "http://localhost:26792/home/SaveImage");
//ajax.send(formdata);
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>
</html>
</code></pre>
| 0 | 2,129 |
RuntimeException: Could not inflate Behavior subclass
|
<p>I new in android and I've troubles with <code>FloatingActionButton</code> behaivors</p>
<p>My custom behavoir class:</p>
<pre><code>public class ScrollingFABBehavior extends FloatingActionButton.Behavior {
private static final String TAG = "ScrollingFABBehavior";
public ScrollingFABBehavior(Context context, AttributeSet attrs,
Handler mHandler) {
super();
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child, View directTargetChild, View target,
int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
|| super.onStartNestedScroll(coordinatorLayout, child,
directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child, View target, int dxConsumed,
int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed,
dyConsumed, dxUnconsumed, dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
child.hide();
} else if (dyConsumed < 0 && child.getVisibility() == View.GONE) {
child.show();
}
}
@Override
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton
child, View target) {
super.onStopNestedScroll(coordinatorLayout, child, target);
}
}
</code></pre>
<p>Fragment XML:</p>
<p>...
</p>
<pre><code><android.support.design.widget.FloatingActionButton
android:id="@+id/share_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:contentDescription="@string/action_share"
android:elevation="@dimen/fab_elevation"
android:src="@drawable/ic_share"
app:layout_behavior=".ScrollingFABBehavior"/>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>RuntimeError when fragment inflate xml:</p>
<pre><code>07-14 08:52:43.904 30785-30785/com.example.xyzreader E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xyzreader, PID: 30785
android.view.InflateException: Binary XML file line #115: Could not inflate Behavior subclass com.example.xyzreader.ui.ScrollingFABBehavior
Caused by: java.lang.RuntimeException: Could not inflate Behavior subclass com.example.xyzreader.ui.ScrollingFABBehavior
at android.support.design.widget.CoordinatorLayout.parseBehavior(CoordinatorLayout.java:615)
at android.support.design.widget.CoordinatorLayout$LayoutParams.<init>(CoordinatorLayout.java:2652)
</code></pre>
<p>e.t.c</p>
<p>Whats wrong?</p>
| 0 | 1,541 |
Disable background when div popup
|
<p>What I am trying to do is to show a div as a pop-up when I push a button and disable the background.</p>
<p>My pop-up is working perfectly fine but the problem comes when I try to disable the background. To do this, I make use of the div called 'mask' which must to take up all the body. This div must be hidden at the beginning and to show it when somebody push the button.</p>
<p>The thing is that this div (mask) is shown all the time, since the beginning.</p>
<p>I have been trying to find a solution in internet and I found, among others, the following links:
<a href="https://stackoverflow.com/questions/18386548/css-disable-background-when-div-popup">CSS Disable background when div popup</a> and
<a href="https://stackoverflow.com/questions/17103723/disable-background-using-css-when-popup-appear">disable background using css when popup appear</a></p>
<p>The first one doesn't have a solution and the solution of the second one doesn't fix my problem.</p>
<p>This is my .jsp file:</p>
<pre><code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<link href="css/popup.css" rel="stylesheet" type="text/css">
<script src="js/jquery-2.1.0.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript" src="js/popup.js"></script>
</head>
<body>
<div id="pop">
<div id="close">X</div>
<div id="contentPop"></div>
</div>
<div id="mask">
<div id="page-wrap">
...
<a class="minibtn" onclick="show();">Show pop-up</a>
...
</div>
</div>
</body>
</html>
</code></pre>
<p>I have omitted all the code that it is alien to the pop-up and I have replaced it for "...". </p>
<p>The popup.css file: </p>
<pre><code>#mask{
z-index: 500;
position: fixed;
display: none; /* removes the element completely from the document, it doesn't take up any space. */
/* visibility: hidden; -- hides the element, but it still takes up space in the layout. */
background: transparent;
background-color: #ccc;
height: 100%;
width: 100%;
top: 0px;
left: 0px;
}
#pop {
z-index:2;
position:absolute;
border: 1px solid #333333;
text-align:center;
background:#ffffff;
}
#close {
float:right;
margin-right:5px;
cursor:pointer;
font:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
font-weight:bold;
color:#FFFFFF;
background-color:#666666;
width:12px;
position:relative;
margin-top:-1px;
text-align:center;
}
</code></pre>
<p>And the popup.js file: </p>
<pre><code>function show() {
// Show pop-up and disable background using #mask
$("#pop").fadeIn('slow');
$("#mask").fadeIn('slow');
// Load content.
$.post("contentPopup.html", function(data) {
$("#contentPop").html(data);
});
}
$(document).ready(function() {
// Hide pop-up and mask
$("#mask").hide();
$("#pop").hide();
// Size pop-up
var img_w = 600;
var img_h = 300;
// width and height in css.
$("#pop").css('width', img_w + 'px');
$("#pop").css('height', img_h + 'px');
// Get values from the browser window
var w = $(this).width();
var h = $(this).height();
// Centers the popup
w = (w / 2) - (img_w / 2);
h = (h / 2) - (img_h / 2);
$("#pop").css("left", w + "px");
$("#pop").css("top", h + "px");
// Function to close the pop-up
$("#close").click(function() {
$("#pop").fadeOut('slow');
$("#mask").fadeOut('slow');
});
});
</code></pre>
<p>Thank you very much for your time and help. If there is any doubt, just let me know and I will try to explain it in a better way.</p>
| 0 | 1,795 |
Bootstrap modal in React.js
|
<p>I need to open a Bootstrap Modal from clicking on a button in a Bootstrap navbar and other places (<strong>to show data for a component instance, ie. providing "editing" functionality</strong>), but I don't know how to accomplish this. Here is my code:</p>
<p><strong>EDIT: Code updated.</strong></p>
<pre><code>ApplicationContainer = React.createClass({
render: function() {
return (
<div className="container-fluid">
<NavBar />
<div className="row">
<div className="col-md-2">
<ScheduleEntryList />
</div>
<div className="col-md-10">
</div>
</div>
<ScheduleEntryModal />
</div>
);
}
});
NavBar = React.createClass({
render: function() {
return (
<nav className="navbar navbar-default navbar-fixed-top">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="#">
<span className="glyphicon glyphicon-eye-open"></span>
</a>
</div>
<form className="navbar-form navbar-left">
<button className="btn btn-primary" type="button" data-toggle="modal" data-target="#scheduleentry-modal">
<span className="glyphicon glyphicon-plus">
</span>
</button>
</form>
<ul className="nav navbar-nav navbar-right">
<li><a href="#"><span className="glyphicon glyphicon-user"></span> Username</a></li>
</ul>
</div>
</nav>
);
}
});
ScheduleEntryList = React.createClass({
getInitialState: function() {
return {data: []}
},
loadData: function() {
$.ajax({
url: "/api/tasks",
dataType: "json",
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, error) {
console.error("/api/tasks", status, error.toString());
}.bind(this)
});
},
componentWillMount: function() {
this.loadData();
setInterval(this.loadData, 20000);
},
render: function() {
items = this.state.data.map(function(item) {
return <ScheduleEntryListItem item={item}></ScheduleEntryListItem>;
});
return (
<div className="list-group">
<a className="list-group-item active">
<h5 className="list-group-item-heading">Upcoming</h5>
</a>
{items}
</div>
);
}
});
ScheduleEntryListItem = React.createClass({
openModal: function() {
$("#scheduleentry-modal").modal("show");
},
render: function() {
deadline = moment(this.props.item.deadline).format("MMM Do YYYY, h:mm A");
return (
<a className="list-group-item" href="#" onClick={this.openModal}>
<h5 className="list-group-item-heading">
{this.props.item.title}
</h5>
<small className="list-group-item-text">
{deadline}
</small>
</a>
);
}
});
Modal = React.createClass({
componentDidMount: function() {
$(this.getDOMNode())
.modal({backdrop: "static", keyboard: true, show: false});
},
componentWillUnmount: function() {
$(this.getDOMNode())
.off("hidden", this.handleHidden);
},
open: function() {
$(this.getDOMNode()).modal("show");
},
close: function() {
$(this.getDOMNode()).modal("hide");
},
render: function() {
return (
<div id="scheduleentry-modal" className="modal fade" tabIndex="-1">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">
<span>&times;</span>
</button>
<h4 className="modal-title">{this.props.title}</h4>
</div>
<div className="modal-body">
{this.props.children}
</div>
<div className="modal-footer">
<button type="button" className="btn btn-danger pull-left" data-dismiss="modal">Delete</button>
<button type="button" className="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
)
}
});
ScheduleEntryModal = React.createClass({
render: function() {
var modal = null;
modal = (
<Modal title="Add Schedule Entry">
<form className="form-horizontal">
<div className="form-group">
<label htmlFor="title" className="col-sm-2 control-label">Title</label>
<div className="col-sm-10">
<input id="title" className="form-control" type="text" placeholder="Title" ref="title" name="title"/>
</div>
</div>
<div className="form-group">
<label htmlFor="deadline" className="col-sm-2 control-label">Deadline</label>
<div className="col-sm-10">
<input id="deadline" className="form-control" type="datetime-local" ref="deadline" name="deadline"/>
</div>
</div>
<div className="form-group">
<label htmlFor="completed" className="col-sm-2 control-label">Completed</label>
<div className="col-sm-10">
<input id="completed" className="form-control" type="checkbox" placeholder="completed" ref="completed" name="completed"/>
</div>
</div>
<div className="form-group">
<label htmlFor="description" className="col-sm-2 control-label">Description</label>
<div className="col-sm-10">
<textarea id="description" className="form-control" placeholder="Description" ref="description" name="description"/>
</div>
</div>
</form>
</Modal>
);
return (
<div className="scheduleentry-modal">
{modal}
</div>
);
}
});
</code></pre>
<p>Other comments and improvements to the code are appreciated.</p>
| 0 | 4,524 |
Django REST-framework: Using serializer for simple ForeignKey-relationship
|
<p>I'm using the django REST-framework and try to map a simple foreign-key relationship to provide related data for further use, similar to the following request: </p>
<p><a href="https://stackoverflow.com/questions/38139378/using-reverse-relationships-with-django-rest-frameworks-serializer?rq=1][1]">Using reverse relationships with django-rest-framework's serializer</a></p>
<p>Instead of a result, I receive the following exception:</p>
<p><em>Got AttributeError when attempting to get a value for field <code>album_name</code> on serializer <code>AlbumSerializer</code>.
The serializer field might be named incorrectly and not match any attribute or key on the <code>int</code> instance.
Original exception text was: 'int' object has no attribute 'album_name'.</em></p>
<p><strong>Models:</strong></p>
<pre><code> class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
# album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ('album', 'order')
ordering = ['order']
def __unicode__(self):
return '%d: %s' % (self.order, self.title)
</code></pre>
<p><strong>Serializers:</strong></p>
<pre><code>class AlbumSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = ('id', 'album_name', 'artist' )
class TrackSerializer(serializers.ModelSerializer):
album_id = AlbumSerializer(many=False, read_only=True)
class Meta:
model = Track
fields = ('order', 'title', 'duration', 'album_id')
</code></pre>
<p><strong>View:</strong></p>
<pre><code>class TrackView(viewsets.ModelViewSet):
queryset = Track.objects.all().select_related('album')
serializer_class = serializers.TrackSerializer
</code></pre>
<p><strong>What I have tried so far:</strong> </p>
<ol>
<li>Serializing Albums with related tracks as nested serializers, using a reverse relationship => <strong>works</strong></li>
<li>Doing the work just for the TrackSerializer without nested Album => <strong>works</strong></li>
<li>Doing the work just for the AlbumSerializer => <strong>works</strong></li>
<li>Using the TrackSerializer as shown in the code-section but reducing the AlbumSerializer by every
field except for the primary key 'id' => <strong>works</strong> (but I would need the
whole data set of album)</li>
<li>Changed the nested Serializer to a many-relationship by setting <em>many=True</em>. => dumps, since the framework tries to iterate on all fields of AlbumSerializer. </li>
</ol>
<p>Since I'm running out of ideas and material to browse for I'm asking the question:
How to list all or single attributes (!= PrimaryKey) of Album for each Track in regards to my example.</p>
| 0 | 1,042 |
[Vue warn]:Property or method is not defined on the instance but referenced during render
|
<p>I use laravel 5.7 and vue 2.5.7, I just learned vue.js a few weeks ago, I'm following an advanced series to make a blog using laravel and vue on youtube. I thought I had followed what was done in the video correctly, there was nothing different other than the version of laravel and vue that I used with the one in the video.</p>
<p>this is the video: <a href="https://www.youtube.com/watch?v=hEjrUCEN3WY" rel="nofollow noreferrer">User CRUD - Build an Advanced Blog/CMS (Episode 12)</a>.</p>
<p>in one episode, we started using vue, and I immediately got an error like this:</p>
<blockquote>
<p>[Vue warn]: Property or method "autoPassword" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. (found in Root)</p>
</blockquote>
<p>I don't understand what's happening, but this is the code:</p>
<p><strong>app.js</strong></p>
<pre><code>require('./bootstrap');
window.Vue = require('vue');
import Buefy from 'buefy'
Vue.use(Buefy)
var app = new Vue({
el: '#app'
});
</code></pre>
<p><strong>layout.blade.php</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
@include('partials.meta-tags')
<title>Dashboard | Bulma CMS</title>
@include('partials.styles')
</head>
<body class="has-navbar-fixed-top">
<div id="app">
<header>
@include('partials.nav.top')
@include('partials.nav.side')
</header>
<main class="has-sidenav-fixed-left">
<div class="p-4">
@yield('content')
</div>
</main>
</div>
<script src="{{ asset('js/app.js') }}"></script>
@yield('scripts')
</body>
</html>
</code></pre>
<p><strong>users/create.blade.php</strong></p>
<pre><code>@extends('layout')
@section('content')
<div class="columns">
<div class="column">
<h1 class="title">Manage Users</h1>
<form action="{{ route('users.store') }}" method="POST" autocomplete="off">
@csrf
<div class="field">
<div class="control">
<input type="text" name="name" placeholder="Name" class="input" required />
</div>
</div>
<div class="field">
<div class="control">
<input type="email" name="email" placeholder="Email" class="input" required />
</div>
</div>
<div class="field">
<div class="control">
<input type="password" name="password" placeholder="Password" class="input" :disabled="autoPassword" required />
</div>
</div>
<div class="field">
<div class="control">
<b-checkbox name="auto_password" :checked="true" v-model="autoPassword">Auto Generate Password</b-checkbox>
</div>
</div>
<div class="field">
<div class="control">
<button class="button">Submit</button>
</div>
</div>
</form>
</div>
</div>
@endsection
@section('scripts')
<script>
var app = new Vue({
el: '#app',
data: {
autoPassword: true
}
});
</script>
@endsection
</code></pre>
<p>one more thing, I use buefy checkbox</p>
<pre><code><b-checkbox name="auto_password" :checked="true" v-model="autoPassword">Auto Generate Password</b-checkbox>
</code></pre>
<p>I added <code>:checked="true"</code> to be checked by default as in the video, but what I have is not checked by default.</p>
<p>can anyone help me?</p>
| 0 | 1,744 |
How to fix this bug using Kotlin,could not find Fragment constructor?
|
<p>I am developing <code>Android</code> app using Kotlin.In my app contains <code>Tab</code> with <code>ViewPager</code> so i implement the two tabs.when i move to another activity and compack to tab view activity the app getting fource stop and the <code>logcat</code> shows below the error.</p>
<blockquote>
<p>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crypto.wallet/com.crypto.wallet.activities.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.crypto.wallet.activities.ReceiveFragment: could not find Fragment constructor</p>
</blockquote>
<p><strong>MyFragment.kt</strong></p>
<pre><code>@SuppressLint("ValidFragment")
class ReceiveFragment(private val transactionList: List<TransactionEntity>, val appDatabase: AppDatabase, private val direction: TransactionAdapterDirection,
val networkDefinitionProvider: NetworkDefinitionProvider) : Fragment(){
private var linearLayoutManager: LinearLayoutManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.receive_fragment, container, false)
val recyclerView = rootView.findViewById<RecyclerView>(R.id.transaction_recycler_in) as RecyclerView
linearLayoutManager = LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false)
recyclerView.layoutManager = linearLayoutManager
recyclerView.adapter = TransactionRecyclerAdapter(transactionList,appDatabase,direction,networkDefinitionProvider)
recyclerView.setHasFixedSize(true);
return rootView
}
}
</code></pre>
<p><strong>ViewPager.kt</strong></p>
<pre><code>override fun getItem(position: Int): Fragment? {
var fragment: Fragment? = null
when (position) {
//0 -> fragment = ReceiveFragment(MytransactionList,MyappDatabase,Myincoming,MynetworkDefinitionProvider)
0 -> fragment = ReceiveFragment(MyIT,MyAppDatabase,MyIncoming,MyNetwork)
1 -> fragment = SendFragment()
}
return fragment
}
</code></pre>
<p><strong>Main.kt
OnCreate()</strong></p>
<pre><code>val viewPager = findViewById<ViewPager>(R.id.viewpager)
if (viewPager != null) {
val adapter = ViewPagerAdapter(supportFragmentManager,it,appDatabase,INCOMING,networkDefinitionProvider)
viewPager.adapter = adapter
}
val pref = applicationContext.getSharedPreferences("MyPref", 0) // 0 - for private mode
val editor = pref.edit()
val gson = Gson()
val json = gson.toJson(it)
editor.putString("MyObject", json)
editor.apply()
</code></pre>
<p><strong>OnResume()</strong></p>
<pre><code>val prefs = applicationContext.getSharedPreferences("MyPref", 0)
val gson = Gson()
val json = prefs.getString("MyObject", "")
val person1: List<TransactionEntity> = gson.fromJson(json, ArrayList<TransactionEntity>()::class.java)
</code></pre>
<p><strong>UPDATE:</strong>
After i tried this i get same error(i tried both Bundle and Shared pref):</p>
<pre><code>companion object {
@JvmStatic
fun newInstance(myIT: List<TransactionEntity>, myAppDatabase: AppDatabase, myIncoming: TransactionAdapterDirection,
myNetwork: NetworkDefinitionProvider,
bundle: Bundle) =
ReceiveFragment(myIT, myAppDatabase, myIncoming, myNetwork,bundle).apply {
arguments = Bundle().apply {
/* val prefs = getActivity()!!.getApplicationContext().getSharedPreferences("myPrefs", 0)
val gson = Gson()
val json = prefs.getString("MyObject", "")
val person1: List<TransactionEntity> = gson.fromJson(json,
ArrayList<TransactionEntity>()::class.java)
Log.d("Karthi", "Frag-GSON " + person1)*/
val dd = bundle.getSerializable("MySerializable")
Log.d("Karthi", "Frag-GSON " + dd)
}
}
}
</code></pre>
<p>Main.kt:</p>
<pre><code>val bundle = Bundle()
val gson_budle = Gson()
val json_bundle = gson_budle.toJson(it)
bundle.putSerializable("MySerializable", json_bundle)
val sharedPreferences = getSharedPreferences(myPreferences, Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
val gson = Gson()
val json = gson.toJson(it)
editor.putString("MyObject", json)
editor.putString("MyObject_json_bundle", json_bundle)
Log.d("Karthi","After - IT" + json)
Log.d("Karthi","After - IT" + json_bundle)
editor.apply()
</code></pre>
<blockquote>
<p>FATAL EXCEPTION: main
Process: com.crypto.wallet, PID: 29313
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crypto.wallet/com.crypto.wallet.activities.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.crypto.wallet.activities.ReceiveFragment: could not find Fragment constructor
at android.support.v4.app.FragmentController.restoreAllState(FragmentController.java:152)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:330)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84)
at com.crypto.wallet.activities.MainActivity.onCreate(MainActivity.kt:194)</p>
</blockquote>
| 0 | 2,811 |
Spring 3 validation not working
|
<p>I have a user entity in my application which I need to validate. </p>
<pre><code>public class User {
private String userName;
private String password;
public void setUserName(String userName){
this.userName = userName;
}
public getUserName(){
return this.userName;
}
// and so on
</code></pre>
<p>}</p>
<p>For this I have created a UsersValidator like below.</p>
<pre><code>public class UserValidator implements Validator {
public boolean supports(Class clazz) {
return User.class.equals(clazz);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "field.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required");
}
}
</code></pre>
<p>and I have a controller like this</p>
<pre><code>@RequestMapping(value = "/login", method = RequestMethod.POST)
public String home(@Valid User user,
BindingResult result) {
if (result.hasErrors()) {
return "loginForm";
} else {
//continue
}
}
</code></pre>
<p>The binding result does not have any errors. </p>
<p>What else I need to do in order for the validation to work? Do I have make any changes in the controller or the spring configuration file.</p>
<pre><code><mvc:annotation-driven />
<context:component-scan base-package="com.myapp" />
<mvc:resources location="/resources/" mapping="/resources/**" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.tiles2.TilesView</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>com/dimex/resourceBundles/ApplicationResources</value>
<value>com/dimex/resourceBundles/errors</value>
</list>
</property>
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="locale"></property>
</bean>
</mvc:interceptors>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
</code></pre>
<p><strong>EDIT:-</strong></p>
<p>Do I need to have hibernate validator in my classpath. We are not using hibernate in our application.
Please help.</p>
<p><strong>EDIT2:-</strong></p>
<p>When I use validation annotations (@NotNull, @Size etc) directly in my entity class then @Valid annotations in controller works but if I remove them from my entities and try to use the validator written above then @Valid does not work. </p>
<p>Is it like that @Valid annotations only work with the validation annotation in the entities only and not with the validators? In order to use my validators will I have to invoke the validate method in my validator directly?</p>
| 0 | 1,314 |
Navigating back to parent activity in ActionBar without handling Up button event
|
<p>I have two activities that I want this navigation to happen, they are VendorsActivity and QuestionsActivity. The following how my AndroidManifest.xml looks like:</p>
<p>(I am not using the full name of my activities like <code>com.hello.world.MyActivity</code> as I am defined <code>package</code> attribute in <code>manifest</code> node.)</p>
<p>
</p>
<pre><code><uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".VendorsActivity"
android:label="@string/vendors_activity_title" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TestsActivity"
android:label="@string/tests_activity_title"
android:parentActivityName=".VendorsActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".VendorsActivity" />
</activity>
<activity
android:name=".QuestionsActivity"
android:label="@string/questions_activity_title" >
</activity>
</application>
</code></pre>
<p></p>
<p>And in <code>TestsActivity</code>, I am calling <code>getActionBar().setDisplayHomeAsUpEnabled(true);</code> method from within <code>onCreate</code> method.</p>
<p>The problem is, it won't work unless I implement the following method in <code>.TestsActivity</code> class:</p>
<pre><code>@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
NavUtils.navigateUpFromSameTask(TestsActivity.this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>But Android Developer Guide says that I don't have to handle the Up button's event as mentioned at the very bottom of hit page: <a href="https://developer.android.com/training/basics/actionbar/adding-buttons.html" rel="noreferrer">https://developer.android.com/training/basics/actionbar/adding-buttons.html</a></p>
<blockquote>
<p>Because the system now knows MainActivity is the parent activity for
DisplayMessageActivity, when the user presses the Up button, the
system navigates to the parent activity as appropriate—you do not need
to handle the Up button's event.</p>
</blockquote>
<p><strong>Edit and Answer:</strong></p>
<p>As Android Developer Guide says:</p>
<blockquote>
<p>Beginning in Android 4.1 (API level 16), you can declare the logical
parent of each activity by specifying the android:parentActivityName
attribute in the element.</p>
<p>If your app supports Android 4.0 and lower, include the Support
Library with your app and add a element inside the
. Then specify the parent activity as the value for
android.support.PARENT_ACTIVITY, matching the
android:parentActivityName attribute.</p>
</blockquote>
<p>So I think my problem was because of two reasons:</p>
<ol>
<li><p>Running the app on a proper emulator. I was targeting a higher version but the emulator was running on API 14 (Android 4.0) so it didn't know how to handle <code>android:parentActivityName</code> attribute.</p></li>
<li><p>Targeting the right API level in Project Build Target properties as shown below:</p></li>
</ol>
<p><img src="https://i.stack.imgur.com/6UsaJ.png" alt="enter image description here"></p>
| 0 | 1,313 |
Set and Get item id of recycler view
|
<p>I am new in RecyclerView. We can get clicked item position in RecyclerView, but can we set and get item's ID of RecyclerView? Because in my RecyclerView, the item has custom ID provided by server. I've try this code :</p>
<p><strong>FragmentListProduct.java</strong></p>
<pre><code>productData = new JSONArray();
linearLayoutManager = new LinearLayoutManager(fragmentActivity);
lpAdapter = new ListProductAdapter(fragmentActivity, R.layout.list_product_grid, productData, null,
new ListProductHolder.OnProductClickListener() {
@Override
public void onProductClick(View v, long id) {
Toast.makeText(fragmentActivity, "id:"+id, Toast.LENGTH_SHORT).show();
MainActivity.setIdToRead((int) id);
MainActivity.replaceFragment(FragmentListProduct.this, new FragmentViewProduct());
}
});
rvProductList = (RecyclerView) mainView.findViewById(R.id.rvProductList);
rvProductList.setLayoutManager(linearLayoutManager);
rvProductList.setAdapter(lpAdapter);
rvProductList.setHasFixedSize(true);
</code></pre>
<p><strong>ListProductHolder.java</strong></p>
<pre><code>public class ListProductHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvTitle;
TextView tvPrice;
ImageView ivImage;
private OnProductClickListener onProductClickListener;
ListProductHolder(View itemView, OnProductClickListener onProductClickListener) {
super(itemView);
this.onProductClickListener = onProductClickListener;
tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
ivImage = (ImageView) itemView.findViewById(R.id.ivImage);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
onProductClickListener.onProductClick(view, getItemId());
}
public static interface OnProductClickListener {
public void onProductClick(View v, long id);
}
}
</code></pre>
<p><strong>ListProdutAdapter.java</strong></p>
<pre><code>public class ListProductAdapter extends RecyclerView.Adapter<ListProductHolder> {
private Activity activity;
private int layoutResource;
private JSONArray productDataArray;
private StringSignature downloadSignature;
private ListProductHolder.OnProductClickListener onProductClickListener;
public ListProductAdapter(Activity activity, int layoutResource, JSONArray productDataArray, StringSignature downloadSignature, ListProductHolder.OnProductClickListener onProductClickListener) {
this.activity = activity;
this.layoutResource = layoutResource;
this.productDataArray = productDataArray;
this.downloadSignature = downloadSignature;
this.onProductClickListener = onProductClickListener;
}
@Override
public ListProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(activity).inflate(layoutResource, parent, false);
return new ListProductHolder(v, onProductClickListener);
}
@Override
public void onBindViewHolder(ListProductHolder holder, int position) {...}
@Override
public long getItemId(int i) {
long itemId = -1;
try {
itemId = productDataArray.getJSONObject(i).getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
return itemId;
}
}
</code></pre>
<p>But when i tried it, the ID is always -1. How to solve this? or is there another solution i can do?</p>
| 0 | 1,296 |
Save Matplotlib Animation
|
<p>I am trying to make an Animation of a wave package and save it as a movie. Everything except the saving is working. Can you please tell me what I am doing wrong? When going into the line <code>ani.save('MovWave.mp4')</code> he tells me:</p>
<pre><code> writer = writers.list()[0]
IndexError: list index out of range
</code></pre>
<p>I tried googling it of course, but I don't even know what it means.</p>
<p><strong>UPDATE:</strong> I can call <code>ffmpeg</code> in console now. It says I have ffmpeg version <code>0.10.7-6:0.10.7-0jon1~precise</code> installed. I updated the code and ran the program, but now I get the following error:</p>
<pre><code>Traceback (most recent call last):
ani.save('MovWave.mpeg', writer="ffmpeg")
writer.grab_frame()
dpi=self.dpi)
self.canvas.print_figure(*args, **kwargs)
self.figure.dpi = origDPI
self.dpi_scale_trans.clear().scale(dpi, dpi)
self._mtx = np.identity(3)
from numpy import eye
File "<frozen importlib._bootstrap>", line 1609, in _handle_fromlist
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
</code></pre>
<p><strong>Update 2:</strong> Apparently there is a bug when using python 3.3 as doctorlove pointed out. I am now trying to use python 2.7 instead. Now it creates an mpeg-file but it cannot be played and it is only about ~150 kB big.</p>
<p><strong>Update 3:</strong> Okay, so I tried the exact same code on my Win7 machine and it also works in python 3.3. But I have the same problem, I had earlier with python 2.7. The mpeg-file created cannot be played and is only a few hundred kB.</p>
<pre><code>#! coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
time.clock()
def FFT(x,y):
X = (x[-1]-x[0])/len(y)
f = np.linspace(-2*np.pi/X/2,2*np.pi/X/2,len(y))
F = np.fft.fftshift(np.fft.fft(y))/np.sqrt(len(y))
return(f,F)
def FUNCTION(k_0,dx,c,t):
y = np.exp(1j*k_0*(x-c*t))*np.exp(-((x-c*t)/(2*dx))**2 )*(2/np.pi/dx**2)**(1/4)
k,F = FFT((x-c*t),y)
return(x,y,k,F)
#Parameter
N = 1000
x = np.linspace(0,30,N)
k_0 = 5
dx = 1
c = 1
l = [k_0,c,dx]
fig = plt.figure("Moving Wavepackage and it's FFT")
sub1 = plt.subplot(211)
sub2 = plt.subplot(212)
sub2.set_xlim([-10,10])
sub1.set_title("Moving Wavepackage and it's FFT")
sub1.set_ylabel("$Re[\psi(x,t)]$")
sub1.set_xlabel("$t$")
sub2.set_ylabel("$Re[\psi(k_x,t)]$")
sub2.set_xlabel("$k_x$")
n = 50
t = np.linspace(0,30,n)
img = []
for i in range(n):
x,y,k,F = FUNCTION(k_0,dx,c,t[i])
img.append(plt.plot(x,np.real(y),color="red", axes=plt.subplot(211)))
img.append(plt.plot(k,np.real(F),color="red", axes=plt.subplot(212)))
ani = animation.ArtistAnimation(fig, img, interval=20, blit=True, repeat_delay=0)
ani.save('MovWave.mpeg', writer="ffmpeg")
print(time.clock())
plt.show()
</code></pre>
| 0 | 1,208 |
PrintWriter or any other output stream in Java do not know "\r\n"
|
<p>I have trouble using PrintWriter or any other output stream to send message between server and client program. It works properly if I use println("abc") to communicate, but it does not work if I use print("abc\r\n"), print("abc\n") or print("abc\r"). What I mean by "it does not work" is that the readLine() will not end because it seems not to see "newline" character and it is still waiting for "\r" or "\n" </p>
<p>To make it more clear, I will simply put some codes in the following:
The client:</p>
<pre><code>import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(1234);
} catch (IOException e) {
System.err.println("Could not listen on port: 1234.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
}
System.out.println("Connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String textFromClient;
textFromClient = in.readLine(); // read the text from client
System.out.println(textFromClient);
String textToClient = "Recieved";
out.print(textToClient + "\r\n"); // send the response to client
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
</code></pre>
<p>The Server:</p>
<pre><code>import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
}
System.out.println("Connected");
String textToServer;
textToServer=read.readLine();
out.print(textToServer + "\r\n" ); // send to server
System.out.println(in.readLine()); // read from server
out.close();
in.close();
read.close();
socket.close();
}
}
</code></pre>
<p>I want to use print() + "\r\n" instead of println() because the server program I am writing has the requirement that the message sent from server to client needs to contain "\r\n" at the end, eg. "this is the message from server to client\r\n". I think println() is the same as print("\r\n"), So I do not think I should use println() + "\r\n", otherwise it will have 2 newlines. (Although I do not know how the client side will read from server because I am asked to just write server program only. They will write the client side to test my server program.) However, I am supposed to send the messages contain "\r\n" at the end but the readLine() seems not recognize it. So what could I do with it?</p>
<p>If you do not understand my question, you can try the codes above and you will know what I mean. </p>
| 0 | 1,127 |
Spring MVC: How to use a request-scoped bean inside a spawned thread?
|
<p>In a Spring MVC application, I have a request-scoped bean. I inject this bean somewhere. There, the HTTP-request serving thread could possibly spawn a new thread.</p>
<p>But whenever I try accessing the request-scoped bean from the newly spawned thread, I get a <code>org.springframework.beans.factory.BeanCreationException</code> (see stack trace below).<br>
Accessing the request-scoped bean from the HTTP request thread works fine.</p>
<p><strong>How can I make a request-scoped bean available to threads spawned by the HTTP request thread?</strong></p>
<hr>
<h2>Simple setup</h2>
<p>Get the following code snippets running. Then start up a server, for instance at <a href="http://example.com:8080">http://example.com:8080</a>.<br>
When accessing <a href="http://example.com:8080/scopetestnormal">http://example.com:8080/scopetestnormal</a>, each time a request is made to this address, <code>counter</code> is incremented by 1 (noticeable via logger output). :) Super!</p>
<p>When accessing <a href="http://example.com:8080/scopetestthread">http://example.com:8080/scopetestthread</a>, each time a request is made to this address, the mentioned exceptions are thrown. :(. No matter what chosen <code>ScopedProxyMode</code>, this happens for both CGLIB-based <em>and</em>
JDK-dynamic-proxy-interface-based request-scoped beans</p>
<p>Configuration file</p>
<pre><code>package com.example.config
@Configuration
@ComponentScan(basePackages = { "com.example.scopetest" })
public class ScopeConfig {
private Integer counter = new Integer(0);
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Number counter() {
counter = new Integer(counter.intValue() + 1);
return counter;
}
/* Adding a org.springframework.social.facebook.api.Facebook request-scoped bean as a real-world example why all this matters
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Facebook facebook() {
Connection<Facebook> facebook = connectionRepository()
.findPrimaryConnection(Facebook.class);
return facebook != null ? facebook.getApi() : new FacebookTemplate();
}
*/
...................
}
</code></pre>
<p>Controller file</p>
<pre><code>package com.example.scopetest;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FacebookProfile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ScopeTestController {
//@Inject
//private Facebook facebook;
@Inject
private Number counter;
private static final Logger logger = LoggerFactory
.getLogger(ScopeTestController.class);
@RequestMapping(value = "/scopetestnormal")
public void scopetestnormal() {
logger.debug("About to interact with a request-scoped bean from HTTP request thread");
logger.debug("counter is: {}", counter);
/*
* The following also works
* FacebookProfile profile = facebook.userOperations().getUserProfile();
* logger.debug("Facebook user ID is: {}", profile.getId());
*/
}
@RequestMapping(value = "/scopetestthread")
public void scopetestthread() {
logger.debug("About to spawn a new thread");
new Thread(new RequestScopedBeanAccessingThread()).start();
logger.debug("Spawned a new thread");
}
private class RequestScopedBeanAccessingThread implements Runnable {
@Override
public void run() {
logger.debug("About to interact with a request-scoped bean from another thread. Doomed to fail.");
logger.debug("counter is: {}", counter);
/*
* The following is also doomed to fail
* FacebookProfile profile = facebook.userOperations().getUserProfile();
* logger.debug("Facebook user ID is: {}", profile.getId());
*/
}
}
}
</code></pre>
<hr>
<p>Stack trace for CGLIB-based request-scoped bean (<code>proxyMode = ScopedProxyMode.TARGET_CLASS</code>)</p>
<pre><code>SLF4J: Failed toString() invocation on an object of type [$java.lang.Number$$EnhancerByCGLIB$$45ffcde7]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.counter': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:342)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.getTarget(Cglib2AopProxy.java:654)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:605)
at $java.lang.Number$$EnhancerByCGLIB$$45ffcde7.toString(<generated>)
at org.slf4j.helpers.MessageFormatter.safeObjectAppend(MessageFormatter.java:304)
at org.slf4j.helpers.MessageFormatter.deeplyAppendParameter(MessageFormatter.java:276)
at org.slf4j.helpers.MessageFormatter.arrayFormat(MessageFormatter.java:230)
at ch.qos.logback.classic.spi.LoggingEvent.<init>(LoggingEvent.java:114)
at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:447)18:09:48.276 container [Thread-16] DEBUG c.g.s.c.c.god.ScopeTestController - counter is: [FAILED toString()]
at ch.qos.logback.classic.Logger.filterAndLog_1(Logger.java:421)
at ch.qos.logback.classic.Logger.debug(Logger.java:514)
at com.example.scopetest.ScopeTestController$RequestScopedBeanAccessingThread.run(ScopeTestController.java:58)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:40)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:328)
... 14 more
</code></pre>
<hr>
<p>Stack trace for JDK-dynamic-proxy-interface-based request-scoped bean (<code>proxyMode = ScopedProxyMode.INTERFACES</code>)</p>
<pre><code>Exception in thread "Thread-16" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.facebook': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:342)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:182)
at $Proxy28.userOperations(Unknown Source)
at com.example.scopetest.ScopeTestController$PrintingThread.run(ScopeTestController.java:61)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:40)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:328)
... 6 more
</code></pre>
| 0 | 3,097 |
How to save a Nested Relation with Entity on API Platform
|
<p>I have two entities, <strong>Question</strong> and <strong>Alternative</strong> where Question has a OneToMany relation with Alternative and I'm trying to send a JSON with a nested document of <strong>Alternative</strong> on it via POST to <strong>Question</strong> API Platform.</p>
<p>The API Platform returns that error below :</p>
<pre><code>Nested documents for "alternatives" attribute are not allowed. Use IRIs instead.
</code></pre>
<p>Searching about it I've found some people saying that is only possible using IRIs and some other people saying that is possible to use Denormalization and Normalization contexts to solve this problem but I can't find some example or tutorial about it.</p>
<p><strong>TL;DR;</strong></p>
<p>Is there a way to send a nested relation into an entity POST on API Platform without using IRIs?</p>
<p><strong>UPDATE:</strong></p>
<p>As asked, please see below the two mappings of Question and Alternative entities.</p>
<p><strong>Question</strong></p>
<pre><code><?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\QuestionRepository")
* @ApiResource()
*/
class Question implements CreatedAtEntityInterface, UpdatedAtEntityInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Token", inversedBy="questions")
* @ORM\JoinColumn(nullable=false)
* @Assert\NotBlank()
*/
private $token;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="question_versions")
*/
private $question;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Question", mappedBy="question")
*/
private $question_versions;
/**
* @ORM\Column(type="integer")
* @Assert\NotBlank()
*/
private $version;
/**
* @ORM\Column(type="string", length=100)
* @Assert\Length(max="100")
* @Assert\NotBlank()
*
*/
private $name;
/**
* @ORM\Column(type="integer")
* @Assert\NotBlank()
*/
private $type;
/**
* @ORM\Column(type="text", length=65535)
* @Assert\NotBlank()
* @Assert\Length(max="65535")
*/
private $enunciation;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Assert\Length(max="255")
*/
private $material;
/**
* @ORM\Column(type="text", length=65535, nullable=true)
* @Assert\Length(max="65535")
*/
private $tags;
/**
* @ORM\Column(type="boolean")
* @Assert\NotNull()
*/
private $public;
/**
* @ORM\Column(type="boolean")
* @Assert\NotNull()
*/
private $enabled;
/**
* @ORM\Column(type="datetime")
* @Assert\DateTime()
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
* @Assert\DateTime()
*/
private $updatedAt;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Alternative", mappedBy="question")
*/
private $alternatives;
/**
* @ORM\OneToMany(targetEntity="App\Entity\QuestionProperty", mappedBy="question")
*/
private $properties;
/**
* @ORM\OneToMany(targetEntity="App\Entity\QuestionAbility", mappedBy="question")
*/
private $abilities;
/**
* @ORM\OneToMany(targetEntity="QuestionCompetency", mappedBy="question")
*/
private $competencies;
}
</code></pre>
<p><strong>Alternative</strong></p>
<pre><code><?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\AlternativeRepository")
* @ORM\Table(name="alternatives")
* @ApiResource()
*/
class Alternative implements CreatedAtEntityInterface, UpdatedAtEntityInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="alternatives")
* @ORM\JoinColumn(nullable=false)
* @Assert\NotBlank()
*/
private $question;
/**
* @ORM\Column(type="text", length=65535)
* @Assert\NotBlank()
* @Assert\Length(max="65535")
*/
private $enunciation;
/**
* @ORM\Column(type="datetime")
* @Assert\DateTime()
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
* @Assert\DateTime()
*/
private $updatedAt;
/**
* @ORM\OneToMany(targetEntity="App\Entity\AlternativeProperty", mappedBy="alternatives")
*/
private $properties;
}
</code></pre>
| 0 | 1,978 |
Z-index in android?
|
<p>I've more than one elemen in one xml.. listview,slidingdrawer,edittext and button...
i want to sliding drawer order is always in front of another elements...but i can't..</p>
<p>here my xml</p>
<pre><code><com.ltvie.chat.MultiDirectionSlidingDrawer
xmlns:my="http://schemas.android.com/apk/res/com.ltvie.chat"
android:id="@+id/drawer"
my:direction="topToBottom"
android:layout_width="fill_parent"
android:layout_height="match_parent"
my:handle="@+id/handle"
my:content="@+id/content"
>
<include
android:id="@id/content"
layout="@layout/pen_content"
android:gravity="top"
/>
<ImageView
android:id="@id/handle"
android:layout_width="wrap_content"
android:layout_height="5dp"
android:src="@drawable/sliding_drawer_handle_bottom" />
</com.ltvie.chat.MultiDirectionSlidingDrawer>
<ListView android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
android:layout_above="@+id/InnerRelativeLayout"
android:layout_alignParentTop="true"
/>
<RelativeLayout
android:id="@+id/InnerRelativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<Button
android:text="kirim"
android:id="@+id/button_send"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="tambahItems"
>
</Button>
</RelativeLayout>
</code></pre>
<p>the result of mycode in my pict bellow :D</p>
<p><img src="https://i.stack.imgur.com/f6Edq.png" alt="enter image description here" /></p>
<p>i want to know how to fix it??</p>
<p>regard,</p>
| 0 | 1,088 |
IPC: Using of named pipes in c++ between two programs
|
<p>I'm trying to realise a IPC between two different programs running on the same machine (in my case its a CentOS7). To have just a kind of loose coupling I decided to use a named pipe for the IPC. Therefore I'm was playing with the following example and ran into different problems.</p>
<p>Creating and writing into the pipe:</p>
<pre><code>#include <sys/types.h>
#include <sys/select.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
using namespace std;
main() {
int fd;
char * myfifo = new char [12];
strcpy(myfifo, "./tmp/myfifo1");
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write "Hi" to the FIFO */
fd = open("./tmp/myfifo1", O_WRONLY ); //open(myfifo, O_WRONLY | O_NONBLOCK);
if (fd == -1) {
perror("open");
return EXIT_FAILURE;
}
printf("File open\n");
write(fd, "entry [1]", sizeof("entry [1]"));
sleep(1);
write(fd, "entry [2]", sizeof("entry [2]"));
sleep(2);
write(fd, "entry [3]", sizeof("entry [3]"));
printf("Content written\n");
close(fd);
printf("Connection closed\n");
/* remove the FIFO */
unlink(myfifo);
return 0;
}
</code></pre>
<p>Reading the pipe:</p>
<pre><code>#include <sys/types.h>
#include <sys/select.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
main() {
int fd;
fd_set set_a;
char * myfifo = new char [12];
strcpy(myfifo, "./tmp/myfifo1");
char buffer[1024];
fd = open("./tmp/myfifo1", O_RDONLY | O_NONBLOCK);
if (fd == -1) {
perror("open");
return EXIT_FAILURE;
}
ssize_t bytes;
size_t total_bytes = 0;
printf("\nDropped into read pipe\n");
while(1){
if((bytes = read(fd, buffer, sizeof(buffer))) > 0){
std::string message(&buffer[22]);
total_bytes += (size_t)bytes;
printf("%i", bytes);
printf("Message: %s\n", message.c_str());
memset(&buffer[0], 0, sizeof(buffer));
}else{
if (errno == EWOULDBLOCK) {
printf("\ndone reading (%d bytes)\n", (int)total_bytes);
//break;
}
printf("No message\n");
sleep(2);
}
}
return EXIT_SUCCESS;
}
</code></pre>
<p>I feel like named pipes are pretty unflexible in its behavior I figured out with my test programs. First of all if no reading process is attached to the fifo pipe all messages except of the last one written to the pipe get lost (or generally speaking only the last message can be read after the reading process is attached to the pipe). If you write multiple messages into the pipe all messages betweem the reading (e.g. polled) will be interpreted as one single message (I'm aware that they can be splitted by \0). </p>
<p>The main goals for the named pipe is a) system logs and b) kind of user authentication. The asynchronous of named pipes fits perfectly to my need. But anyway, I'm not sure if named pipes are the best solution for IPC between different programs. Also I'm not sure if the behavior descripted above is normal or if I'm using named pipe in a wrong way. I also thought about sockets but then I will run into huge blocking problems.</p>
<p>Thanks for your help.</p>
| 0 | 1,369 |
How to properly close socket in both client and server (python)
|
<p>I am writing 2 scripts in python.</p>
<ol>
<li>Client.py</li>
<li>Server.py</li>
</ol>
<p>There is a socket between the client and server.
The scenario is this:<br>
I am having one client that ask to close the program therefore it should inform the server which by then will inform the other client, therefore I need to close the socket from client (1) to the server and then close the socket from the server to other client (imagin yourself a game of 2 people that one ask to exit the game).</p>
<p>I am doing it like that.In Client.py:</p>
<pre><code># send the request to the server
eNum, eMsg = Protocol.send_all(self.socket_to_server, msg)
if eNum:
sys.stderr.write(eMsg)
self.close_client()
self.socket_to_server.shutdown(socket.SHUT_WR)
exit(0)
</code></pre>
<p>then in the code of Server.py:</p>
<pre><code># get the msg from the client that calleds
num, msg = Protocol.recv_all(self.players_sockets[0])
# case of failure
if num == Protocol.NetworkErrorCodes.FAILURE:
sys.stderr.write(msg)
self.shut_down_server()
# case it was disconnected
if num == Protocol.NetworkErrorCodes.DISCONNECTED:
print msg
self.shut_down_server()
technical_win = ("exit" == msg)
# send the msg to the client needed to call
eNum, eMsg = Protocol.send_all(self.players_sockets[1],msg)
if eNum:
sys.stderr.write(eMsg)
self.shut_down_server()
# case end of game (winning or asking to exit)
if technical_win:
self.shut_down_server()
</code></pre>
<p>while <code>self.shut_down_server()</code>is:</p>
<pre><code>def shut_down_server(self):
# close socket of one of the player
self.players_sockets[0].shutdown(socket.SHUT_RDWR)
self.players_sockets[0].close()
# close socket of one of the player
self.players_sockets[1].shutdown(socket.SHUT_RDWR)
self.players_sockets[1].close()
# clean up
exit(0)
</code></pre>
<p>When the server send the msg that the other player ask to exit the client get it and doing the same as I showed in the begining.</p>
<p>unfortunately it is not working because when the server perform the code:</p>
<pre><code>num, msg = Protocol.recv_all(self.players_sockets[0])
# case of failure
if num == Protocol.NetworkErrorCodes.FAILURE:
sys.stderr.write(msg)
self.shut_down_server()
# case it was disconnected
if num == Protocol.NetworkErrorCodes.DISCONNECTED:
print msg
self.shut_down_server()
</code></pre>
<p>it get into the second if and print <code>'ERROR - Could not receive a message: timed out.'</code></p>
<p>How do I fix this properly?</p>
<p>P.S</p>
<p>I am using Linux</p>
| 0 | 1,177 |
android EditText ,keyboard textWatcher problem
|
<p>I am working on a android app and I have an EditText where user can input numbers. I want to format the number using different currency formats (say ##,##,###) and I want to do it on the fly, ie when user enter each digit(not when enter is pressed). I googled around, and came across <a href="http://developer.android.com/reference/android/text/TextWatcher.html" rel="noreferrer">TextWatcher</a> which I first found promising, but it turned out to be an absolute pain. I am debugging my code on a HTC Desire phone which only has a soft keyboard.</p>
<p>Now I want to get a callback when user press numbers (0 to 9) , del (backspace) key and enter key. From my testing I found these (atleast on my phone)</p>
<blockquote>
<p>1) editText onKeyListener is called
when user presses del or enter key.
When user presses enter, onKey
function is called twice for one enter
(which I believe is for ACTION_UP and
ACTION_DOWN). When user presses del,
onKey is called once (only for
ACTION_DOWN) which I dont know why.
onKey is never called when user
presses any digits(0 to 9) which too I
cant understand. </p>
<p>2) TextWatchers 3 callback functions
are called (beforeTextChanged,
onTextChanged, afterTextChanged)
whenever user presses any number (0 to
9) key . So I thought by using
TextWatcher and onKeyListener together
I can get all callbacks I need.</p>
</blockquote>
<p>Now my questions are these..</p>
<blockquote>
<p>1) First in my HTC soft keyboard there
is a key (a keyboard symbol with a
down arrow) and when I click on it
keyboard is resigned without giving
any callback. I still cant believe
android letting user to edit a field
and resign without letting program to
process (save) the edit. Now my
editText is showing one value and my
object has another value (I am saving
user edits on enter, and handling back
press on keyboard by reseting
editText value with the value in the
object , but I have no answer to this
keyboard down key). </p>
<p>2) Second, I want to format the number
after user entered the new digit. Say
I already have 123 on editText and
user entered pressed 4, I want my
editText to display 1,234. I get full
number on onTextChanged() and
afterTextChanged() and I can format
the number and put it back to
editText in any of these callback.
Which one should I use? Which is the
best practice?</p>
<p>3) Third one is the most crucial
problem. When app start I put the
current object value in the editText.
Say I put 123 on onResume(), and when
user enter a digit (say 4) I want it
to be 1234. But on my onTextChanged
callback what I am getting is 4123. When
I press one more key (say 5) I am
getting 45123. So for user inputs
editText cursor are pointing to end of
the text. But when value is set by
hand, editText cursor dont seems to be
updating. I believe I have to do
something in textWatcher callbacks but
I dont know what I should do.</p>
</blockquote>
<p>I am posting my code below.</p>
<pre><code>public class AppHome extends AppBaseActivity {
private EditText ed = null;
private NumberFormat amountFormatter = null;
private boolean isUserInput = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_home_screen);
ed = (EditText)findViewById(R.id.main_amount_textfield);
amountFormatter = new DecimalFormat("##,##,###");
ed.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN)
return true;
String strippedAmount = ed.getText().toString().replace(",", "");
if(keyCode == KeyEvent.KEYCODE_DEL){
//delete pressed, strip number of comas and then delete least significant digit.
strippedAmount = strippedAmount.substring(0, strippedAmount.length() - 1);
int amountNumeral = 0;
try{
amountNumeral = Integer.parseInt(strippedAmount);
} catch(NumberFormatException e){
}
myObject.amount = amountNumeral;
isUserInput = false;
setFormattedAmount(amountNumeral,ed.getId());
}else if(keyCode == KeyEvent.KEYCODE_ENTER){
//enter pressed, save edits and resign keyboard
int amountNumeral = 0;
try{
amountNumeral = Integer.parseInt(strippedAmount);
} catch(NumberFormatException e){
}
myObject.amount = amountNumeral;
isUserInput = false;
setFormattedAmount(myObject.amount,ed.getId());
//save edits
save();
//resign keyboard..
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(AppHome.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
return true;
}
});
TextWatcher inputTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
if(isUserInput == false){
//textWatcher is recursive. When editText value is changed from code textWatcher callback gets called. So this variable acts as a flag which tells whether change is user generated or not..Possibly buggy code..:(
isUserInput = true;
return;
}
String strippedAmount = ed.getText().toString().replace(",", "");
int amountNumeral = 0;
try{
amountNumeral = Integer.parseInt(strippedAmount);
} catch(NumberFormatException e){
}
isUserInput = false;
setFormattedAmount(amountNumeral,ed.getId());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
ed.addTextChangedListener(inputTextWatcher);
}//end of onCreate...
public void setFormattedAmount(Integer amount, Integer inputBoxId){
double amountValue = 0;
String textString =null;
TextView amountInputBox = (TextView) findViewById(inputBoxId);
amountValue = Double.parseDouble(Integer.toString(amount));
textString = amountFormatter.format(amountValue).toString();
amountInputBox.setText(textString);
}
}
</code></pre>
<p>I know it is a big question, but I am working on this same problem for 2 days. I am new to android and still cant believe that there is no easy way to process textEdit data on the fly (I done the same on iphone with ease). Thanks all</p>
<p><strong>EDIT</strong>: after using input filter</p>
<pre><code>InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String strippedAmount = dest.toString() + source;
strippedAmount = strippedAmount.replace(",", "");
int amountNumeral = 0;
try{
amountNumeral = Integer.parseInt(strippedAmount);
} catch(NumberFormatException e){
}
return amountFormatter.format(amountNumeral).toString();
}
};
ed.setFilters(new InputFilter[]{filter});
</code></pre>
<p>When app starts I am putting 1,234 on the editText</p>
<pre><code>myObject.amount = 1234;
ed.setText(amountFormatter.format(myObject.amount).toString());
</code></pre>
<p>Then when user clicks the editText, keyboard pops up, and say user enters digit 6 </p>
<blockquote>
<p>I am getting : 61234 I want :
12346</p>
</blockquote>
| 0 | 3,209 |
java.lang.ClassCastException: String can't be cast to Date
|
<h2>Stacktrace:</h2>
<pre><code>java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
at org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor.unwrap(JdbcTimestampTypeDescriptor.java:41)
at org.hibernate.type.descriptor.sql.TimestampTypeDescriptor$1.doBind(TimestampTypeDescriptor.java:65)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:90)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:286)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:281)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:613)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at com.nutsaboutcandywebproject.dao.SQLOrdersDataAccess.getMonthlyReport(SQLOrdersDataAccess.java:129)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getOrdersPerMonth(ServiceFacadeImpl.java:127)
at com.nutsaboutcandywebproject.controller.OrderController.orderHistory(OrderController.java:237)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
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:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
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:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
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:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
</code></pre>
<h2>Code:</h2>
<pre><code>@Override
public List <Orders> getMonthlyReport(String date){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
String hqlQuery = "FROM Orders WHERE orderDate LIKE :orderDate AND orderStatus = :orderStatus";
Query query = session.createQuery(hqlQuery);
query.setParameter("orderDate", date+"%");
query.setParameter("orderStatus", "PENDING");
List<Orders> orderList = query.list();
transaction.commit();
session.close();
return orderList;
}
</code></pre>
| 0 | 2,355 |
setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error
|
<p>I've been looking for an answer and I've tried many possible solutions, but nothing seems to work..</p>
<p>I'm trying to setup a Material Action Bar following <a href="http://www.android4devs.com/2014/12/how-to-make-material-design-app.html" rel="noreferrer">this tutorial</a>.</p>
<p>Here's my code:</p>
<p><strong>tool_bar.xml:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/ColorPrimary"
android:elevation="4dp">
</android.support.v7.widget.Toolbar>
</code></pre>
<p><strong>activity.xml:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<!-- The main content view -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/app_bar"
layout="@layout/tool_bar" />
</RelativeLayout>
<!-- Navigation Drawer -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="220dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#1C1C1C"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p><strong>And finally my activity.java:</strong></p>
<pre><code>import android.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toolbar;
public class rutaActivity extends ActionBarActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ruta);
getSupportActionBar().hide();//Ocultar ActivityBar anterior
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar); //HERE'S THE PROBLEM !!!!
</code></pre>
<p><strong>Error:</strong> </p>
<blockquote>
<p>setSupporActionBar (android.support.v7.widget.Toolbar) in ActionBarActivity cannot be applied to (android.widget.Toolbar)</p>
</blockquote>
<p>How can I fix this?</p>
| 0 | 1,118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.