title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
MUI Select - Change Select size
|
<p>whilst using the selects from MUI, I'm struggling to get them working properly using a height and width with 'vh' and 'vw' appropriately and a text-size using 'vh'.</p>
<p>I end up having a proper size for the boxes, but the label text is not centered anymore due to apparently using a 'transform' to offset itself from the top left corner.</p>
<p>Anyway, here's what I have:
<a href="https://codesandbox.io/s/material-demo-ujz2g" rel="noreferrer">https://codesandbox.io/s/material-demo-ujz2g</a></p>
<pre><code>import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormHelperText from "@material-ui/core/FormHelperText";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
const useStyles = makeStyles(theme => ({
formControl: {
margin: theme.spacing(1),
width: "20vw"
},
selectEmpty: {
marginTop: theme.spacing(2)
},
select: {
height: "10vh"
},
inputLabel: {
fontSize: "4vh",
alignSelf: "center"
}
}));
export default function SimpleSelect() {
const classes = useStyles();
const [age, setAge] = React.useState("");
const inputLabel = React.useRef(null);
const [labelWidth, setLabelWidth] = React.useState(0);
React.useEffect(() => {
setLabelWidth(inputLabel.current.offsetWidth);
}, []);
const handleChange = event => {
setAge(event.target.value);
};
return (
<div>
<FormControl variant="outlined" className={classes.formControl}>
<InputLabel
className={classes.inputLabel}
ref={inputLabel}
id="demo-simple-select-outlined-label"
>
Age
</InputLabel>
<Select
className={classes.select}
labelId="demo-simple-select-outlined-label"
id="demo-simple-select-outlined"
value={age}
onChange={handleChange}
labelWidth={labelWidth}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
<FormControl variant="filled" className={classes.formControl}>
<InputLabel id="demo-simple-select-filled-label">Age</InputLabel>
<Select
labelId="demo-simple-select-filled-label"
id="demo-simple-select-filled"
value={age}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</div>
);
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { makeStyles, InputLabel, MenuItem, FormHelperText, FormControl, Select } = MaterialUI;
const useStyles = makeStyles(theme => ({
formControl: {
margin: theme.spacing(1),
width: "20vw"
},
selectEmpty: {
marginTop: theme.spacing(2)
},
select: {
height: "10vh"
},
inputLabel: {
fontSize: "4vh",
alignSelf: "center"
}
}));
function SimpleSelect() {
const classes = useStyles();
const [age, setAge] = React.useState("");
const inputLabel = React.useRef(null);
const [labelWidth, setLabelWidth] = React.useState(0);
React.useEffect(() => {
setLabelWidth(inputLabel.current.offsetWidth);
}, []);
const handleChange = event => {
setAge(event.target.value);
};
return (
<div>
<FormControl variant="outlined" className={classes.formControl}>
<InputLabel
className={classes.inputLabel}
ref={inputLabel}
id="demo-simple-select-outlined-label"
>
Age
</InputLabel>
<Select
className={classes.select}
labelId="demo-simple-select-outlined-label"
id="demo-simple-select-outlined"
value={age}
onChange={handleChange}
labelWidth={labelWidth}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
<FormControl variant="filled" className={classes.formControl}>
<InputLabel id="demo-simple-select-filled-label">Age</InputLabel>
<Select
labelId="demo-simple-select-filled-label"
id="demo-simple-select-filled"
value={age}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</div>
);
}
ReactDOM.render(<SimpleSelect />, document.querySelector('#root'));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@4/umd/material-ui.production.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>EDIT: the odd behavior is especially visible when zooming in and out - the label itself moves within the dropdown.</p>
| 0 | 3,075 |
why angularjs ng-repeat not working
|
<p>I am trying out the basics of AngularJS first time. I am trying out ng-repeat first time. However it is not working. </p>
<p>Here is a non working <a href="http://jsfiddle.net/Mahesha999/XPjNy/1/" rel="nofollow">jsfiddle</a>.</p>
<p>I have written the code in single standalone HTML file as follows and also angular.js file resides in the same directory</p>
<pre><code><html ng-app>
<head>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript">
var users = [
{
name:"Mahesh",
description:"A geek",
age:"22"
},
{
name:"Ganesh",
description:"A nerd",
age:"25"
},
{
name:"Ramesh",
description:"A noob",
age:"27"
},
{
name:"Ketan",
description:"A psychopath",
age:"26"
},
{
name:"Niraj",
description:"Intellectual badass",
age:"29"
}
];
</script>
</head>
<body>
<div>
<div data-ng-repeat="user in users">
<h2>{{user.name}}</h2>
<div>{{user.description}}</div>
</div>
</div>
</body>
</html>
</code></pre>
| 0 | 1,117 |
Oracle APEX - Saving Shuttle Item selections to a new table
|
<p>I have a project I am working on where I am dealing with PARTS and ORDERS. Each ORDER may contain many PARTS and each PART has the possiblity of being on more than one ORDER over the course of its life (though not more than one ACTIVE ORDER at a time). My tables are currently as follows:</p>
<pre><code> PARTS_TABLE
PART_NUMBER varchar2(20)
ASSIGNED_ORDER_NUMBER number(5)
ASSIGNED_ORDER_STATUS varchar2(20)
ORDER_TABLE
ORDER_NUMBER number (5)
ORDER_STATUS varchar2(20)
ORDER_PARTS_LIST varchar2(4000) //Comma delimited list generated by shuttle item.
</code></pre>
<p>This current set up is working for us atm (with the help of this previous question: <a href="https://stackoverflow.com/questions/9024336/oracle-apex-database-trigger-problems-with-referencing-database-columns">Previous Question</a>) but it requires duplicating lots of data in both tables and it does not really allow for a PART being on multiple ORDERS over the course of its life. </p>
<p>What I would like to do is create a cross-reference table between these two tables:</p>
<pre><code> ORDER_PARTS_TABLE
ORDER_NUMBER number(5) (pk1)
PART_NUMBER varchar2(20) (pk2)
ORDER_STATUS varchar2(20)
</code></pre>
<p>Where PART_NUMBER and ORDER_NUMBER create a joint primary key. </p>
<p>My main issue is creating and editing the rows in ORDER_PARTS_TABLE based on the value of a shuttle item. I am able to effectively edit/update with my current set up but in my current set up I am not trying to create rows, I am just referencing the rows in PARTS_TABLE. When a person, using a shuttle item on a form in APEX, adds PARTS to an ORDER new rows should be created in ORDER_PARTS_TABLE i.e.:</p>
<pre><code> ORDER_TABLE
ORDER_NUMBER ORDER_PARTS_LIST ORDER_STATUS
12345 675:342:871:902 ACTIVE
ORDER_PARTS_TABLE
ORDER_NUMBER PART_NUMBER ORDER_STATUS
12345 675 ACTIVE
12345 342 ACTIVE
12345 871 ACTIVE
12345 902 ACTIVE
</code></pre>
<p>And if that order is later edited where a part is removed then the row pertaining to that relationship should either be removed from the ORDER_PARTS_TABLE or have its ORDER_STATUS set to 'REMOVED'</p>
<pre><code> ORDER_TABLE
ORDER_NUMBER ORDER_PARTS_LIST ORDER_STATUS
12345 675:871:902 ACTIVE
either...
ORDER_PARTS_TABLE
ORDER_NUMBER PART_NUMBER ORDER_STATUS
12345 675 ACTIVE
12345 342 REMOVED
12345 871 ACTIVE
12345 902 ACTIVE
or...
ORDER_PARTS_TABLE
ORDER_NUMBER PART_NUMBER ORDER_STATUS
12345 675 ACTIVE
12345 871 ACTIVE
12345 902 ACTIVE
</code></pre>
<p>Does any of that make sense? My current solution is just using triggers which I have been decently happy with but let me know what the best way to approach this new issue is. Thanks!</p>
<p><strong>EDIT:</strong> I have been doing some continued digging and found something that sounds reasonably promising if it can be adapted. Has anyone here had experience with
REGEXP_SUBSTR? <a href="https://forums.oracle.com/forums/thread.jspa?threadID=837253&start=0&tstart=0" rel="nofollow noreferrer">LINK</a> <a href="http://docs.oracle.com/cd/B14117_01/server.101/b10759/functions116.htm" rel="nofollow noreferrer">LINK</a></p>
| 0 | 1,480 |
Undefined attribute name (role) , eclipse
|
<p>I have a following file structure</p>
<p>WebContent->bootstrap-></p>
<p>js</p>
<p>css</p>
<p>img</p>
<p>WebContent->index.jsp</p>
<p>None of the following two urls are helping to resolve undefined attribute error.</p>
<p><a href="https://stackoverflow.com/questions/12988208/undefined-attribute-name-data-toggle">Undefined attribute name (data-toggle)</a></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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<button type="submit" class="btn btn-default">Submit</button>
<span class="label label-primary">Primary</span>
<span class="label label-success">Success</span>
<span class="label label-info">Info</span>
<span class="label label-warning">Warning</span>
<span class="label label-danger">Danger</span>
<a href="#">Inbox <span class="badge">42</span></a>
</div>
<div class="jumbotron">
<h1>Hello, world!</h1>
<p>...</p>
<p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
<li role="presentation" class="divider"></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
</body>
</html>
</code></pre>
<p>Eclipse version details are listed below.
Spring Tool Suite </p>
<p>Version: 3.6.1.RELEASE
Build Id: 201408250818
Platform: Eclipse Luna (4.4)</p>
<p>Copyright (c) 2007 - 2014 Pivotal Software, Inc.
All rights reserved. Visit <a href="http://spring.io/tools/sts" rel="nofollow noreferrer">http://spring.io/tools/sts</a></p>
<p>This product includes software developed by the
Apache Software Foundation <a href="http://www.apache.org" rel="nofollow noreferrer">http://www.apache.org</a></p>
| 0 | 1,381 |
PHP: Dynamic Drop down with optgroup
|
<p>I am developing a drop down menu that uses HTML optgroups for group names that employees are a part of. Here is the MySQL query and output:</p>
<pre>
mysql> SELECT employees.emp_id,employees.empname,employees.grp_id,groups.groupname FROM employees left join groups on employees.grp_id = groups.grp_id order by groupname asc;
+--------+------------+--------+-----------+
| emp_id | empname | grp_id | groupname |
+--------+------------+--------+-----------+
| 20 | Employee 2 | 13 | Group 1 |
| 19 | Employee 1 | 13 | Group 1 |
| 21 | Employee 3 | 14 | Group 2 |
+--------+------------+--------+-----------+
3 rows in set (0.00 sec)
</pre>
<p>The only issue is, I'm having the hardest time figuring out how to get the optgroup to work correctly. I've tried countless times, and it's really starting to frustrate me. <strong>The following is pretty much I want the output to be (example):</strong></p>
<pre><code><select name="dropdownmenu">
<optgroup label="Group 1">
<option name="20">Employee 2</option>
<option name="19">Employee 1</option>
</optgroup>
<optgroup label="Group 2">
<option name="21">Employee 3</option>
</optgroup>
</select>
</code></pre>
<p>Basically, the optgroup needs to be the "groupname", the option "name" should be the "emp_id", and the action "option" (drop down item) is the "empname".</p>
<p>I hope this is something that can be done, but really not sure. Here's the function I have, but it doesn't exactly work well:</p>
<pre><code>function getDynGrpList() {
global $db;
// $query = "SELECT * FROM employees ORDER BY grp_id desc;";
$query = "SELECT employees.emp_id,employees.empname,employees.grp_id,groups.groupname FROM employees left join groups on employees.grp_id = groups.grp_id order by groupname asc;";
$employees = $db->GetAll($query);
$groups = array();
while ($qa = $employees->GetRows()) {
$groups[$qa['groupname']][$qa['grp_id']] = $qa['empname'];
}
foreach ($groups as $label => $opt) { ?>
<optgroup label="<?php echo $label; ?>">
<?php }
foreach ($groups[$label] as $id => $name) { ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</optgroup>
<?php }
</code></pre>
<p><strong>getDynGrpList function as of 3:15AM CST (2/27):</strong></p>
<pre><code>function getDynGrpList() {
global $db;
// $query = "SELECT * FROM employees ORDER BY grp_id desc;";
$query = "SELECT employees.emp_id,employees.empname,employees.grp_id,groups.groupname FROM employees left join groups on employees.grp_id = groups.grp_id order by groupname asc;";
$employees = $db->GetAll($query);
$groups = array();
while ($qa = $employees->GetRows()) {
$groups[$qa['groupname']][$qa['emp_id']] = $qa['empname'];
}
var_export($groups);
foreach($groups as $label => $opt): ?>
<optgroup label="<?php echo $label; ?>">
<?php foreach ($opt as $id => $name): ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php endforeach; ?>
</optgroup>
<?php endforeach;
}
</code></pre>
<p><strong>Final Solution (with the help of Felix Kling)</strong></p>
<pre><code>function getDynGrpList() {
global $db;
$query = "SELECT employees.emp_id,employees.empname,employees.grp_id,groups.groupname FROM employees left join groups on employees.grp_id = groups.grp_id order by groupname asc;";
$employees = $db->GetAll($query);
$groups = array();
foreach ($employees as $employee) {
$groups[$employee['groupname']][$employee['emp_id']] = $employee['empname'];
}
foreach($groups as $label => $opt): ?>
<optgroup label="<?php echo $label; ?>">
<?php foreach ($opt as $id => $name): ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php endforeach; ?>
</optgroup>
<?php endforeach;
}
</code></pre>
| 0 | 1,743 |
sliding between route transition angularjs
|
<p>I've only been working with Angular for about a week, so I apologize if my code is crap.</p>
<p>I'm attempting to create a sliding action between route transitions. I can create the effect in a slideshow but not between route transitions.</p>
<p>Anyway code below:
Nav</p>
<pre><code><li><a ng-click="go('/')" class = "intro currentLink navLinks">Intro</a></li>
<li><a ng-click="go('/why')" class = "why navLinks">Why</a></li>
<li><a ng-click="go('/resume')" class = "resume navLinks">Res</a></li>
<li><a ng-click="go('/qualified')" class = "qualified navLinks">How</a></li>
<li><a ng-click="go('/contact')" class = "contact navLinks">Contact me</a></li>
</code></pre>
<p>view(s)</p>
<pre><code><div class = "pages">
<div ng-view id="slides" ng-animate="'slide'">
<!--inside main view-->
</div><!--end main view-->
</div><!--end pages-->
</code></pre>
<p>css</p>
<pre><code>.slide-leave-setup {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
}
.slide-enter-setup {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
}
.slide-enter-setup {
position: absolute;
left: 1300px;
}
.slide-enter-start {
left: 0;
}
.slide-leave-setup {
position: absolute;
left: -1700px;
}
.slide-leave-start {
right: 0;
}
</code></pre>
<p>includes</p>
<pre><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular-animate.min.js"></script>
<script src="http://code.angularjs.org/1.2.3/angular-route.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular-sanitize.js"></script>
<script src="js/vendor/ui-bootstrap-custom-tpls-0.6.0.js"></script>
</code></pre>
<p>javascript:</p>
<pre><code>var app = angular.module('MyApp', ['ui.bootstrap', 'ngSanitize', 'ngRoute', 'ngAnimate']);
</code></pre>
<p>Full project at <a href="https://github.com/arttay/blizz" rel="nofollow">https://github.com/arttay/blizz</a></p>
<p>Thank you</p>
| 0 | 1,252 |
The Namespace * already contains a definition for *
|
<p>I've created a separate folder and pages in my ASP.NET web application. When I build the solution, I receive the error </p>
<pre><code>The Namespace MyApp already contains a defintion for VDS
</code></pre>
<p>Here's the contents of VDS.Master.cs:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MayApp{
public partial class VDS : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
</code></pre>
<p>Here's the content of VDS.Master.designer.cs:</p>
<pre><code>//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MyApp.VDS {
public partial class VDS {
/// <summary>
/// Head1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
/// <summary>
/// head control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder head;
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// ScriptManager1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.ScriptManager ScriptManager1;
/// <summary>
/// NavMenu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Menu NavMenu;
/// <summary>
/// smds1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.SiteMapDataSource smds1;
/// <summary>
/// MainContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent;
/// <summary>
/// lblfoot control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
</code></pre>
<p>Here's the content of VDS.Master:</p>
<pre><code><%@ Master Language="C#" AutoEventWireup="True" CodeBehind="VDS.Master.cs" Inherits="MyApp.VDS.VDS" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Dealer Services</title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
<link href="Styles/master.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<div class="header">
<h1>Welcome to Dealer Services </h1>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
<div class=" clear nav">
<asp:Menu runat="server" ID="NavMenu" BackColor="Silver" DataSourceID="smds1"
DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em"
ForeColor="White" Orientation="Horizontal" StaticSubMenuIndent="10px">
<DynamicHoverStyle BackColor="#284E98" ForeColor="White" />
<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
<DynamicMenuStyle BackColor="#B5C7DE" />
<DynamicSelectedStyle BackColor="#507CD1" />
<StaticHoverStyle BackColor="#284E98" ForeColor="White" />
<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
<StaticSelectedStyle BackColor="#507CD1" />
</asp:Menu>
<asp:SiteMapDataSource ID="smds1" runat="server" ShowStartingNode="False" />
</div>
<div class="login">
</div>
<div class="content">
<asp:ContentPlaceHolder id="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="footer">
<asp:Label runat="server" ID="lblfoot">&trade; Veehco Inc. 2011</asp:Label>
</div>
</div>
</form>
</body>
</html>
</code></pre>
<p>I've tried deleting the VDS.Master.designer.cs file, but the error is returned upon each build. How do I rectify this issue?</p>
<p>Thanks much!</p>
| 0 | 2,224 |
CSS: 100% font size - 100% of what?
|
<p>There are <a href="http://www.alistapart.com/articles/howtosizetextincss" rel="noreferrer">many</a> <a href="http://www.w3.org/TR/CSS2/fonts.html#font-size-props" rel="noreferrer">articles</a> and <a href="https://stackoverflow.com/questions/132685/font-size-in-css-or-em">questions</a> about <a href="http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/" rel="noreferrer">percentage-sized vs other-sized</a> fonts. However, I can not find out WHAT the reference of the percent-value is supposed to be. I understand this is 'the same size in all browsers'. I also read this, for instance:</p>
<blockquote>
<p>Percent (%): The percent unit is much like the “em” unit, save for a few fundamental differences. First and foremost, the current font-size is equal to 100% (i.e. 12pt = 100%). While using the percent unit, your text remains fully scalable for mobile devices and for accessibility.</p>
</blockquote>
<p>Source: <a href="http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/" rel="noreferrer">http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/</a></p>
<p>But if you say "ie 12 pt = 100%", then it means you first have to define <code>font-size: 12pt</code>. Is that how it works? You first define a size in an absolute measure, and then refer to this as '100%'? Does not make a lot of sense, as many samples say it is useful to put:</p>
<pre><code>body {
font-size: 100%;
}
</code></pre>
<p>So by doing this, <em>WHAT</em> is the font size relative to? I notice that the size I see on my screen differs for every font. Arial looks way bigger than Times New Roman, for instance. Also, if I would just do this, body size = 100%, would <em>that</em> mean that it will be the same on all browsers? Or only if I first define an absolute value? </p>
<p><strong>UPDATE, SAT JUL 23</strong></p>
<p>I am getting there, but please bear with me. </p>
<p>So, the % value relates to the default browser font size, if I understand correctly. Well, that is nice but gives me again several other questions:</p>
<ol>
<li>Is this standard size always the same for every browser version, or do they vary between versions?</li>
<li>I ! found (see image below) the settings for Google Chrome (never looked at this before!), and I see standard "serif", "sans-serif" and "monospace" settings. But how do I interpret this for other fonts? Say I define <code>font: 100% Georgia;</code>, what size will the browser take? Will it look up the standard size for serif, or has the "Georgia" font a standard size for the browser</li>
<li>On several websites I <a href="http://www.alistapart.com/articles/howtosizetextincss" rel="noreferrer">read</a> things like <code>Sizing text and line-height in ems, with a percentage specified on the body [..], was shown to provide **accurate, resizable text across all browsers** in common use today</code>. But from what I am learning now I believe that you should actually choose between either resizable text (using % or em, like what they recommend in this quote), or having 'accurate, consistent font-sizes across browsers' (by using px or pt as a base). Is this correct? </li>
</ol>
<p>Google Settings:</p>
<p><img src="https://i.stack.imgur.com/9dR1N.png" alt="Google Chrome Settinsg"></p>
<p>This is how I <em>think</em> things <em>could</em> look like if you do not define the size in absolute values. </p>
<p><img src="https://i.stack.imgur.com/GomGD.gif" alt="enter image description here"></p>
| 0 | 1,104 |
Spring Security logout does not work - does not clear security context and authenticated user still exists
|
<p>I know, there are many articles about this topic, but I have a problem and I can't find any solution.</p>
<p>I have a classic spring security java config:</p>
<pre><code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuctionAuthenticationProvider auctionAuthenticationProvider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(auctionAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequest = http.authorizeRequests();
configureAdminPanelAccess(authorizeRequest);
configureFrontApplicationAccess(authorizeRequest);
configureCommonAccess(authorizeRequest);
http.csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
http.logout()
.clearAuthentication(true)
.invalidateHttpSession(true);
}
...
}
</code></pre>
<p>Also, I have two controller methods, where I login/logout from my web application by AJAX.</p>
<p>When I would like to logout, I first call this method, which I expect to clear user sessions and clear everything from the security context.</p>
<pre><code>@Override
@RequestMapping(value = "/logout", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Boolean> logout(final HttpServletRequest request, final HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return new ResponseEntity<>(Boolean.TRUE, HttpStatus.OK);
}
</code></pre>
<p>After this I reload my client web application and each time, when it is reloaded, I check whether the user is authenticated by calling the following controller method:</p>
<pre><code>@Override
@RequestMapping(value = "/user", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<UserDetails> user() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
return new ResponseEntity<>((UserDetails) principal, HttpStatus.OK);
}
return null;
}
</code></pre>
<p>And here I aways receive the last authenticated user. It seems that in the previous logout method, Spring logout doesn't work.</p>
<p>Keep in mind that I tried to logout with the following code, without any success:</p>
<pre><code> @Override
@RequestMapping(value = "/logout", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Boolean> logout(final HttpServletRequest request) {
try {
request.logout();
return new ResponseEntity<>(Boolean.TRUE, HttpStatus.OK);
} catch (ServletException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("There is a problem with the logout of the user", ex);
}
}
</code></pre>
<p>Are you have any idea what I miss in my config and the logout process?</p>
| 0 | 1,053 |
Angular get offset of element by id
|
<p>I try to set the navbar li object to active when i currently watch the corresponding section.
In other words: When scrolling through my page (single page with multiple sections), the section i'm watching should be highlighted in the navbar.</p>
<p>I already got the scrolling position via directive. Where I fail is to trigger ng-class on the .nav ul li.</p>
<pre><code><li class="" ng-class="{'active': $parent.scrollPos > document.getElementById('something').offset()}">
<a class="" ng-click="isCollapsed = true" href="#something" du-smooth-scroll>Something</a>
</li>
</code></pre>
<p>I doesn't make any difference when I use </p>
<pre><code>ng-class="{'active': $parent.scrollPos > angular.element('#something').offset()}"
</code></pre>
<p>How do I get the distance from document-top of any element? </p>
<p>Thanks a lot. </p>
<p>PS: I use jQuery (not lite)!</p>
<p><strong>EDIT</strong>
How it works (Thanks to @Sharikov Vladislav):
On body I use the "PageCtrl":</p>
<pre><code><body id="page-top" class="index bg-default" ng-app="previewApp" ng-controller="PageCtrl">
</code></pre>
<p>which looks like that:</p>
<pre><code>angular.module('previewApp')
.controller('PageCtrl', function($scope, $element) {
$scope.scrollPos = 0;
$scope.getOffset = function (elementId) {
var element = $element.find(elementId);
return element.offset().top;
};
});
</code></pre>
<p>Right after the body I use a span </p>
<pre><code><span scroll-position="scrollPos"></span>
</code></pre>
<p>to initialise my "scrollPosition"-directive, which allows me to access the current scroll position over the $scope.scrollPos in PageCtrl.
Directive:</p>
<pre><code>angular.module('previewApp')
.directive('scrollPosition', function ($window) {
return {
scope: {
scrollPos: "=scrollPosition"
},
link: function (scope, element, attrs) {
var windowElement = angular.element($window);
var handler = function () {
scope.scrollPos = windowElement.scrollTop();
}
windowElement.on('scroll', scope.$apply.bind(scope, handler));
handler();
}
};
});
</code></pre>
<p>In my .nav ul li looks like the following. The "- 150" is for a more acurate highlighting. </p>
<pre><code><div class="navbar-collapse" uib-collapse="isCollapsed" id="menu-center">
<ul class="nav navbar-nav navbar-right">
<li class="hidden">
<a href="#page-top"></a>
</li>
<li ng-class="{'active': $parent.scrollPos > $parent.getOffset('#section1') - 150 && $parent.scrollPos < $parent.getOffset('#section2') - 150}">
<a ng-click="isCollapsed = true" href="#section1" du-smooth-scroll>Section1</a>
</li>
<li ng-class="{'active': $parent.scrollPos > $parent.getOffset('#section2') - 150 && $parent.scrollPos < $parent.getOffset('#section3')}">
<a ng-click="isCollapsed = true" href="#section2" du-smooth-scroll>Section2</a>
</li>
</ul>
</div>
</code></pre>
<p>I hope this helps somebody out there who is struggling over the same problem like me. Greets</p>
| 0 | 1,295 |
Module not found: Can't resolve './components/player' in '.../score-board-app/src/components'
|
<p>I use Create-React-App to build a small React application. The full code is stored in <a href="https://github.com/juan-coding/score-board-app" rel="nofollow noreferrer">github</a></p>
<p>My file structure: </p>
<pre><code>src
components
Players.js
Player.js
App.css
App.js
index.css
index.js
...
</code></pre>
<p><em>App.js:</em></p>
<pre><code>import React from 'react';
import './App.css';
import PropTypes from 'prop-types';// used to fix the error: 'PropTypes' is not defined
import Header from './components/Header';
import Players from './components/Players';
const App = (props) => (
<div className="scoreboard">
<Header title={props.title} />
<Players />
</div>
);
App.propTypes = {
title: PropTypes.string.isRequired
};
export default App;
</code></pre>
<p><em>Player.js:</em></p>
<pre><code>import React from 'react';
const Player = (props) => (
<div className="player">
<div className="player-name">
Jim Hoskins
</div>
<div className="player-score">
<div className="counter">
<button className="counter-action decrement"> - </button>
<div className="counter-score">31</div>
<button className="counter-action increment"> + </button>
</div>
</div>
</div>
);
export default Player;
</code></pre>
<p><em>Players.js:</em></p>
<pre><code>import React from 'react';
import Player from './components/Player';
const Players = () => (
<div className="players">
<div className="player">
<div className="player-name">
Jim Hoskins
</div>
<div className="player-score">
<div className="counter">
<button className="counter-action decrement"> - </button>
<div className="counter-score">31</div>
<button className="counter-action increment"> + </button>
</div>
</div>
</div>
<div className="player">
<div className="player-name">
Juan Li
</div>
<div className="player-score">
<div className="counter">
<button className="counter-action decrement"> - </button>
<div className="counter-score">30</div>
<button className="counter-action increment"> + </button>
</div>
</div>
</div>
</div>
)
export default Players;
</code></pre>
<p>And the line <code>import Player from './components/Player';</code> leads to this error:
<a href="https://i.stack.imgur.com/cEIJH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cEIJH.png" alt="enter image description here"></a>
But if I put this line on top of <code>App.js</code> file, it doesn't report such compiling error. I really want to know what's the issue indeed with my code? </p>
| 0 | 1,335 |
How to create XML file on server using stored procedure or cursor
|
<p>In my database (<code>GoogleSEOData</code>), I have got one Table (GoogleMarkupList) and below sample data are there in table:</p>
<pre><code>PUBLICATION_ID | PAGEID | URL
-------------------------------------------------------------
233 | 654345 | /english/index.aspx
345 | 654345 | /de/english/index.aspx
432 | 654345 | /ru/russian/index.aspx
533 | 654345 | /ae/arabic/index.aspx
233 | 452323 | /english/offers.aspx
345 | 452323 | /de/english/offers.aspx
432 | 452323 | /ru/russian/offers.aspx
533 | 452323 | /ae/arabic/offers.aspx
233 | 834343 | /english/destinations.aspx
345 | 834343 | /de/english/destinations.aspx
432 | 834343 | /ru/russian/destinations.aspx
533 | 834343 | /ae/arabic/destinations.aspx
</code></pre>
<p>Now I want to write SQL Procedure which will take File Path of the server as input say (D://GoogleMarkup) and would create below type of XML files on server (For above sample data).</p>
<p>Name of XML file for 654345 type of data will be <code>654345.XML</code></p>
<pre><code><ps>
<p n="233" u="/english/index.aspx" />
<p n="345" u="/de/english/index.aspx" />
<p n="432" u="/ru/russian/index.aspx" />
<p n="533" u="/ae/arabic/index.aspx" />
</ps>
</code></pre>
<p>Name of XML file for 452323 type of data will be <code>452323.XML</code></p>
<pre><code><ps>
<p n="233" u="/english/offers.aspx" />
<p n="345" u="/de/english/offers.aspx" />
<p n="432" u="/ru/russian/offers.aspx" />
<p n="533" u="/ae/arabic/offers.aspx" />
</ps>
</code></pre>
<p>Name of XML file for 834343 type of data will be <code>834343.XML</code></p>
<pre><code><ps>
<p n="233" u="/english/destinations.aspx" />
<p n="345" u="/de/english/destinations.aspx" />
<p n="432" u="/ru/russian/destinations.aspx" />
<p n="533" u="/ae/arabic/destinations.aspx" />
</ps>
</code></pre>
<p>I know there is utility </p>
<pre><code>SQLCMD -S Server -d Database -E -v pageid=%pid%
-Q "Select publication_id as [n], url from table as [p] where pageid=$(pageid) for xml auto, root('ps')"
-o D://GoogleMarkup/%pid%.xml
</code></pre>
<p>But how to create all the XMLs in one go, so that it will read pageid one by one and would pass to <code>SQLCMD</code> to create XML, do I need to write cursor for that, please suggest with some good code sample. </p>
<p>Please suggest!! </p>
| 0 | 1,206 |
Convert Linkedlist to ArrayList
|
<p>I had to write a program to do LZWDecode and I decided to use LinkedList to write the LZWDecode program below but I want to convert it to an ArrayList. Anyone have idea on how I can convert the LinkedList to an ArrayList to make it simpler.
Thanks.</p>
<pre><code>import java.util.*;
public class LZWDecoder {
private final int CLEAR_TABLE=256;
private final int END_OF_DATA=257;
private final int TABLE_SIZE=4096;
private static LinkedList<Integer> input = new LinkedList<Integer>();
@SuppressWarnings("unchecked")
private LinkedList<Integer>[] table
= new LinkedList[TABLE_SIZE];
private LinkedList<Integer> temp = new LinkedList<Integer>();
private int index = 258;
private LinkedList<String> trace = new LinkedList<String>();
private boolean view = true;
private void enterData() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Input Code (EOD = 257):");
int n=0;
while(n!=END_OF_DATA && scan.hasNextInt()){
n = scan.nextInt();
//System.out.println("Adding "+n);
input.add(n);
}
System.out.println("Decoding...\nOutput:");
String code="";
for(int i=0; i<input.size(); i++) {
code+=input.get(i)+" ";
}
trace.add("\nInput: "+code);
//test
/*
while(!input.isEmpty()) {
System.out.println(input.remove());
}
*/
}
private void reset() {
trace.add("Clearing...");
//table.clear();
for(int i=0; i<TABLE_SIZE;i++) {
table[i] = new LinkedList<Integer>();
}
}
private void decode(int c) {
switch(c) {
case CLEAR_TABLE:
trace.add("decode\t"+CLEAR_TABLE+"->[256]");
reset();
break;
case END_OF_DATA:
trace.add("decode\t"+END_OF_DATA+"->[257]");
trace.add("Decoding finished.");
break;
default:
if(c<256) {
trace.add("decode\t"+c+"->["+c+"]");
if(!temp.isEmpty()) append(c);
emit(c);
add(temp);
} else {
trace.add("decode\t"+c+"->["+printTableNode(table[c])+"]");
if(!temp.isEmpty()) append(table[c].get(0));
emit(c, table[c]);
add(temp);
}
}
}
private void emit(int n, LinkedList<Integer> c) {
//int [] a=new int[c.size()];
temp=new LinkedList<Integer>();
for(int i=0; i<c.size(); i++) {
//a[i]=c.get(i);
System.out.print(c.get(i)+" ");
temp.add(c.get(i));
}
trace.add("emit\t"+n+"->"+"["+printTableNode(c)+"]");
}
private void emit(int c) {
//print out output
temp=new LinkedList<Integer>();
temp.add(c);
trace.add("emit\t"+c+"->"+"["+c+"]");
System.out.print(c+" ");
}
/*
private void add(int c) {
//added to table is copied to temp
table[index].add(c);
temp = (LinkedList)table[index].clone();
trace.add("add\t"+index+"->["+printTableNode(table[index])+"]");
}
*/
private void add(LinkedList<Integer> c) {
for(int i=0; i<c.size();i++) {
//temp.add(c.get(i));
table[index].add(c.get(i));
}
trace.add("add\t"+index+"->["+printTableNode(table[index])+"]");
}
private void append(int c) {
//table[c].add(12);//add what?
//temp.add(c);
table[index].add(c);
trace.add("append\t"+index+"->["+printTableNode(table[index])+"]");
index++;
}
private String printTableNode(LinkedList l) {
String list="";
for(int i=0; i<l.size();i++) {
list+=l.get(i);
if(i<l.size()-1) {
list+=", ";
}
}
return list;
}
private void printTrace() {
System.out.print("Printing Trace...");
for(int i=0; i<trace.size(); i++) {
System.out.println(trace.get(i));
}
}
public static void main(String[] args) {
// TODO code application logic here
LZWDecoder d = new LZWDecoder();
d.enterData();
while(!input.isEmpty()) {
d.decode(input.remove());
}
System.out.print("\n\n");
d.printTrace();
}
}
</code></pre>
| 0 | 1,467 |
How to have Keycloak login page in iframe?
|
<p>There is a web server running locally, and I want to have Keycloak (on another domain) login page inside the iframe. I tried the following setting in the Keycloak Real Settings > Security Defenses > Headers > Content-Security-Policy</p>
<pre><code>frame-src 'self' http://127.0.0.1 http://192.168.1.140 http://localhost *.home-life.hub http://trex-macbook.home-life.hub localhost; frame-ancestors 'self'; object-src 'none';
</code></pre>
<p>Basically, I put my local IP addresses and host names as sources to <code>frame-src</code>.</p>
<p>The login page is not shown and I get this error in the browser console</p>
<pre><code>Refused to display 'http://keycloak.example.com:8080/auth/realms/master/protocol/openid-connect/auth?client_id=es-openid&response_type=code&redirect_uri=https%3A%2F%2Fkibana.example.com%3A5601%2Fauth%2Fopenid%2Flogin&state=3RV-_nbW-RvmB8EfUwgkJq&scope=profile%20email%20openid' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self'".
</code></pre>
<p>My custom headers are present
<a href="https://i.stack.imgur.com/vNezD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vNezD.png" alt="enter image description here"></a></p>
<p>My server and UI (server rendered) code:</p>
<pre><code>'use strict';
const Hapi = require('@hapi/hapi');
const init = async () => {
// Run server on all interfaces
const server = Hapi.server({
port: 3000,
});
await server.start();
// server.ext('onPreResponse', (req, h) => {
// req.response.header('Content-Security-Policy', "default-src 'self' *.example.com");
// console.log('req.response.headers', req.response.headers);
// return h.continue;
// });
server.route({
method: 'GET',
path: '/home',
handler: () => {
return `<html>
<head>
<title>searchguard kibana openid keycloak</title>
</head>
<body>
<p>
<iframe src="https://kibana.example.com:5601" width="800" height="600"></iframe>
</p>
</body>
</html>`;
},
});
server.route({
method: '*',
path: '/{path*}',
handler: (req, h) => {
return h.redirect('/home');
},
});
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
</code></pre>
<p>The iframe should show a page on kibana.example.com in the end. The Keycloak is used as an identity provider for the kibana.example.com.</p>
| 0 | 1,127 |
How to click a button through coding?
|
<p>I have two buttons in my program and i want that when i press first button the second button is clicked automatically ( in the event handler of first button , i want to press the second button through coding).</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
passWord = pwd.Text;
user = uName.Text;
loginbackend obj = new loginbackend();
bool isValid = obj.IsValidateCredentials(user, passWord, domain);
if (isValid)
{
loginbackend login = new loginbackend();
passWord = pwd.Text;
login.SaveUserPass(passWord);
HtmlDocument webDoc = this.webBrowser1.Document;
HtmlElement username = webDoc.GetElementById("__login_name");
HtmlElement password = webDoc.GetElementById("__login_password");
username.SetAttribute("value", user);
password.SetAttribute("value", passWord);
HtmlElementCollection inputTags = webDoc.GetElementsByTagName("input");
foreach (HtmlElement hElement in inputTags)
{
string typeTag = hElement.GetAttribute("type");
string typeAttri = hElement.GetAttribute("value");
if (typeTag.Equals("submit") && typeAttri.Equals("Login"))
{
hElement.InvokeMember("click");
break;
}
}
button3_Click(sender, e);
label1.Visible = false ;
label3.Visible = false;
uName.Visible = false;
pwd.Visible = false;
button1.Visible = false;
button2.Visible = true;
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
private void button3_Click(object sender, EventArgs e)
{
HtmlDocument webDoc1 = this.webBrowser1.Document;
HtmlElementCollection aTags = webDoc1.GetElementsByTagName("a");
foreach (HtmlElement link in aTags)
{
if (link.InnerText.Equals("Show Assigned"))
{
link.InvokeMember("click");
break;
}
}
}
</code></pre>
| 0 | 1,052 |
Get all rows matching a list in a SQL query
|
<p>I have the following SQL query that selects any row matching ANY of the values in the list (9, 10):</p>
<pre><code>SELECT
r.id, r.title,
u.name as 'Created By',
c.name as 'Category',
c.value,
cr.category_id
FROM
category_resource cr
INNER JOIN resource r
ON cr.resource_id = r.id
INNER JOIN user u
ON r.created_by = u.id
INNER JOIN category c
ON cr.category_id = c.id
WHERE cr.category_id IN ('10', '9');
</code></pre>
<p>I have tried finding out how to do the opposite, which I also need, i.e select rows that match ALL values.</p>
<p>I have read about using a statement sort of like this:</p>
<pre><code>SELECT
r.id, r.title
FROM
resource r
WHERE
id IN (
SELECT
resource_id
FROM
category_resource
WHERE
category_id IN (9, 10)
GROUP BY
resource_id
HAVING
COUNT(DISTINCT category_id) = 2
);
</code></pre>
<p>This is my attempt at adapting this answer to my needs:
<a href="https://stackoverflow.com/questions/15977126/sql-server-select-rows-that-match-all-items-in-a-list">SQL Server - select rows that match all items in a list</a></p>
<p>But that doesn't get me as much information back in the results as the first statement does. So how could I do something that is more equivalent? I've tried to put it together, but I'm too new to SQL to figure it out right, I just get errors...</p>
<p>LONG UPDATE: </p>
<p>Gordon Linoff pointed out that this is a strange request. And I know, I feel that it’s strange too, to have a query that returns multiple rows for the same resource. But I don’t know how to do this any other way, maybe I’m on the wrong track altogether, because it just hit me that the original request (the one getting all rows for resources with categories matching ANY in the list) does quite not fulfill my requirement either…</p>
<p>Here’s my requirement as a whole:</p>
<p>First of all, I think the model of this part of the db might be helpful.</p>
<p><img src="https://i.stack.imgur.com/clxX8.png" alt="enter image description here"></p>
<p>(BTW category has a relation with itself also because it is stored as a hierarchy, using the adjacency model, where each category stores its parent id, if anyone was wondering about that arrow...)</p>
<p>1: Find all resources where a category matches ANY of the values in the list. But (this is where that was insufficient) for each of these resources, I need to know the resource along with all of the categories it has…</p>
<p>Let me explain the point of this with a simple example:</p>
<p>This is a many to many relationship as you can see. A resource (e.g let’s say with the title ”Introduction to carpentry in 18th century New England”) can be associated with many categories (e.g category.name = ”subject” value = ”Carpentry”, category.name=”subject” value = ”Wood”, category.name=”subject” value = ”New England”, category.name=”subject” value = ”History”). Note that this example is simplified, but you see the basic idea.</p>
<p>Now, if a user searches for a resource matching ANY of the categories ”Carpentry” and ”Painting”, the resource ”Introduction to carpentry in 18th century New England” should show up in the results, since one of its categories matched. But, here’s the rub, and why Gordon felt my request was strange: in the search result I want to present to the user, I want to list the title ”Introduction to carpentry in 18th century New England” along with a column showing all the categories that title is classified with, even though the user didn’t search for them - in order to give a better overview of the complete subject matter of this resource.</p>
<p>So how can I do that? The only way I could think of was the first statement in my question, but as I said it just hit me that it doesnt’ give me all categories a resource might have, only the ones actually searched for… </p>
<p>Of course I could do a query for the results first, only getting one row for each. And then do a second query, finding all categories for each resource in the results. But if the first query gives me 1000 results (which will be common), then to get the categories for all of these I would have to do 1000 queries to get the categories for each… Sounds like that would give me performance issues… </p>
<p>Am I thinking about this the wrong way? Is there another way to accomplish what I want to do? I.e give me the resources the query selects, along with all of that resource’s associated categories...</p>
<p>2: Well, after that long explanation, the second requirement is simpler to explain: again the same thing about getting all categories back for a resource selected, but this time the selection in the query should only get those resources that match ALL of the provided values. However, just because I provide all of the values in the query again doesn’ mean that I already have all the categories, since each resource in the results may actually have more (and other) categories and I need those too when presenting the results as mentioned in the first (ANY) requirement.</p>
| 0 | 1,585 |
AlertDialog do not show positive and negative button
|
<p>I used AlertDialog to alert user confirm delete. I check on my device (Android 5.1) and it show well</p>
<p><a href="https://i.stack.imgur.com/c6WhP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/c6WhP.png" alt="enter image description here"></a></p>
<p>But on some another device (also run Android 5.1), the dialog missed positive and negative button.</p>
<p><a href="https://i.stack.imgur.com/b5psH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/b5psH.png" alt="enter image description here"></a></p>
<p>I checked and found that devices happen this issue have a medium resolution (960x540, 854x480). </p>
<p>Is resolution relate with this issue ?
If not, can you tell me the reason and how to fix this issue ?</p>
<p>My code for display dialog:</p>
<pre><code> public static final Dialog yesNoDialog(Context context,
String message,
DialogInterface.OnClickListener yesAction, DialogInterface.OnClickListener noAction) {
AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.todoDialogLight);
builder.setTitle(context.getString(R.string.app_name))
.setMessage(message)
.setCancelable(false)
.setPositiveButton("YES", yesAction)
.setNegativeButton("NO", noAction);
return builder.create();
}
</code></pre>
<p><strong>And styles.xml</strong></p>
<pre><code> <style name="todoDialogLight" parent="Theme.AppCompat.Light.Dialog">
<!-- Used for the buttons -->
<item name="colorAccent">@color/colorPrimaryDark</item>
<item name="android:textStyle">bold</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">@color/colorText</item>
<!-- Used for the background -->
<!-- <item name="android:background">#4CAF50</item>-->
<item name="android:fontFamily">sans-serif</item>
<item name="android:windowAnimationStyle">@style/RemindDialogAnimation</item>
<item name="android:layout_width">@dimen/width_remind_dialog</item>
<item name="android:layout_height">wrap_content</item>
</style>
</code></pre>
| 0 | 1,087 |
Counting number of SELECTED rows in Oracle with PHP
|
<p>I'm doing this project for university, which is basically a movie database and for a couple of queries I need to know how many rows were selected. For now, there's 2 situations where I need this:</p>
<ul>
<li>Display a <strong>single movie</strong> information. I want the count of selected rows to know if the database contains the selected movie by the user. <em>Or is there a better solution for this?</em></li>
<li>That selected movie has genres, I need to know how many so that I can construct a string with the genres separated by <code>|</code> without adding one to the end of the string.</li>
</ul>
<p>With MySQL this is easy, I just query the database and use <code>mysql_num_rows()</code> but <code>oci_num_rows()</code> doesn't work quite the same for the SELECT statement.</p>
<p>The only solution I found with OCI/PHP is this:</p>
<pre><code>if(is_numeric($mid) && $mid > 0) {
$stid = oci_parse($db,
'SELECT COUNT(*) AS NUM_ROWS
FROM movies
WHERE mid = '.$mid
);
oci_define_by_name($stid, 'NUM_ROWS', $num_rows);
oci_execute($stid);
oci_fetch($stid);
if($num_rows > 0) {
$stid = oci_parse($db,
'SELECT title, year, synopsis, poster_url
FROM movies
WHERE mid = '.$mid
);
oci_execute($stid);
$info = oci_fetch_assoc($stid);
$stid = oci_parse($db,
'SELECT COUNT(*) AS NUM_ROWS
FROM genres g, movies_genres mg
WHERE mg.mid = '.$mid.' AND g.gid = mg.gid'
);
oci_define_by_name($stid, 'NUM_ROWS', $num_rows);
oci_execute($stid);
oci_fetch($stid);
$stid = oci_parse($db,
'SELECT g.name AS genre
FROM genres g, movies_genres mg
WHERE mg.mid = '.$mid.' AND g.gid = mg.gid');
oci_execute($stid);
$genres_list = null;
while($row = oci_fetch_assoc($stid)) {
$genres_list .= $row['GENRE'];
if($num_rows > 1) {
$genres_list .= ' | ';
$num_rows--;
}
}
$Template->assignReferences(array(
'Index:LinkURI' => $link_uri,
'Movie:Title' => $info['TITLE'],
'Movie:Year' => $info['YEAR'],
'Movie:GenresList' => $genres_list,
'Movie:Synopsis' => $info['SYNOPSIS'],
'Movie:PosterURL' => $info['POSTER_URL'] // FIX: Handle empty poster link
));
$Template->renderTemplate('movieinfo');
} else {
// TODO: How to handle this error?
}
} else {
// TODO: How to handle this error?
}
</code></pre>
<p>But I don't like it. I always need to make 2 queries to count the rows and then select the actual data and there's too many lines of code just to count the rows.</p>
<p>This code doesn't show it (haven't done it yet cause I'm looking for a better solution) but I'll also need to do the same for the movie directors/writers.</p>
<p>Is there any better and <strong>simpler</strong> solution to accomplish this or this is the only way?</p>
<p>I could add separators in the fetch loop until it finishes and then use PHP functions to trim the last separator from the string, but for this project I'm forced to use SEQUENCES, VIEWS, FUNCTIONS, PROCEDURES and TRIGGERS. Do any of these help solving my problem?</p>
<p>I know what SEQUENCES are, I'm using them already but I don't see how can they help.</p>
<p>For VIEWS, they probably wouldn't simplify the code that much (<em>it's basically a stored query right?</em>). For FUNCTIONS, PROCEDURES and TRIGGERS, as far as I understand them, I can't see how can they be of any help either.</p>
<p>Solutions?</p>
| 0 | 1,779 |
Multi-Schema Privileges for a Table Trigger in an Oracle Database
|
<p>I'm trying to write a table trigger which queries another table that is outside the schema where the trigger will reside. Is this possible? It seems like I have no problem querying tables in my schema but I get:</p>
<pre><code>Error: ORA-00942: table or view does not exist
</code></pre>
<p>when trying trying to query tables outside my schema.</p>
<p><strong>EDIT</strong></p>
<p>My apologies for not providing as much information as possible the first time around. I was under the impression this question was more simple.</p>
<p>I'm trying create a trigger on a table that changes some fields on a newly inserted row based on the existence of some data that may or may not be in a table that is in another schema.</p>
<p>The user account that I'm using to create the trigger does have the permissions to run the queries independently. In fact, I've had my trigger print the query I'm trying to run and was able to run it on it's own successfully. </p>
<p>I should also note that I'm building the query dynamically by using the EXECUTE IMMEDIATE statement. Here's an example:</p>
<pre><code>CREATE OR REPLACE TRIGGER MAIN_SCHEMA.EVENTS
BEFORE INSERT
ON MAIN_SCHEMA.EVENTS REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
DECLARE
rtn_count NUMBER := 0;
table_name VARCHAR2(17) := :NEW.SOME_FIELD;
key_field VARCHAR2(20) := :NEW.ANOTHER_FIELD;
BEGIN
CASE
WHEN (key_field = 'condition_a') THEN
EXECUTE IMMEDIATE 'select count(*) from OTHER_SCHEMA_A.'||table_name||' where KEY_FIELD='''||key_field||'''' INTO rtn_count;
WHEN (key_field = 'condition_b') THEN
EXECUTE IMMEDIATE 'select count(*) from OTHER_SCHEMA_B.'||table_name||' where KEY_FIELD='''||key_field||'''' INTO rtn_count;
WHEN (key_field = 'condition_c') THEN
EXECUTE IMMEDIATE 'select count(*) from OTHER_SCHEMA_C.'||table_name||' where KEY_FIELD='''||key_field||'''' INTO rtn_count;
END CASE;
IF (rtn_count > 0) THEN
-- change some fields that are to be inserted
END IF;
END;
</code></pre>
<p>The trigger seams to fail on the EXECUTE IMMEDIATE with the previously mentioned error.</p>
<p><strong>EDIT</strong></p>
<p>I have done some more research and I can offer more clarification.</p>
<p>The user account I'm using to create this trigger is not MAIN_SCHEMA or any one of the OTHER_SCHEMA_Xs. The account I'm using (ME) is given privileges to the involved tables via the schema users themselves. For example (USER_TAB_PRIVS):</p>
<pre><code>GRANTOR GRANTEE TABLE_SCHEMA TABLE_NAME PRIVILEGE GRANTABLE HIERARCHY
MAIN_SCHEMA ME MAIN_SCHEMA EVENTS DELETE NO NO
MAIN_SCHEMA ME MAIN_SCHEMA EVENTS INSERT NO NO
MAIN_SCHEMA ME MAIN_SCHEMA EVENTS SELECT NO NO
MAIN_SCHEMA ME MAIN_SCHEMA EVENTS UPDATE NO NO
OTHER_SCHEMA_X ME OTHER_SCHEMA_X TARGET_TBL SELECT NO NO
</code></pre>
<p>And I have the following system privileges (USER_SYS_PRIVS):</p>
<pre><code>USERNAME PRIVILEGE ADMIN_OPTION
ME ALTER ANY TRIGGER NO
ME CREATE ANY TRIGGER NO
ME UNLIMITED TABLESPACE NO
</code></pre>
<p>And this is what I found in the Oracle documentation:</p>
<blockquote>
<p>To create a trigger in another user's
schema, or to reference a table in
another schema from a trigger in your
schema, you must have the CREATE ANY
TRIGGER system privilege. With this
privilege, the trigger can be created
in any schema and can be associated
with any user's table. In addition,
the user creating the trigger must
also have EXECUTE privilege on the
referenced procedures, functions, or
packages.</p>
</blockquote>
<p>Here: <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_triggers.htm" rel="nofollow noreferrer">Oracle Doc</a></p>
<p>So it looks to me like this should work, but I'm not sure about the "EXECUTE privilege" it's referring to in the doc.</p>
| 0 | 1,495 |
Django Rest Framework - Missing Static Directory
|
<p>I have recently started a Digital Ocean server with a pre-installed Django image on Ubuntu 14.04. I wanted to create an API, and have decided on the Django Rest Framework. I installed the Django Rest Framework exactly according to <a href="http://www.django-rest-framework.org/" rel="noreferrer">http://www.django-rest-framework.org/</a>.</p>
<p><em>Here is what the tutorial site looks like when I access it on my server.</em></p>
<p><img src="https://i.stack.imgur.com/rzUyY.png" alt="enter image description here"></p>
<p>As you can see, it does not look like the site on the rest framework tutorial website. This is because of the fact that when I view the source code of my site, all of the <code>/static/rest_framework/*</code> files give me a 404 error.</p>
<p><em>Here is my settings.py file in the Django 'django_project' root directory.</em></p>
<pre><code>"""
Django settings for django_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7Vnib8zBUEV3LfacGKi2rT185N36A8svyq8azJLvNpv7BxxzMK'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'yj4SM6qcP0',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
</code></pre>
<p>Can anyone help me fix this missing /static/rest_framework/ location error? If I am going to have an API for my application I would like it to be a good looking one.</p>
<p>Let me know if you need anything else to help you fix this, and thank you in advance for your help.</p>
| 0 | 1,390 |
Disable point-of-interest information window using Google Maps API v3
|
<p>I have a custom map with an information bubble and custom markers. When I zoom into points of interest such as parks and universities appear and when I click an information window opens. How do I disable the info window?</p>
<p>My code is as follows:</p>
<pre><code>var geocoder;
var map;
var infoBubble;
var dropdown = "";
var gmarkers = [];
var hostel_icon = new google.maps.MarkerImage('/resources/hostel_blue_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));
var bar_icon = new google.maps.MarkerImage('/resources/bar_red_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));
var icon_shadow = new google.maps.MarkerImage('/resources/myicon_shadow.png',
new google.maps.Size(45,32),
new google.maps.Point(0,0),
new google.maps.Point(12,32));
var customIcons = {
hostel: {
icon: hostel_icon,
shadow: icon_shadow
},
bar: {
icon: bar_icon,
shadow: icon_shadow
}
};
function initialize() {
var latlng = new google.maps.LatLng(12.82364, 26.29987);
var myMapOptions = {
zoom: 2,
center: latlng,
panControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},
navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT}
}
map = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
infoBubble = new InfoBubble({
shadowStyle: 0,
padding: 0,
backgroundColor: 'rgb(57,57,57)',
borderRadius: 5,
arrowSize: 10,
borderWidth: 1,
maxWidth: 400,
borderColor: '#2c2c2c',
disableAutoPan: false,
hideCloseButton: true,
arrowPosition: 50,
backgroundClassName: 'phoney',
arrowStyle: 0
});
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml_2.php", function(data) {
var xml = parseXml(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var bar_name = markers[i].getAttribute("bar_name");
var hostel_name = markers[i].getAttribute("hostel_name");
var street = markers[i].getAttribute("street");
var city = markers[i].getAttribute("city");
var postcode = markers[i].getAttribute("postcode");
var country = markers[i].getAttribute("country");
var page = markers[i].getAttribute("page");
var map_photo = markers[i].getAttribute("map_photo");
var type = markers[i].getAttribute("type");
var category = markers[i].getAttribute("category");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = '<div class="infowindow"><div class="iwPhoto" style="width: 105px; height: 65px;">' + "<a href='" + page + "'><img src='" + map_photo + "' alt=''/></a>" + '</div><div class="iwName" style="height: 24px;">' + "<a href='" + page + "'>" + hostel_name + "</a>" + '</div><div class="iwCategory" style="height: 15px;">' + category + '</div><div class="iwCity" style="height: 29px;">' + "<a href='" + page + "'>" + city + "</a>" + '<div class="iwArrow" style="width: 29px; height: 29px;">' + "<a href='" + page + "'><img src='/resources/arrow.png'/></a>" + '</div></div></div>';
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
title: bar_name
});
marker.bar_name = bar_name;
marker.category = category;
bindInfoBubble(marker, map, infoBubble, html, bar_name);
gmarkers.push(marker);
str = '<option selected> - Select a club - </option>';
for (j=0; j < gmarkers.length; j++){
str += '<option value="'+gmarkers[j].bar_name+'">'+gmarkers[j].bar_name+', '+gmarkers[j].category+'</option>';
}
var str1 ='<form name="form_city" action=""><select style="width:150px;" id="select_city" name="select_cityUrl" onchange="handleSelected(this);">';
var str2 ='</select></form>';
dropdown = str1 + str + str2;
}
document.getElementById("dd").innerHTML = dropdown;
});
}
function handleSelected(opt) {
var indexNo = opt[opt.selectedIndex].index;
google.maps.event.trigger(gmarkers[indexNo-1], "click");
}
function bindInfoBubble(marker, map, infoBubble, html) {
google.maps.event.addListener(marker, 'click', function() {
infoBubble.setContent(html);
infoBubble.open(map, marker);
google.maps.event.addListener(map, "click", function () {
infoBubble.close();
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
</code></pre>
| 0 | 2,704 |
How to post form login using jsoup?
|
<p>i want to login in <a href="https://www.desco.org.bd/ebill/login.php" rel="noreferrer">here</a>
<img src="https://i.stack.imgur.com/oj84K.png" alt="enter image description here">
source code </p>
<pre><code><HTML><HEAD><TITLE>:: Dhaka Electric Supply Company Limited (DESCO)::</TITLE>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<META http-equiv=Pragma content=no-cache>
<META http-equiv=imagetoolbar content=no>
<META content="Home Page of Dhaka Electric Supply Company Limited" name=description>
<META content="MSHTML 6.00.2900.2180" name=GENERATOR>
<style type="text/css">
img{
border:0px;
}
</style>
<script type="text/javascript" src="js/ajax-dynamic-content.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/ajax-tooltip.js"></script>
<link rel="stylesheet" href="css/ajax-tooltip.css" media="screen" type="text/css">
<link rel="stylesheet" href="css/ajax-tooltip-demo.css" media="screen" type="text/css">
<LINK media=all href="css/global.css" type=text/css rel=stylesheet>
</HEAD>
<BODY>
<DIV id=over style="DISPLAY: none"></DIV>
<DIV class=baselayout>
<DIV class=pagetopshadow></DIV>
<DIV class=basebg>
<DIV class=pageleft></DIV>
<DIV class=pagecenter>
<DIV id=Header>
</DIV>
<DIV id=Menu>
</DIV>
<DIV id=HomeContent>
<DIV class=right>
<DIV class=homeintro>
<div style="padding-top: 0px;">
<script>
function checkLogin()
{ if( document.login.username.value == '')
{
alert( 'Please enter your account number' );
return false;
}return true;
}
alert('Payments through VISA and Master Card are stopped by DBBL. only DBBL Nexus card is allowed.');
</script>
<form NAME='login' METHOD='POST' ACTION='authentication.php'>
<table width="350" height="181"cellpadding='0' cellspacing='0' border='0' style="border:#e5e5e5 0px solid; BACKGROUND: url(css/images/top9.png) no-repeat left top;" align="center">
<tr> <td rowspan="6" style="padding-left:15px;"><img src="css/images/groupperms.gif" width="50" height="50"><td></tr>
<tr>
<td colspan="2" height="50"></td>
</tr>
<tr>
<td nowrap><span class="textcolor1">Account No. </span></td>
<td><input type='text' name='username' style="border:#cacaca 2px solid; color:#000099;" value=''></td></tr>
<tr>
<td> <a class="uiTooltip" href="#" onMouseOver="ajax_showTooltip(window.event,'tooltip/help.html',this);return false" onMouseOut="ajax_hideTooltip()">Help</a></td>
<td><input name="login" type='submit' value='Login' style="width:80px; font-family:Arial, Helvetica, sans-serif; font-weight:bold; color:#FFFFFF; border:#000000 2px solid; cursor:pointer; background-color: #1b4585;" border="0" align="right" title="Login" onClick="return checkLogin();"/></td>
</tr>
</table>
</form>
<table width="630" border="0" cellspacing="2" cellpadding="2" align="center" bgcolor="#FFFFFF" bordercolor="#FFFFFF">
<tr>
<td width="80"></td>
<td><img src="images/right_3.gif"/></td>
<td><span class="textcolor"><strong><a href='https://www.desco.org.bd/index.php?page=internet-bill-payment' target="_blank" class="uiTooltip">Before, use this facility/services please read instructions...</a></strong></span></td>
</tr>
</table>
<p align="center" class="textcolor"><strong><a href='https://www.desco.org.bd' class="uiTooltip">Back Home</a></strong></p>
<table align="center" width="135" border="0" cellpadding="2" cellspacing="0" title="Click to Verify - This site chose VeriSign SSL for secure e-commerce and confidential communications.">
<tr>
<td width="135" align="center" valign="top"><script type="text/javascript" src="https://seal.verisign.com/getseal?host_name=www.desco.org.bd&amp;size=S&amp;use_flash=YES&amp;use_transparent=YES&amp;lang=en"></script><br />
<a href="http://www.verisign.com/ssl-certificate/" target="_blank" style="color:#000000; text-decoration:none; font:bold 7px verdana,sans-serif; letter-spacing:.5px; text-align:center; margin:0px; padding:0px;">ABOUT SSL CERTIFICATES</a></td>
</tr>
</table>
</div>
<div align="center" style="padding-top:10px;">
<CENTER><B>
Total Visits: 1</B></CENTER>
</div>
</DIV>
</DIV>
</DIV>
</DIV>
<DIV class=pageright></DIV></DIV>
<DIV class=pagebotshadow>
<DIV id=Footer>Copyright © 2010 Dhaka Electric Supply Company Ltd. All rights reserved.</DIV>
</DIV>
</DIV>
</BODY>
</HTML>
</code></pre>
<p>basically below code is the form</p>
<pre><code><form NAME='login' METHOD='POST' ACTION='authentication.php'>
<table width="350" height="181"cellpadding='0' cellspacing='0' border='0' style="border:#e5e5e5 0px solid; BACKGROUND: url(css/images/top9.png) no-repeat left top;" align="center">
<tr> <td rowspan="6" style="padding-left:15px;"><img src="css/images/groupperms.gif" width="50" height="50"><td></tr>
<tr>
<td colspan="2" height="50"></td>
</tr>
<tr>
<td nowrap><span class="textcolor1">Account No. </span></td>
<td><input type='text' name='username' style="border:#cacaca 2px solid; color:#000099;" value=''></td></tr>
<tr>
<td> <a class="uiTooltip" href="#" onMouseOver="ajax_showTooltip(window.event,'tooltip/help.html',this);return false" onMouseOut="ajax_hideTooltip()">Help</a></td>
<td><input name="login" type='submit' value='Login' style="width:80px; font-family:Arial, Helvetica, sans-serif; font-weight:bold; color:#FFFFFF; border:#000000 2px solid; cursor:pointer; background-color: #1b4585;" border="0" align="right" title="Login" onClick="return checkLogin();"/></td>
</tr>
</table>
</form>
</code></pre>
<p><img src="https://i.stack.imgur.com/HR6Q9.png" alt="enter image description here"></p>
<p>i am trying this</p>
<pre><code>package jsouptest;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JsouptTest {
public static void main(String[] args) throws Exception {
Connection.Response loginForm = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
.method(Connection.Method.GET)
.execute();
Document document = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
.data("cookieexists", "false")
.data("username", "32007702")
.data("login", "Login")
.cookies(loginForm.cookies())
.post();
System.out.println(document);
}
}
</code></pre>
<p>but im getting below error</p>
<pre><code>Exception in thread "main" java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:152)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
at sun.security.ssl.InputRecord.read(InputRecord.java:480)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:439)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:424)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:178)
at jsouptest.JsouptTest.main(JsouptTest.java:12)
</code></pre>
<p>am is missing something? how to fix it?</p>
| 0 | 3,968 |
Value of type java.lang.String cannot be converted to JSONArray in Android(repost)
|
<p>I am repost this coz I dont find the solution for this problem...</p>
<p>here is error</p>
<pre><code>org.json.JSONException:Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray
</code></pre>
<p>here is JSON output:</p>
<pre><code>[{"name":"Muhaimin","address":"Sylhet","bgroup":"o+"}]
</code></pre>
<p>here is class code:</p>
<pre><code>entpackage com.example.blood;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.enableDefaults();
resultView=(TextView) findViewById(R.id.result);
getData();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getData()
{
String result="";
InputStream isr=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://10.0.2.2/blood/index.php");
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("Accept", "JSON");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
isr=entity.getContent();
}catch(Exception e){
String err=e.toString();
resultView.setText("Could not connect to database"+err);
Log.e("error", err);
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line=null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}catch(Exception e){
String err2=e.toString();
resultView.setText("Error coverting result"+err2);
Log.e("error", err2);
}
try{
String s="";
JSONArray jArray=new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json=jArray.getJSONObject(i);
s= s +
"Name :"+json.getString("name")+"\n"+
"Blood Group :"+json.getString("bgroup")+"\n" +
"Address :"+json.getString("address")+"\n\n";
}
resultView.setText(s);
}catch(Exception e){
String err1=e.toString();
resultView.setText("xxx"+err1);
Log.e("error", err1);
}
}
}
</code></pre>
<p>here is php code:</p>
<pre><code> <?php
$con=mysql_connect("localhost","root","","BloodDB");
mysql_select_db("BloodDB",$con);
$result=mysql_query("SELECT name,address,bgroup FROM tbl_blood_donor");
while($row=mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
</code></pre>
<p>Now how to solve this problem.I am working in localhost.thanks in advance</p>
| 0 | 1,337 |
ERR_TOO_MANY_REDIRECTS in backoffice when running Prestashop in Docker
|
<p>I'm trying to make a docker environment for a Prestashop project. I have it almost working but for some reason, the back office is inaccessible - it gives me a ERR_TOO_MANY_REDIRECTS error.</p>
<p>I changed the urls in <code>shop_url</code> table and changed PS_SHOP_DOMAIN and PS_SHOP_DOMAIN_SSL to no vain. I tried to disable friendly URLs, enable/disable SSL - but the problem persists.</p>
<p>I'm using a custom image for a webserver:</p>
<p><code>luken-wodby-nginx-prestashop</code> Dockerfile:</p>
<pre><code>FROM wodby/nginx:1.10
ENV WODBY_DIR_FILES /mnt/files
RUN rm /etc/gotpl/default-vhost.conf.tpl && \
mkdir -p $WODBY_DIR_FILES && \
mkdir -p /var/log/nginx
COPY prestashop.conf.tpl /etc/gotpl/
COPY init/* /docker-entrypoint-init.d/
</code></pre>
<p>docker-compose.yml:</p>
<pre><code>version: "2"
services:
mariadb:
image: wodby/mariadb:10.1-2.0.0
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: organic
MYSQL_USER: prestashop
MYSQL_PASSWORD: prestashop
volumes:
- ./database:/docker-entrypoint-initdb.d
ports:
- "33060:3306"
php:
image: wodby/php:5.6-2.0.0
environment:
PHP_SENDMAIL_PATH: /usr/sbin/sendmail -t -i -S mailhog:1025
PHP_XDEBUG: 1
PHP_XDEBUG_DEFAULT_ENABLE: 1
volumes:
- ./:/var/www/html
nginx:
image: luken-wodby-nginx-prestashop:latest
depends_on:
- php
environment:
NGINX_BACKEND_HOST: php
NGINX_SERVER_NAME: prestashop.docker.localhost
NGINX_SERVER_ROOT: /var/www/html/public_html
volumes:
- ./:/var/www/html
ports:
- "8000:80"
mailhog:
image: mailhog/mailhog
ports:
- "8002:8025"
</code></pre>
<p>Nginx virtual host configuration:</p>
<pre><code>server {
listen 80;
server_name {{ getenv "NGINX_SERVER_NAME" "prestashop" }};
root {{ getenv "NGINX_SERVER_ROOT" "/var/www/html/" }};
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
index index.php index.html;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
auth_basic off;
allow all;
log_not_found off;
access_log off;
}
# Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 1;
gzip_buffers 16 8k;
gzip_http_version 1.0;
gzip_types application/json text/css application/javascript;
rewrite ^/api/?(.*)$ /webservice/dispatcher.php?url=$1 last;
rewrite ^/([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$1$2$3.jpg last;
rewrite ^/([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$1$2$3$4.jpg last;
rewrite ^/([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$1$2$3$4$5.jpg last;
rewrite ^/([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg last;
rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg last;
rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg last;
rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg last;
rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg last;
rewrite ^/c/([0-9]+)(-[.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+.jpg$ /img/c/$1$2$3.jpg last;
rewrite ^/c/([a-zA-Z_-]+)(-[0-9]+)?/.+.jpg$ /img/c/$1$2.jpg last;
rewrite ^/images_ie/?([^/]+).(jpe?g|png|gif)$ /js/jquery/plugins/fancybox/images/$1.$2 last;
rewrite ^/order$ /index.php?controller=order last;
location /panel_adm/ { #Change this to your admin folder
if (!-e $request_filename) {
rewrite ^/.*$ /panel_adm/index.php last; #Change this to your admin folder
}
}
location / {
if (!-e $request_filename) {
rewrite ^/.*$ /index.php last;
}
}
location ~ .php$ {
fastcgi_split_path_info ^(.+.php)(/.*)$;
try_files $uri =404;
fastcgi_keep_conn on;
include /etc/nginx/fastcgi_params;
fastcgi_pass backend; #Change this to your PHP-FPM location
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
</code></pre>
<p>Website works just fine, only the back office is inaccessible and gives ERR_TOO_MANY_REDIRECTS error.</p>
<p>Any ideas what can be wrong?</p>
| 0 | 2,583 |
Why Laravel Vite Directive Not Working in My Project?
|
<p>I installed and configured laravel breeze and blade according to the <a href="https://laravel.com/docs/9.x/starter-kits#breeze-and-blade" rel="noreferrer">documentation</a> given by laravel. By default it uses Vite but somehow @vite directive is not working in my project and I don't know what I miss.</p>
<p><strong>tailwind.config.js</strong></p>
<pre><code>const defaultTheme = require('tailwindcss/defaultTheme');
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
'./storage/framework/views/*.php',
'./resources/views/**/*.blade.php',
],
theme: {
extend: {
fontFamily: {
sans: ['Nunito', ...defaultTheme.fontFamily.sans],
},
},
},
plugins: [require('@tailwindcss/forms')],
};
</code></pre>
<p><strong>vite.config.js</strong></p>
<pre><code>import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel([
'resources/css/app.css',
'resources/js/app.js',
]),
]
});
</code></pre>
<p>The vite is compiling properly my js and css assets:
<a href="https://i.stack.imgur.com/70E9x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/70E9x.png" alt="enter image description here" /></a></p>
<p>I then created a test blade template with <code>@vite</code> directive:</p>
<pre><code><!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">
<!-- Scripts -->
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
<div class="font-sans text-gray-900 antialiased">
Hello World
</div>
</body>
</html>
</code></pre>
<p>My test route:</p>
<pre><code>Route::get('/nice', function () {
return view('test');
});
</code></pre>
<p>The output below shows that the <code>@vite</code> is not generating the appropriate script and link assets tag:</p>
<p><a href="https://i.stack.imgur.com/WpI6z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WpI6z.png" alt="enter image description here" /></a></p>
<p>My development environment is homestead, and I have laravel mix alongside since I am slowly upgrading our front-end to vite. I hope somebody here will be able to help me fix the issues and thank you.</p>
| 0 | 1,240 |
WPF Force rebind
|
<p>I have an object that can't inherit DependencyObject OR use NotifyPropertyChanged, and I've binded it to quite a few controls, so when the properties change, I don't want to go to each control and change it's value on the code, so I'm thinking there must be a way to tell the XAML to "Rebind" all that it's bound to with one or two lines of code, instead of going:</p>
<pre><code>label1.Content = myObject.DontNotifyThis;
label2.Content = myObject.DontNotifyThisEither;
label3.Content = myObject.DontEvenThinkOfNotifyingThis;
label4.Content = myObject.NotSoFastPal;
</code></pre>
<p>So on, so forth...</p>
<p>This is an oversimplified example:</p>
<p>XAML:</p>
<pre><code><Window x:Class="StackOverflowTests.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" x:Name="window1" Height="300" Width="300" Loaded="window1_Loaded">
<Grid x:Name="gridMain">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="{Binding Status}" ContentStringFormat="Today's weather: {0}" />
<Label Grid.Row="2" Content="{Binding Temperature}" ContentStringFormat="Today's temperature: {0}" />
<Label Grid.Row="1" Content="{Binding Humidity}" ContentStringFormat="Today's humidity: {0}" />
</Grid>
</Window>
</code></pre>
<p>C#:</p>
<pre><code>using System.Windows;
namespace StackOverflowTests
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
Weather weather = new Weather("Cloudy", "60F", "25%");
public Window1()
{
InitializeComponent();
this.DataContext = weather;
}
private void window1_Loaded(object sender, RoutedEventArgs e)
{
weather.Status = "Sunny";
weather.Temperature = "80F";
weather.Humidity = "3%";
}
}
class Weather
{
public string Status { get; set; }
public string Temperature { get; set; }
public string Humidity { get; set; }
public Weather(string status, string temperature, string humidity)
{
this.Status = status;
this.Temperature = temperature;
this.Humidity = humidity;
}
}
}
</code></pre>
<p>I found a way to do it, but it's not elegant at all, and unfortunatelly, I can't just set the DataContext to a new instance of weather, it needs to be the SAME reference (that's why I set it to null so it changes):</p>
<pre><code>private void window1_Loaded(object sender, RoutedEventArgs e)
{
weather.Status = "Sunny";
weather.Temperature = "80F";
weather.Humidity = "3%";
// bad way to do it
Weather w = (Weather)this.DataContext;
this.DataContext = null;
this.DataContext = w;
}
</code></pre>
<p>Thanks in advance!</p>
| 0 | 1,277 |
Activity has leaked window that was originally added here
|
<p>I am getting this error when i try to execute this class file.I am not getting what the error is..?can anyone pls identify where i am going wrong..?</p>
<p><strong>Mnst.class</strong></p>
<pre><code> //this is class file
public class Mnst extends AppCompatActivity implements
View.OnClickListener {
Button btnDatePicker,save;
EditText txtDate;
EditText txtnormal;
private int mYear, mMonth, mDay;
String value;
private String vault;
public static final String SHARED_PREF_NAME = "myloginapp";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
public static final String MYLAST_SHARED_PREF = "my_last_period";
public static final String NORMAL_SHARED_PREF = "normal_cycle";
public static final String REVISED_SHARED_PREF = "revised_cycle";
public static final String NEXT_SHARED_PREF = "next_period_date";
public static final String PREDICTEDSTART_SHARED_PREF = "predicted_start_date";
public static final String PREDICTEDEND_SHARED_PREF = "predicted_end_date";
DatePickerDialog datePickerDialog;
private boolean loggedIn = false;
public static final String UPLOAD_URL = "http://oursite.com/predict.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mnst);
btnDatePicker=(Button)findViewById(R.id.btn_date);
save = (Button)findViewById(R.id.save);
txtDate=(EditText)findViewById(R.id.in_date);
txtnormal = (EditText) findViewById(R.id.in_date1);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
btnDatePicker.setOnClickListener(this);
save.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == btnDatePicker) {
// Get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
value = txtDate.getText().toString();
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
if( v == save)
{
registerUser();
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}
}
/*@Override
protected void onDestroy() {
if(datePickerDialog !=null && datePickerDialog.isShowing())
{
//<HERE I WANT THE STATE TO BE SAVED IN THE BUNDLE>
datePickerDialog.dismiss();
}
super.onDestroy();
}*/
private void registerUser() {
final String vault_no = vault;
final String my_last_period = txtDate.getText().toString();
final String normal_cycle = txtnormal.getText().toString();
register(vault_no,my_last_period,normal_cycle);
}
public void register(String vault_no , String my_last_period , String normal_cycle){
class RegisterUser extends AsyncTask<String, Integer, JSON> {
ProgressDialog loading;
RequestHandler7 ruc = new RequestHandler7();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Mnst.this, "Please Wait",null, true, true);
}
@SuppressWarnings("deprecation")
@Override
protected void onPostExecute(JSON s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Welcome to Miisky",Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences1 = Mnst.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences1.edit();
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(MYLAST_SHARED_PREF, s.my_last_period);
editor.putString(NORMAL_SHARED_PREF, s.normal_cycle);
editor.putString(REVISED_SHARED_PREF, s.revised_cycle);
editor.putString(NEXT_SHARED_PREF, s.next_period_date);
editor.putString(PREDICTEDSTART_SHARED_PREF, s.predicted_start_date);
editor.putString(PREDICTEDEND_SHARED_PREF, s.predicted_end_date);
editor.apply();
Intent i = new Intent(Mnst.this,DisplayMnst.class);
startActivity(i);
}
@Override
protected JSON doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("vault_no", params[0]);
data.put("my_last_period" , params[1]);
data.put("normal_cycle", params[2]);
JSON result = ruc.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
RegisterUser ru = new RegisterUser();
ru.execute(vault_no,my_last_period,normal_cycle);
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>I have added the RequestHandler class..</p>
<p><strong>RequestHandler7</strong></p>
<pre><code>public class RequestHandler7 {
public JSON sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return new Gson().fromJson(sb.toString(),JSON.class);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
</code></pre>
<hr>
<p><strong>Log</strong></p>
<p>This is my logcat error..here it is showing "Activity com.example.android.Mnst has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here"</p>
<pre><code>E/WindowManager: Activity com.example.miisky.Mnst has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here
android.view.WindowLeaked: Activity com.example.miisky.Mnst has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:104)
at com.example.miisky.Mnst$1RegisterUser.onPreExecute(Mnst.java:132)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.example.miisky.Mnst.register(Mnst.java:178)
at com.example.miisky.Mnst.registerUser(Mnst.java:118)
at com.example.miisky.Mnst.onClick(Mnst.java:95)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
| 0 | 4,733 |
Access the Repeater.Item.Count value within a codebehind method
|
<p>I have a repeater on my page:</p>
<pre><code><asp:Repeater id="attachmentsRepeater" runat="server">
<HeaderTemplate>
<%
if (attachmentsRepeater.Items.Count > 0) {
if (attachmentsRepeater.Items.Count == 1) {
Response.Write("<h3>Attachment</h3>");
Response.Write("<p>");
} else {
Response.Write("<h3>Attachments</h3>");
Response.Write("<ul>");
}
}
%>
</HeaderTemplate>
<ItemTemplate>
<%# OutputAttachment(Container)%>
</ItemTemplate>
<FooterTemplate>
<%
if (attachmentsRepeater.Items.Count > 0) {
if (attachmentsRepeater.Items.Count == 1) {
Response.Write("</p>");
} else {
Response.Write("</ul>");
}
}
%>
</FooterTemplate>
</asp:Repeater>
</code></pre>
<p>The original ItemTemplate code looked like this:</p>
<pre><code><ItemTemplate>
<%
if (attachmentsRepeater.Items.Count > 0) {
if (attachmentsRepeater.Items.Count > 1) {
Response.Write("<li>");
}
%>
<a href="<%# DataBinder.Eval(Container.DataItem, "location") %>">
<%# DataBinder.Eval(Container.DataItem, "name") %>
</a>
<%
if (attachmentsRepeater.Items.Count > 1) {
Response.Write("<li>");
}
}
%>
</ItemTemplate>
</code></pre>
<p>In the codebehind, I would like to access the number of Items in the Repeater (line 4):</p>
<pre><code>public string OutputAttachment(RepeaterItem Container) {
string returnValue = "";
Repeater ContainerParent = (Repeater)Container.Parent;
if (attachmentsRepeater.Items.Count > 0) {
if (attachmentsRepeater.Items.Count > 1) {
returnValue += "<li>";
}
returnValue += "<a href=\"" + DataBinder.Eval(Container.DataItem, "location");
if (DataBinder.Eval(Container.DataItem, "location").ToString().EndsWith("/")) {
returnValue += DataBinder.Eval(Container.DataItem, "name");
}
returnValue += ">" + DataBinder.Eval(Container.DataItem, "name") + "</a>";
if (attachmentsRepeater.Items.Count > 1) {
returnValue += "</li>";
}
}
return returnValue;
}
</code></pre>
<p>The code that is output is</p>
<pre><code><h3>Attachment</h3>
<p> </p>
</code></pre>
<p>From this output I know that Item.Count == 1 since there is output, the H3 is singular and there is a P tag. If Item.Count > 1, H3 would be plural and there would be a UL tag.</p>
<p>Is this codebehind method being run before the data is bound? Any workarounds for this? Thanks for your help.</p>
<p>This was working for me before, but I had to change it to fulfill a new requirement, which is when it stopped working.</p>
| 0 | 1,483 |
Calling a SQL Server stored procedure with linq service through c#
|
<p>I am new to Linq and trying to convert this SQL Server stored procedure into Linq, I am building a Silverlight business app and need to call on this procedure to return a grid of results. </p>
<p>I have multiple parameters that the users can use to search for particular pieces. They narrow down their search through the UI and when they hit the search button, the code behind takes all the arguments and sends it to my Linq service, which then needs to call on the stored procedure. </p>
<p>Here is the stored procedure.</p>
<pre class="lang-sql prettyprint-override"><code>ALTER PROCEDURE dbo.spSearchResults
@PieceType nvarchar(6) = '',
@FileType nvarchar(3) = '',
@Market nvarchar(6) = '',
@PieceNumber nvarchar(6) = '',
@Header1 nvarchar(50) = '',
@Header2 nvarchar(50) = '',
@Header3 nvarchar(50) = '',
@Header4 nvarchar(50) = '',
@JobNumber nvarchar(50)=' ',
@bShowInActive BIT = 0,
@UDAC1 nvarchar(50) = '',
@UDAC2 nvarchar(50) = '',
@UDAC3 nvarchar(50) = '',
@UDAC4 nvarchar(50) = ''
AS
BEGIN
SET NOCOUNT ON
SELECT J.*
FROM Job J
LEFT JOIN JobHeading H1 (NOLOCK) ON J.[JobNumber] = H1.[JobID]
LEFT JOIN JobHeading H2 (NOLOCK) ON J.[JobNumber] = H2.[JobID]
LEFT JOIN JobHeading H3 (NOLOCK) ON J.[JobNumber] = H3.[JobID]
LEFT JOIN JobHeading H4 (NOLOCK) ON J.[JobNumber] = H4.[JobID]
LEFT JOIN JobUDAC udac1 (NOLOCK) ON J.[JobNumber] = udac1.[JobID]
LEFT JOIN JobUDAC udac2 (NOLOCK) ON J.[JobNumber] = udac2.[JobID]
LEFT JOIN JobUDAC udac3 (NOLOCK) ON J.[JobNumber] = udac3.[JobID]
LEFT JOIN JobUDAC udac4 (NOLOCK) ON J.[JobNumber] = udac4.[JobID]
WHERE ((@PieceType = '') OR (PieceType = @PieceType))
AND ((@FileType = '') OR (FileType = @FileType))
AND ((@Market = '') OR (Market = @Market))
AND ((@PieceNumber = '') OR (PieceNumber = @PieceNumber))
AND ((@JobNumber = '') OR (JobNumber = @JobNumber))
AND (J.IsActive=1 OR @bShowInActive = 1)
AND (((@Header1 = '' AND @Header2 = '' AND @Header3 = '' AND @Header4 = '') OR
H1.HeadingRowID = @Header1)
OR (--@Header2=0 OR
H2.HeadingRowID = @Header2 )
OR (--@Header3=0 OR
H3.HeadingRowID = @Header3)
OR (--@Header4=0 OR
H4.HeadingRowID = @Header4))
AND (((@UDAC1 = '' AND @UDAC2 = '' AND @UDAC3 = '' AND @UDAC4 = '') OR
udac1.UDACRowID = @UDAC1)
OR (--@Header2=0 OR
udac2.UDACRowID = @UDAC2 )
OR (--@Header3=0 OR
udac3.UDACRowID = @UDAC3)
OR (--@Header4=0 OR
udac4.UDACRowID = @UDAC4))
</code></pre>
<p>In Linq I found that there are certain conversions to do and this is my attempt. </p>
<pre><code>var query = from j in Job
join JobHeading H1 in Job on headingRowID1 equals H1
join JobHeading H2 in Job on headingRowID2 equals H2
join JobHeading H3 in Job on headingRowID3 equals H3
join JobHeading H4 in Job on headingRowID4 equals H4
join JobUDAC udac1 in Job on udacRowID1 equals udac1
join JobUDAC udac2 in Job on udacRowID2 equals udac2
join JobUDAC udac3 in Job on udacRowID3 equals udac3
join JobUDAC udac4 in Job on udacRowID4 equals udac4
join PieceType in db on piece equals PieceType
join JobFileType in db on filetype equals JobFileType
join Book in db on market equals Book
join PieceNumber in db on pieceNumber equals PieceNumber
join JobNumber in db on jobNumber equals JobNumber
join Job in db on FindJobs equals db
where ((piece = string.Empty) || (PieceType = piece))
&& ((filetype = string.Empty) || (JobFileType = filetype))
&& ((market = string.Empty) || (Book = market))
&& ((pieceNumber = string.Empty) || (PieceNumber = pieceNumber))
&& ((jobNumber = string.Empty) || (JobNumber = jobNumber))
&& (showInActive = true)
&& ((((headingRowID1 = string.Empty) + (headingRowID2 = string.Empty) + (headingRowID3 = string.Empty) + (headingRowID4 = string.Empty)) ||
H1.HeadingRowID = headingRowID1)
|| (H2.HeadingRowID = headingRowID2)
|| (H3.HeadingRowID = headingRowID3)
|| (H4.HeadingRowID = headingRowID4))
&& ((((udacRowID1 = string.Empty) + (udacRowID2 = string.Empty) + (udacRowID3 = string.Empty) + (udacRowID4 = string.Empty)) ||
udac1.UDACRowID = udacRowID1)
|| (udac2.UDACRowID = udacRowID2)
|| (udac3.UDACRowID = udacRowID3)
|| (udac4.UDACRowID = udacRowID4))
select j.Job;
return query;
</code></pre>
<p>However, the beginning 'Job' has an error, and says 'could not find an implementation ... 'join' not found' Can anyone help translate? Or offer a better way to call the stored procedure with the code behind? Thanks</p>
| 0 | 2,501 |
java.util.zip.ZipException: invalid LOC header (bad signature)
|
<pre><code>Mar 14, 2017 12:46:24 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [org/springframework/security/authentication/AccountStatusUserDetailsChecker.class] from Jar [jar:file:/C:/dev/saml/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/springsecuritysaml/WEB-INF/lib/spring-security-core-3.1.2.RELEASE.jar!/] for annotations
java.util.zip.ZipException: invalid LOC header (bad signature)
at java.util.zip.ZipFile.read(Native Method)
at java.util.zip.ZipFile.access$1400(ZipFile.java:56)
at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:679)
at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:415)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read(BufferedInputStream.java:254)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at org.apache.tomcat.util.bcel.classfile.ClassParser.readID(ClassParser.java:236)
at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:113)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2055)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1931)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1897)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1882)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1314)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:873)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:371)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5355)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
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:745)
Mar 14, 2017 12:46:24 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [org/springframework/security/authentication/ProviderNotFoundException.class] from Jar [jar:file:/C:/dev/saml/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/springsecuritysaml/WEB-INF/lib/spring-security-core-3.1.2.RELEASE.jar!/] for annotations
java.util.zip.ZipException: invalid LOC header (bad signature)
at java.util.zip.ZipFile.read(Native Method)
at java.util.zip.ZipFile.access$1400(ZipFile.java:56)
at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:679)
at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:415)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read(BufferedInputStream.java:254)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at org.apache.tomcat.util.bcel.classfile.ClassParser.readID(ClassParser.java:236)
at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:113)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2055)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1931)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1897)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1882)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1314)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:873)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:371)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5355)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
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:745)
</code></pre>
<p>Inspite of clearing m2/repo folder and updating maven project, iam getting theses errors for all the jar files and for all the maven projects in my workspace .I have also set project facets and java build path, can anybody tell where the problem is?</p>
| 0 | 1,956 |
First chance System.Configuration.ConfigurationErrorsException "This element is not currently associated with any context"
|
<p>Does anyone know what this particular exception mean and how to fix it?</p>
<p>Note, that I am not asking for help on suppressing it in the Exceptions dialog. I want to understand the root cause of it and how to fix the cause itself, if at all possible.</p>
<p>Thanks.</p>
<p>P.S.</p>
<p>The line that causes FCE is:</p>
<pre><code>using (ServiceHost host = new ServiceHost(typeof(WcfPortal)))
</code></pre>
<p>Exception details:</p>
<pre><code>System.Configuration.ConfigurationErrorsException occurred
Message="This element is not currently associated with any context"
Source="System.Configuration"
BareMessage="This element is not currently associated with any context"
Line=0
StackTrace:
at System.Configuration.ConfigurationElement.get_EvaluationContext()
InnerException:
</code></pre>
<p>The call stack is:</p>
<pre><code>System.Configuration.dll!System.Configuration.ConfigurationElement.EvaluationContext.get() + 0x64 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceModelExtensionElement.System.ServiceModel.Configuration.IConfigurationContextProviderInternal.GetEvaluationContext() + 0x1f bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ConfigurationHelpers.GetEvaluationContext(System.ServiceModel.Configuration.IConfigurationContextProviderInternal provider = {System.ServiceModel.Configuration.ServiceDebugElement}) + 0x41 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceModelExtensionElement.GetConfigurationElementName() + 0x72 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceModelExtensionElement.ConfigurationElementName.get() + 0x3a bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement<System.ServiceModel.Configuration.BehaviorExtensionElement>.Add(System.ServiceModel.Configuration.BehaviorExtensionElement element = {System.ServiceModel.Configuration.ServiceDebugElement}) + 0x2a6 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceBehaviorElement.Add(System.ServiceModel.Configuration.BehaviorExtensionElement element = {System.ServiceModel.Configuration.ServiceDebugElement}) + 0x16b bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement<System.ServiceModel.Configuration.BehaviorExtensionElement>.DeserializeElementCore(System.Xml.XmlReader reader = {Element, Name="serviceDebug"}) + 0x1eb bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement<System.ServiceModel.Configuration.BehaviorExtensionElement>.DeserializeElement(System.Xml.XmlReader reader = {Element, Name="serviceDebug"}, bool serializeCollectionKey = false) + 0x2f bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceBehaviorElement.DeserializeElement(System.Xml.XmlReader reader = {Element, Name="serviceDebug"}, bool serializeCollectionKey = false) + 0x2b bytes
System.Configuration.dll!System.Configuration.ConfigurationElementCollection.OnDeserializeUnrecognizedElement(string elementName = "behavior", System.Xml.XmlReader reader = {Element, Name="serviceDebug"}) + 0xc0 bytes
System.Configuration.dll!System.Configuration.ConfigurationElement.DeserializeElement(System.Xml.XmlReader reader = {Element, Name="serviceDebug"}, bool serializeCollectionKey = false) + 0xf48 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServiceBehaviorElementCollection.DeserializeElement(System.Xml.XmlReader reader = {Element, Name="serviceDebug"}, bool serializeCollectionKey = false) + 0x2a bytes
System.Configuration.dll!System.Configuration.ConfigurationElement.DeserializeElement(System.Xml.XmlReader reader = {Element, Name="serviceDebug"}, bool serializeCollectionKey = false) + 0xe6c bytes
System.Configuration.dll!System.Configuration.ConfigurationSection.DeserializeSection(System.Xml.XmlReader reader = {Element, Name="serviceDebug"}) + 0x8a bytes
System.Configuration.dll!System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(System.Configuration.RuntimeConfigurationRecord configRecord = ConfigPath = "MACHINE/EXE", System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/behaviors", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/behaviors", object parentConfig = {System.ServiceModel.Configuration.BehaviorsSection}, System.Configuration.ConfigXmlReader reader = {Element, Name="serviceDebug"}) + 0xf6 bytes
System.Configuration.dll!System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(System.Configuration.RuntimeConfigurationRecord configRecord = ConfigPath = "MACHINE/EXE", System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/behaviors", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/behaviors", object parentConfig = {System.ServiceModel.Configuration.BehaviorsSection}, System.Configuration.ConfigXmlReader reader = {Element, Name="serviceDebug"}) + 0x98 bytes
System.Configuration.dll!System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSection(bool inputIsTrusted = false, System.Configuration.RuntimeConfigurationRecord configRecord = ConfigPath = "MACHINE/EXE", System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/behaviors", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/behaviors", object parentConfig = {System.ServiceModel.Configuration.BehaviorsSection}, System.Configuration.ConfigXmlReader reader = {Element, Name="serviceDebug"}) + 0x5e bytes
System.Configuration.dll!System.Configuration.RuntimeConfigurationRecord.CreateSection(bool inputIsTrusted = false, System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/behaviors", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/behaviors", object parentConfig = {System.ServiceModel.Configuration.BehaviorsSection}, System.Configuration.ConfigXmlReader reader = {Element, Name="serviceDebug"}) + 0x7a bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.CallCreateSection(bool inputIsTrusted = false, System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/behaviors", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/behaviors", object parentConfig = {System.ServiceModel.Configuration.BehaviorsSection}, System.Configuration.ConfigXmlReader reader = {Element, Name="serviceDebug"}, string filename = "C:\\Dev\\windows\\bin\\Debug\\Server.Host.exe.Config", int line = 89) + 0x74 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.EvaluateOne(string[] keys = {string[2]}, System.Configuration.SectionInput input = SectionInput "system.serviceModel/behaviors", bool isTrusted = false, System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/behaviors", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/behaviors", object parentResult = {System.ServiceModel.Configuration.BehaviorsSection}) + 0x115 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.Evaluate(System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/behaviors", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/behaviors", object parentResult = {System.ServiceModel.Configuration.BehaviorsSection}, bool getLkg = false, bool getRuntimeObject = true, out object result = null, out object resultRuntimeObject = null) + 0x626 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.GetSectionRecursive(string configKey = "system.serviceModel/behaviors", bool getLkg = false, bool checkPermission = true, bool getRuntimeObject = true, bool requestIsHere = true, out object result = null, out object resultRuntimeObject = null) + 0x670 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.GetSection(string configKey = "system.serviceModel/behaviors", bool getLkg = false, bool checkPermission = true) + 0x44 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.GetSection(string configKey = "system.serviceModel/behaviors") + 0x2a bytes
System.Configuration.dll!System.Configuration.ContextInformation.GetSection(string sectionName = "system.serviceModel/behaviors") + 0x2a bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ConfigurationHelpers.UnsafeGetSectionFromContext(System.Configuration.ContextInformation evalContext = {System.Configuration.ContextInformation}, string sectionPath = "system.serviceModel/behaviors") + 0x3a bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ConfigurationHelpers.UnsafeGetAssociatedSection(System.Configuration.ContextInformation evalContext = {System.Configuration.ContextInformation}, string sectionPath = "system.serviceModel/behaviors") + 0x3b bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.BehaviorsSection.ValidateServiceBehaviorReference(string behaviorConfiguration = "serviceBehavior", System.Configuration.ContextInformation evaluationContext = {System.Configuration.ContextInformation}, System.Configuration.ConfigurationElement configurationElement = {System.ServiceModel.Configuration.ServiceElement}) + 0x66 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServicesSection.ValidateSection() + 0xe7 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServicesSection.PostDeserialize() + 0x1e bytes
System.Configuration.dll!System.Configuration.ConfigurationElement.DeserializeElement(System.Xml.XmlReader reader = {EndElement, Name="services"}, bool serializeCollectionKey = false) + 0x1fef bytes
System.Configuration.dll!System.Configuration.ConfigurationSection.DeserializeSection(System.Xml.XmlReader reader = {EndElement, Name="services"}) + 0x8a bytes
System.Configuration.dll!System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(System.Configuration.RuntimeConfigurationRecord configRecord = ConfigPath = "MACHINE/EXE", System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/services", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/services", object parentConfig = {System.ServiceModel.Configuration.ServicesSection}, System.Configuration.ConfigXmlReader reader = {EndElement, Name="services"}) + 0xf6 bytes
System.Configuration.dll!System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(System.Configuration.RuntimeConfigurationRecord configRecord = ConfigPath = "MACHINE/EXE", System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/services", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/services", object parentConfig = {System.ServiceModel.Configuration.ServicesSection}, System.Configuration.ConfigXmlReader reader = {EndElement, Name="services"}) + 0x98 bytes
System.Configuration.dll!System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSection(bool inputIsTrusted = false, System.Configuration.RuntimeConfigurationRecord configRecord = ConfigPath = "MACHINE/EXE", System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/services", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/services", object parentConfig = {System.ServiceModel.Configuration.ServicesSection}, System.Configuration.ConfigXmlReader reader = {EndElement, Name="services"}) + 0x5e bytes
System.Configuration.dll!System.Configuration.RuntimeConfigurationRecord.CreateSection(bool inputIsTrusted = false, System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/services", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/services", object parentConfig = {System.ServiceModel.Configuration.ServicesSection}, System.Configuration.ConfigXmlReader reader = {EndElement, Name="services"}) + 0x7a bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.CallCreateSection(bool inputIsTrusted = false, System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/services", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/services", object parentConfig = {System.ServiceModel.Configuration.ServicesSection}, System.Configuration.ConfigXmlReader reader = {EndElement, Name="services"}, string filename = "C:\\Dev\\windows\\bin\\Debug\\Server.Host.exe.Config", int line = 78) + 0x74 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.EvaluateOne(string[] keys = {string[2]}, System.Configuration.SectionInput input = SectionInput "system.serviceModel/services", bool isTrusted = false, System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/services", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/services", object parentResult = {System.ServiceModel.Configuration.ServicesSection}) + 0x115 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.Evaluate(System.Configuration.FactoryRecord factoryRecord = FactoryRecord "system.serviceModel/services", System.Configuration.SectionRecord sectionRecord = SectionRecord "system.serviceModel/services", object parentResult = {System.ServiceModel.Configuration.ServicesSection}, bool getLkg = false, bool getRuntimeObject = true, out object result = null, out object resultRuntimeObject = null) + 0x626 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.GetSectionRecursive(string configKey = "system.serviceModel/services", bool getLkg = false, bool checkPermission = false, bool getRuntimeObject = true, bool requestIsHere = false, out object result = null, out object resultRuntimeObject = null) + 0x670 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.GetSectionRecursive(string configKey = "system.serviceModel/services", bool getLkg = false, bool checkPermission = false, bool getRuntimeObject = true, bool requestIsHere = false, out object result = null, out object resultRuntimeObject = null) + 0x63d bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.GetSectionRecursive(string configKey = "system.serviceModel/services", bool getLkg = false, bool checkPermission = true, bool getRuntimeObject = true, bool requestIsHere = true, out object result = null, out object resultRuntimeObject = null) + 0x63d bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.GetSection(string configKey = "system.serviceModel/services", bool getLkg = false, bool checkPermission = true) + 0x44 bytes
System.Configuration.dll!System.Configuration.BaseConfigurationRecord.GetSection(string configKey = "system.serviceModel/services") + 0x2a bytes
System.Configuration.dll!System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(string sectionName = "system.serviceModel/services") + 0x7e bytes
System.Configuration.dll!System.Configuration.ConfigurationManager.GetSection(string sectionName = "system.serviceModel/services") + 0x48 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ConfigurationHelpers.UnsafeGetSectionFromConfigurationManager(string sectionPath = "system.serviceModel/services") + 0x31 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ConfigurationHelpers.UnsafeGetAssociatedSection(System.Configuration.ContextInformation evalContext = null, string sectionPath = "system.serviceModel/services") + 0xac bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ConfigurationHelpers.UnsafeGetSection(string sectionPath = "system.serviceModel/services") + 0x22 bytes
System.ServiceModel.dll!System.ServiceModel.Configuration.ServicesSection.UnsafeGetSection() + 0x26 bytes
System.ServiceModel.dll!System.ServiceModel.Description.ConfigLoader.LookupService(string serviceConfigurationName = "Csla.Server.Hosts.WcfPortal") + 0x39 bytes
System.ServiceModel.dll!System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(System.ServiceModel.Description.ConfigLoader configLoader = {System.ServiceModel.Description.ConfigLoader}, System.ServiceModel.Description.ServiceDescription description = ServiceType={Csla.Server.Hosts.WcfPortal}, string configurationName = "Csla.Server.Hosts.WcfPortal") + 0x2d bytes
System.ServiceModel.dll!System.ServiceModel.ServiceHostBase.ApplyConfiguration() + 0xfa bytes
System.ServiceModel.dll!System.ServiceModel.ServiceHostBase.InitializeDescription(System.ServiceModel.UriSchemeKeyedCollection baseAddresses = {System.ServiceModel.UriSchemeKeyedCollection}) + 0xf8 bytes
System.ServiceModel.dll!System.ServiceModel.ServiceHost.InitializeDescription(System.Type serviceType = {Name = "WcfPortal" FullName = "Csla.Server.Hosts.WcfPortal"}, System.ServiceModel.UriSchemeKeyedCollection baseAddresses = {System.ServiceModel.UriSchemeKeyedCollection}) + 0x83 bytes
System.ServiceModel.dll!System.ServiceModel.ServiceHost.ServiceHost(System.Type serviceType = {Name = "WcfPortal" FullName = "Csla.Server.Hosts.WcfPortal"}, System.Uri[] baseAddresses = {System.Uri[0]}) + 0x16a bytes
Server.Host.exe!Server.Host.Program.Main(string[] args = {string[0]}) Line 37 + 0x38 bytes C#
</code></pre>
<p><strong>EDIT</strong></p>
<p>The issue does not produce itself after upgrading to .NET 4 and VS2010. I guess MS fixed it.</p>
| 0 | 4,529 |
Install tesseract/pytesser on Mac OS X
|
<p>I am trying to install this (and additionally pytesser) for osx 10.9 (with anaconda as default python). I have looked around online but I can't get any of the tutorials to work as they all seem to be extinct (homebrew doesn't have a formula for leptonica for instance). I have probably been struggling to install this for the best part of a week with absolutely no luck at all. </p>
<p>Has anyone managed to succeed recently-how did you do it?</p>
<p>Thanks</p>
<p>Edit: Strangely the brew for leptonica has spluttered into life. I have the fairly strange error below.</p>
<pre><code>brew install tesseract
==> Downloading https://bitbucket.org/3togo/python-tesseract/downloads/tesseract
Already downloaded: /Library/Caches/Homebrew/tesseract-3.03-rc1.tar.gz
==> ./configure --prefix=/usr/local/Cellar/tesseract/3.03-rc1
checking for leptonica... yes
checking for pixCreate in -llept... yes
checking leptonica version >= 1.70... configure: error: in `/private/tmp/tesseract- 19Ol/tesseract-3.03':
configure: error: leptonica 1.70 or higher is required
See `config.log' for more details
READ THIS: https://github.com/Homebrew/homebrew/wiki/troubleshooting
</code></pre>
<p>i.e it is registering the install but still not working. I will check out the config. file as instructed</p>
<p>Edit 2:</p>
<p>Upon trying to import the library in python I get this:</p>
<pre><code>import tesseract
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "//anaconda/lib/python2.7/site-packages/python-tesseract_0.8-3.0-py2.7_macosx-10.9- intel.egg/tesseract.py", line 28, in <module>
_tesseract = swig_import_helper()
File "//anaconda/lib/python2.7/site-packages/python-tesseract_0.8-3.0-py2.7_macosx-10.9-intel.egg/tesseract.py", line 24, in swig_import_helper
_mod = imp.load_module('_tesseract', fp, pathname, description)
ImportError: dlopen(//anaconda/lib/python2.7/site-packages/python-tesseract_0.8-3.0- py2.7_macosx-10.9-intel.egg/_tesseract.so, 2): Library not loaded: /usr/local/lib/libtesseract.3.dylib
</code></pre>
<p>Referenced from: //anaconda/lib/python2.7/site-packages/python-tesseract_0.8-3.0-py2.7_macosx-10.9-intel.egg/_tesseract.so</p>
<p>Reason: image not found</p>
<p>To be honest I am a complete amateur with respect to any of this behind the scenes installation and had to google extensively to even get this far. I would be really grateful if someone with a bit of knowledge could shed any light on the obvious things to try, as I feel as though I have exhausted the web looking for solutions and am getting close to considering this library unuseable and attempting to write my own ocr library-100% not a job I am looking forward to. Alternatively, if anyone knows any decent python ocr libraries with decent support/ install mainatenance I would love to know about them (From my google searching I suspect that tesseract is by far the best known, which is why it is so frustrating that the install is so tricky)</p>
<p>I will happily provide any any more info about my system etc to any warrior willing to have a crack at helping with this.</p>
<p>Thanks!</p>
| 0 | 1,065 |
Plot semi transparent contour plot over image file using matplotlib
|
<p>I'd like to plot a transparent contour plot over an image file in matplotlib/pyplot.</p>
<p>Here's what I got so far...</p>
<p>I have a 600x600 pixel square image file <code>test.png</code> that looks like so:</p>
<p><a href="https://i.stack.imgur.com/YTHQg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YTHQg.png" alt="enter image description here"></a></p>
<p>I would like to plot a contour plot over this image (having the image file be 'below' and a semi-transparent version of the contour plot overlaid) using matplotlib and pyplot. As a bonus, the image would be automatically scaled to fit within the current plotting boundaries. My example plotting script is as follows:</p>
<pre><code>from matplotlib import pyplot
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from pylab import *
import numpy as np
import random
# ----------------------------- #
dx, dy = 500.0, 500.0
y, x = np.mgrid[slice(-2500.0, 2500.0 + dy, dy),slice(-2500.0, 2500.0 + dx, dx)]
z = []
for i in x:
z.append([])
for j in y:
z[-1].append(random.uniform(80.0,100.0))
# ----------------------------- #
plot_aspect = 1.2
plot_height = 10.0
plot_width = int(plot_height*plot_aspect)
# ----------------------------- #
pyplot.figure(figsize=(plot_width, plot_height), dpi=100)
pyplot.subplots_adjust(left=0.10, right=1.00, top=0.90, bottom=0.06, hspace=0.30)
subplot1 = pyplot.subplot(111)
# ----------------------------- #
cbar_max = 100.0
cbar_min = 80.0
cbar_step = 1.0
cbar_num_colors = 200
cbar_num_format = "%d"
# ----------
levels = MaxNLocator(nbins=cbar_num_colors).tick_values(cbar_min, cbar_max)
cmap = pyplot.get_cmap('jet')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
pp = pyplot.contourf(x,y,z,levels=levels,cmap=cmap)
cbar = pyplot.colorbar(pp, orientation='vertical', ticks=np.arange(cbar_min, cbar_max+cbar_step, cbar_step), format=cbar_num_format)
cbar.ax.set_ylabel('Color Scale [unit]', fontsize = 16, weight="bold")
# ----------
CS = pyplot.contour(x,y,z, alpha=0.5)
# ----------
majorLocator1 = MultipleLocator(500)
majorFormatter1 = FormatStrFormatter('%d')
minorLocator1 = MultipleLocator(250)
subplot1.xaxis.set_major_locator(majorLocator1)
subplot1.xaxis.set_major_formatter(majorFormatter1)
subplot1.xaxis.set_minor_locator(minorLocator1)
pyplot.xticks(fontsize = 16)
pyplot.xlim(-2500.0,2500.0)
# ----------
majorLocator2 = MultipleLocator(500)
majorFormatter2 = FormatStrFormatter('%d')
minorLocator2 = MultipleLocator(250)
subplot1.yaxis.set_major_locator(majorLocator2)
subplot1.yaxis.set_major_formatter(majorFormatter2)
subplot1.yaxis.set_minor_locator(minorLocator2)
pyplot.yticks(fontsize = 16)
pyplot.ylim(-2500.0,2500.0)
# ----------
subplot1.xaxis.grid()
subplot1.yaxis.grid()
# ----------
subplot1.axes.set_aspect('equal')
# ----------
pyplot.suptitle('Main Title', fontsize = 24, weight="bold")
# ----------
pyplot.xlabel('X [m]', fontsize=16, weight="bold")
pyplot.ylabel('Y [m]', fontsize=16, weight="bold")
# ----------
implot = subplot1.imshow( pyplot.imread('test.png') , interpolation='nearest', alpha=0.5)
# ----------
pyplot.show()
#pyplot.savefig("tmp.png", dpi=100)
pyplot.close()
</code></pre>
<p>...but I'm not getting the result I want... instead I just see the contour plot part. Something like:</p>
<p><a href="https://i.stack.imgur.com/QXlPf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QXlPf.png" alt="enter image description here"></a></p>
<p>What should I do in my code to get what I want?</p>
| 0 | 1,399 |
Program type already present: com.google.android.gms.internal.zzfq
|
<p>I getting this error. Despite trying all thing I am unable to resolve it. Please help me. </p>
<p>Things that I tried are:</p>
<ol>
<li>Delete <code>.build</code>, <code>.idea</code> etc then rebuild</li>
<li>Clean and rebuild</li>
<li>Change version of compile library </li>
</ol>
<p>Thank you</p>
<p>plugins</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'
</code></pre>
<p>Android </p>
<pre><code>android {
dexOptions {
preDexLibraries = false
javaMaxHeapSize "2g"
}
compileSdkVersion 27
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "com.funzone.alarmnap"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
multiDexEnabled true
versionName "1.1"
vectorDrawables.useSupportLibrary = true
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
</code></pre>
<p>Greendao Plugin</p>
<pre><code> apply plugin: 'org.greenrobot.greendao'
greendao {
targetGenDir 'src/main/java'
schemaVersion 2
}
</code></pre>
<p>All libraries:</p>
<pre><code>dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.jjoe64:graphview:4.2.1'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.facebook.android:audience-network-sdk:4.+'
implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
implementation 'com.facebook.android:notifications:1.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:27.1.0'
implementation 'com.android.support:support-v4:27.1.0'
implementation 'com.android.support:support-v13:27.1.0'
implementation 'com.android.support:cardview-v7:27.1.0'
implementation 'com.google.firebase:firebase-messaging:12.0.1'
implementation 'com.google.firebase:firebase-core:12.0.1'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.1'
implementation 'com.android.support:multidex:1.0.3'
implementation 'org.greenrobot:greendao:3.2.2'
testImplementation 'junit:junit:4.12'
testImplementation "org.robolectric:shadows-multidex:3.0"
testImplementation 'org.robolectric:robolectric:3.4.2'
implementation 'com.android.support:preference-v7:27.1.0'
}
repositories {
mavenCentral()
google()
}
</code></pre>
<p>Google plugin</p>
<pre><code>apply plugin: 'com.google.gms.google-services'
</code></pre>
| 0 | 1,054 |
Reading Key value pairs of a JSON File
|
<p>My code is as follows: The JSON File is <a href="https://www.dropbox.com/s/uwqfqb27blxr1bj/citiesclimate_2014_03_27.json" rel="nofollow">https://www.dropbox.com/s/uwqfqb27blxr1bj/citiesclimate_2014_03_27.json</a></p>
<p>A small sample:</p>
<pre><code>[ { "_id" : { "$oid" : "5333d7e18828169279d9250d" },
"actions" : null,
"actions_nr" : 0,
"city" : "Adachi City",
"citylink" : "<a href=\"/data/report/commitments/?tx_datareport_pi1%5Buid%5D=198\" target=\"_blank\" >Adachi City</a>",
"commitments" : "338,339",
"commitments_nr" : 1,
"country" : "Japan",
"latitude" : "35.465",
"longitude" : "139.482",
"performance" : "355,356,1090,1091",
"performance_nr" : 4,
"uid" : "198"
},
{ "_id" : { "$oid" : "5333d7e18828169279d92511" },
"test" : [ { "actions" : null,
"actions_nr" : 0,
"city" : "Adachi City",
"citylink" : "<a href=\"/data/report/commitments/?tx_datareport_pi1%5Buid%5D=198\" target=\"_blank\" >Adachi City</a>",
"commitments" : "338,339",
"commitments_nr" : 1,
"country" : "Japan",
"latitude" : "35.465",
"longitude" : "139.482",
"performance" : "355,356,1090,1091",
"performance_nr" : 4,
"uid" : "198"
},
{ "actions" : "3025,3105,3106,3108,3109,3110,3111,3112,3113,3114,3115,3116,3164,3166,3167,3168,3170,3171,3172,3173,3174,3175,3176,3177,3180,3181,3182,3183,3184,3185,3187,3188,3189,3190,3191,3192,3193,3194,3196,3197,3410",
"actions_nr" : 41,
"city" : "Ahmadabad City",
"citylink" : "<a href=\"/data/report/commitments/?tx_datareport_pi1%5Buid%5D=549\" target=\"_blank\" >Ahmadabad City</a>",
"commitments" : "816",
"commitments_nr" : 1,
"country" : "India",
"latitude" : "23.0300",
"longitude" : "72.5800",
"performance" : "900,901",
"performance_nr" : 2,
"uid" : "549"
}
]
}
]
</code></pre>
<p>I keep getting string indices must be integers </p>
<pre><code>json_file = source_json
with open(json_file) as json_file:
json_data = json.load(json_file)
for e in json_data: # iterator over a dictionary
#print e
for key, value in e.iteritems():
if key != '_id':
print key, value
#city_climate_data['city'] = value['test.city']
#print city_climate_data['city']
</code></pre>
| 0 | 1,303 |
Tab icon not showing
|
<p>I'm trying to do a simple tab app in android with two tabs. My problem is that when I put this code, in the tab, only is shown the text, but no the icons.
If I put the text to "" the icon is shown. </p>
<p>Could someone help me? My android version is 4.0.3.</p>
<p>Thanks a lot. </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TabWidget android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/tabs" />
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/tabcontent" >
<LinearLayout android:id="@+id/tab1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:id="@+id/textView1"
android:text="Contenido Tab 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout android:id="@+id/tab2"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:id="@+id/textView2"
android:text="Contenido Tab 2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</code></pre>
<p>and the activity code is </p>
<pre><code>public class TabTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
TabHost tabs=(TabHost)findViewById(R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec=tabs.newTabSpec("mitab1");
spec.setContent(R.id.tab1);
spec.setIndicator("sss",
res.getDrawable(android.R.drawable.ic_btn_speak_now));
tabs.addTab(spec);
spec=tabs.newTabSpec("mitab2");
spec.setContent(R.id.tab2);
spec.setIndicator("TAB2",
res.getDrawable(android.R.drawable.ic_dialog_map));
tabs.addTab(spec);
tabs.setCurrentTab(0);
}
</code></pre>
<p>as you can see is very simple. But when I write <code>spec.setIndicator("",
res.getDrawable(android.R.drawable.ic_dialog_map));</code>
I can see the icon, bu when I write <code>spec.setIndicator("TAB2",
res.getDrawable(android.R.drawable.ic_dialog_map));</code>
I can only see TAB2, but no both of them.</p>
<p>It seems that there are no enougth space to show both. So I've tried to get increase the tab height with this </p>
<pre><code>tabs.getTabWidget().getChildAt(1).getLayoutParams().height = 150;
</code></pre>
<p>but not seems to work.</p>
| 0 | 1,413 |
How to resolve 'SMTP Error: Could not connect to SMTP host.' in phpmailer?
|
<p>I'm trying to send email using my gmail account but i am getting an error</p>
<blockquote>
<p>"SMTP Error: Could not connect to SMTP host".</p>
</blockquote>
<p>I have tried port 587,465 25 but still its not working.</p>
<pre><code><?php
if(isset($_POST['submit']))
{
$message=
'Full Name: '.$_POST['fullname'].'<br />
Subject: '.$_POST['subject'].'<br />
Phone: '.$_POST['phone'].'<br />
Email: '.$_POST['emailid'].'<br />
Comments: '.$_POST['comments'].'
';
require "phpmailer/class.phpmailer.php"; //include phpmailer class
// Instantiate Class
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host = "smtp.gmail.com"; //Gmail SMTP server address
$mail->Port = 465; //Gmail SMTP port
$mail->SMTPSecure = "tls";
$mail->Encoding = '7bit';
// Authentication
$mail->Username = "rhlsngh302@gmail.com"; // Your full Gmail address
$mail->Password = "*********"; // Your Gmail password
// Compose
$mail->SetFrom($_POST['emailid'], $_POST['fullname']);
$mail->AddReplyTo($_POST['emailid'], $_POST['fullname']);
$mail->Subject = "New Contact Form Enquiry"; // Subject (which isn't required)
$mail->MsgHTML($message);
// Send To
$mail->AddAddress("rhlsngh302@gmail.com", "RahulName"); // Where to send it - Recipient
$result = $mail->Send(); // Send!
$message = $result ? 'Successfully Sent!' : 'Sending Failed!';
unset($mail);
}
?>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<div style="margin: 100px auto 0;width: 300px;">
<h3>Contact Form</h3>
<form name="form1" id="form1" action="" method="post">
<fieldset>
<input type="text" name="fullname" placeholder="Full Name" />
<br />
<input type="text" name="subject" placeholder="Subject" />
<br />
<input type="text" name="phone" placeholder="Phone" />
<br />
<input type="text" name="emailid" placeholder="Email" />
<br />
<textarea rows="4" cols="20" name="comments" placeholder="Comments"></textarea>
<br />
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>
<p><?php if(!empty($message)) echo $message; ?></p>
</div>
</body>
</html>
</code></pre>
<p>How can I solve this problem?</p>
| 0 | 1,413 |
Illegal constructor with EcmaScript 6
|
<p>First of all I would like that say that I don't really know how I can explain what I did on order to get the error mentioned in the title (<code>uncaught TypeError: Illegal constructor</code>). I am using gulpfile in order to compile my Ecmascript 6 to plain Javascript. My gulpfile looks like this:</p>
<pre><code>var gulp = require('gulp');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
gulp.task('compile', function () {
return gulp.src(['resources/assets/js/*.js', 'resources/assets/js/components/*.js'])
.pipe(babel({
presets: ['es2015']
}).on('error', logError))
.pipe(concat('bundle.js'))
.pipe(gulp.dest('public/js'));
});
gulp.task('watch', function () {
gulp.watch('resources/assets/js/**/*', ['compile']);
})
gulp.task('default', ['watch']);
function logError(err) {
console.log(err);
}
</code></pre>
<p>I have a filesystem where all files are concatenated to one file (bundle.js), after being compiled with Babel. </p>
<p>In the browsers console (either Chrome or Firefox), the error appears and it is located in the next line:</p>
<pre><code>var _this = _possibleConstructorReturn(this, (Dropdown.__proto__ || Object.getPrototypeOf(Dropdown)).call(this, element));
</code></pre>
<p><a href="https://i.stack.imgur.com/CGXGK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CGXGK.png" alt="The error within the console"></a></p>
<p>This is the non-compiled code of this:</p>
<pre><code>class Dropdown extends Node {
constructor(element) {
super(element);
this.registerEvents(['click', 'change', 'blur']);
}
onClick() {
this.$element.addClass('clicked');
}
}
</code></pre>
<p>And this is the compiled code of the same class:</p>
<pre><code>var Dropdown = function (_Node) {
_inherits(Dropdown, _Node);
function Dropdown(element) {
_classCallCheck(this, Dropdown);
var _this = _possibleConstructorReturn(this, (Dropdown.__proto__ || Object.getPrototypeOf(Dropdown)).call(this, element));
_this.registerEvents(['click', 'change', 'blur']);
return _this;
}
_createClass(Dropdown, [{
key: 'onClick',
value: function onClick() {
this.$element.addClass('clicked');
}
}]);
return Dropdown;
}(Node);
</code></pre>
<p>I am not using <code>export default Dropdown</code> because I am not importing modules in other modules (this is not needed because every file is converted to one file, where everything is accessible). </p>
<p>I did some research and the only reason why peoeple got this error was because there was a capital letter where none was allowed. I didn't find anything else about the cause of this error. Does someone have an idea why I get this error? And does someone have a solution?</p>
| 0 | 1,030 |
Angular2 with RequireJS
|
<p>I am having issues getting Angular2 to load correctly when incorporating RequireJS into the application. </p>
<p>For simplicity wise I am using the very simple Hello World Javascript tutorial on the Angular2 located here : <a href="https://angular.io/docs/js/latest/quickstart.html" rel="noreferrer">https://angular.io/docs/js/latest/quickstart.html</a></p>
<p>I have this system working fine using Angular1 but I can't seem to replicate this success using Angular2.</p>
<p>Here is my index.html file:</p>
<pre><code><html>
<head>
<title>Angular 2 QuickStart JS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 1. Load RequireJS -->
<script type="text/javascript", src="bower_components/requirejs/require.js", data-main="/require.config.js"></script>
</head>
<!-- 3. Display the application -->
<body>
<ireland-product-app>Loading...</ireland-product-app>
</body>
</code></pre>
<p></p>
<p>My require.config.js file:</p>
<pre><code>require([
'assets/requiredPathsAndShim.js'
], function(requirePathsAndShim) {
require.config({
baseUrl: '/',
paths: requirePathsAndShim.paths,
shim: requirePathsAndShim.shim,
/// Kick start app...
deps: ['app/main']
});
</code></pre>
<p>});</p>
<p>I use the requiredPathsAndShim.js file to load all the dependencies I see that are required to start an Angular2 application. Here is the file:</p>
<pre><code>"use strict";
(function(define) {
define([], function() {
return {
waitSeconds : 10000,
paths: {
'shim' : 'node_modules/core-js/client/shim.min',
'zone' : 'node_modules/zone.js/dist/zone',
'Reflect' : 'node_modules/reflect-metadata/Reflect',
'Rx' : 'node_modules/rxjs/bundles/Rx.umd',
'core' : 'node_modules/@angular/core/core.umd',
'common' : 'node_modules/@angular/common/common.umd',
'compiler' : 'node_modules/@angular/compiler/compiler.umd',
'platform-browser' : 'node_modules/@angular/platform-browser/platform-browser.umd',
'platform-dynamic' : 'node_modules/@angular/platform-browser-dynamic/platform-browser-dynamic.umd'
},
shim : {
}
}
});
})(define);
</code></pre>
<p>I then load the 'app/main' file from my 'required.config' file which will load the bootstrap functionality of Angular2:</p>
<pre><code>"use strict";
(function() {
define([
'app/app.component'
], function(app) {
document.addEventListener('DOMContentLoaded', function() {
ng.platformBrowserDynamic.bootstrap(app.AppComponent);
});
});
})();
</code></pre>
<p>The app/app.component file is a file which simply returns my Angular2 component which is passed into the main.js bootstrap function to start the app. this is the file:</p>
<pre><code>"use strict";
(function() {
define([
], function() {
return {
AppComponent : ng.core.Component({
selector : 'ireland-product-app',
template : '<h1>Product App</h1>'
})
.Class({
constructor : function() {}
})
}
});
})();
</code></pre>
<p>I have been playing around with this for a few hours and can't seem to get this working. Can anyone point me in the right direction as to why this isn't working? I have a feeling some shims need to be added into the require.config but I have had no success setting script load dependencies as of yet. </p>
<p>Thanks</p>
| 0 | 1,646 |
How to tell if an X and Y coordinate are inside my button?
|
<p>I have managed, with great difficulty, to make a bitmap overlay the screen. I can also get touch input, however it gets touch input for EVERYWHERE on the screen.</p>
<p>I want to know how I would be able to check if the touch was on my bitmap, which is visible on the screen.</p>
<p>The service and view class is below. I have thought and thought, but I couldn't think of a way to do it :(</p>
<pre><code>package <package>;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
public class MyService extends Service {
ButtonView mView;
Bitmap bit;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
bit = BitmapFactory.decodeResource(getResources(), R.drawable.button);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
builder.setContentTitle("Ingress Tools Running");
builder.setContentText("Click to stop Ingress Tools");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(
this, StopActivity.class), 0));
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, builder.build());
mView = new ButtonView(this, bit);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.FILL_PARENT,
WindowManager.LayoutParams.FILL_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.RIGHT;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mView, params);
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(), "onDestroy", Toast.LENGTH_LONG).show();
if (mView != null) {
((WindowManager) getSystemService(WINDOW_SERVICE))
.removeView(mView);
mView = null;
}
}
}
class ButtonView extends ViewGroup {
private Paint mLoadPaint;
private Rect r;
private Bitmap bit;
public ButtonView(Context context, Bitmap bit) {
super(context);
Toast.makeText(context, "HUDView", Toast.LENGTH_LONG).show();
mLoadPaint = new Paint();
mLoadPaint.setAntiAlias(true);
mLoadPaint.setTextSize(10);
mLoadPaint.setARGB(255, 255, 0, 0);
r = new Rect();
r.set(380, 134, 468, 213);
this.bit = bit;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bit, 100, 100, null);
}
@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int area = bit.getWidth() * bit.getHeight();
//if (event.getY() <= maxY && event.getX() <= maxX) {
Toast.makeText(getContext(), "Open tools: ", Toast.LENGTH_LONG)
.show();
//}
return true;
}
}
</code></pre>
| 0 | 1,692 |
Hibernate's 'hbm2ddl.auto' property with value 'create' is not re-creating table
|
<p>I'm working on my <a href="http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch01.html#tutorial-firstapp" rel="nofollow">first simple Hibernate application</a>. The crux of the problem is, I had renamed a member of persistent class (with apt changes to all other parts) and re-run the application. As 'hbm2ddl.auto' property is assigned 'create' value in configuration xml, Hibernate is expected to create new table on every run but, it's not doing so. Following is detailed information:</p>
<p>CLASS: <br></p>
<pre><code> public class Event {
private Long id;
private String title;
private Date date;
public Event() {
// this form used by Hibernate
}
public Event(String title, Date date) {
// for application use, to create new events
this.title = title;
this.date = date;
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
</code></pre>
<p>Event.hbm.xml: <br></p>
<pre><code><hibernate-mapping package="org.hibernate.tutorial.hbm">
<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="increment"/>
</id>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title"/>
</class>
</code></pre>
<p></p>
<p>hibernate.cfg.xml, among others, has following entry: <br></p>
<pre><code><property name="hbm2ddl.auto">create</property>
</code></pre>
<p>MAIN CLASS: <br></p>
<pre><code>public class EventManager {
public static void main(String[] args) {
EventManager mgr = new EventManager();
List events = mgr.listEvents();
for (int i = 0; i < events.size(); i++) {
Event theEvent = (Event) events.get(i);
System.out.println( "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate() );
}
HibernateUtil.getSessionFactory().close();
}
private List listEvents() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List result = session.createQuery("from Event").list();
session.getTransaction().commit();
return result;
} }
</code></pre>
<p>The above code is working as expected. Just to test 'hbm2ddl.auto' property, I had changed 'title' member in Event class to 'title1'. And, updated setter and getter methods and all references (in mapping xml, Event and EventManager class). Complied with no errors. But, when I try to run the application, I see following exception:</p>
<blockquote>
<p>Exception in thread "main" org.hibernate.exception.SQLGrammarException: Unknown column 'event0_.title1' in 'field list'
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at $Proxy6.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
at org.hibernate.loader.Loader.doQuery(Loader.java:829)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
at org.hibernate.loader.Loader.doList(Loader.java:2438)
at org.hibernate.loader.Loader.doList(Loader.java:2424)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2254)
at org.hibernate.loader.Loader.list(Loader.java:2249)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1248)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.tutorial.hbm.EventManager.listEvents(EventManager.java:56)
at org.hibernate.tutorial.hbm.EventManager.main(EventManager.java:20)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'event0_.title1' in 'field list'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3562)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3494)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1960)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2114)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2696)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2105)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2264)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 16 more</p>
</blockquote>
<p>The error is pointing to EventManager class at following line:</p>
<pre><code>List result = session.createQuery("from Event").list();
</code></pre>
<p>As 'hbm2ddl.auto' property is assigned 'create' value in configuration xml, Hibernate is expected to create new table on every run but, it's not doing so. Please help resolve the problem.</p>
<p>Thanks in advance.</p>
| 0 | 2,581 |
xml schema nested element within an element with attributes
|
<p>I am making a school assignment
This is my XML </p>
<pre><code><lineup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ComplexTypeDemo.xsd">
<team teamName="Maple Leafs" city="Toronto">
<visitor/>
<player number="17">
<name>John Doe</name>
<position>Forward</position>
</player>
<!--Continue 20 Iterations-->
</team>
<team teamName="Rangers" city="New York">
<home/>
<player number="17">
<name>John Doe</name>
<position>Forward</position>
</player>
<!--Continue 20 Iterations-->
</team>
</lineup>
</code></pre>
<p>here is my schema document</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="lineup">
<xs:complexType>
<xs:sequence>
<xs:element name="team" minOccurs="2" maxOccurs="2">
<xs:complexType>
<xs:sequence>
<xs:choice>
<xs:element name="home"/>
<xs:element name="visitor"/>
</xs:choice>
<xs:element name="player" minOccurs="20" maxOccurs="20">
<xs:complexType>
<xs:all>
<xs:element name="name" />
<xs:element name="position"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</code></pre>
<p>i need to make a schema to validate this. but i can't figure out how to validate because it is nested but it has attributes. I can only seem to do one or the other, but not both....</p>
| 0 | 1,113 |
JSON schema: Why does "constant" not validate the same way as a single-valued "enum"?
|
<p>I have an object that provides a sort of audit log of versions of an asset. A couple of its properties (<code>versionSource.metadata</code> and <code>versionSource.files</code>) are objects that should validate against one of two schemas, depending on the value of one of their properties. I started off using a constant in my sub-schemas (inside the <code>oneOf</code>, but that was saying that all the the sub-schemas validated (thus breaking the <code>oneOf</code> since more than one validated. Changing it to a single-valued enum worked, though.</p>
<p>Why the difference in validation?</p>
<p>Here's the original schema:</p>
<pre><code>{
"$id": "https://example.com/schemas/asset-version.json",
"title": "Audit log of asset versions",
"$schema": "http://json-schema.org/draft-07/schema",
"type": "object",
"required": [
"assetID",
"version",
"versionSource"
],
"properties": {
"assetID": {
"type": "string"
},
"version": {
"type": "integer",
"minimum": 1
},
"versionSource": {
"type": "object",
"properties": {
"metadata": {
"type": "object",
"oneOf": [
{
"properties": {
"sourceType": { "constant": "client" }
}
},
{
"$ref": "#/definitions/version-source-previous-version"
}
]
},
"files": {
"type": "object",
"oneOf": [
{
"properties": {
"sourceType": { "constant": "upload" },
"sourceID": {
"type": "string"
}
}
},
{
"$ref": "#/definitions/version-source-previous-version"
}
]
}
}
}
},
"definitions": {
"version-source-previous-version": {
"properties": {
"sourceType": { "constant": "previous-version" },
"sourceID": {
"type": "integer",
"minimum": 1
}
}
}
}
}
</code></pre>
<p>Here's one example document:</p>
<pre><code>{
"assetID": "0150a186-068d-43e7-bb8b-0a389b572379",
"version": 1,
"versionSource": {
"metadata": {
"sourceType": "client"
},
"files": {
"sourceType": "upload",
"sourceID": "54ae67b0-3e42-464a-a93f-3143b0f078fc"
}
},
"created": "2018-09-01T00:00:00.00Z",
"lastModified": "2018-09-02T12:10:00.00Z",
"deleted": "2018-09-02T12:10:00.00Z"
}
</code></pre>
<p>And one more:</p>
<pre><code>{
"assetID": "0150a186-068d-43e7-bb8b-0a389b572379",
"version": 2,
"versionSource": {
"metadata": {
"sourceType": "previous-version",
"sourceID": 1
},
"files": {
"sourceType": "previous-version",
"sourceID": 1
}
},
"created": "2018-09-01T00:00:00.00Z",
"lastModified": "2018-09-02T12:10:00.00Z",
"deleted": "2018-09-02T12:10:00.00Z"
}
</code></pre>
<p>Here's the error I get:</p>
<p>Message: JSON is valid against more than one schema from 'oneOf'. Valid schema indexes: 0, 1.
Schema path:
<a href="https://example.com/schemas/asset-version.json#/properties/versionSource/properties/metadata/oneOf" rel="noreferrer">https://example.com/schemas/asset-version.json#/properties/versionSource/properties/metadata/oneOf</a></p>
<p>Since <code>sourceType</code> is a constant in both schemas inside the <code>oneOf</code>, I'm really not sure how my object could possibly be valid against both schemas.</p>
<p>Changing the schema to the following, though, worked:</p>
<pre><code>{
"$id": "https://example.com/schemas/asset-version.json",
"title": "Audit log of asset versions",
"$schema": "http://json-schema.org/draft-07/schema",
"type": "object",
"required": [
"assetID",
"version",
"versionSource"
],
"properties": {
"assetID": {
"type": "string"
},
"version": {
"type": "integer",
"minimum": 1
},
"versionSource": {
"type": "object",
"properties": {
"metadata": {
"type": "object",
"oneOf": [
{
"properties": {
"sourceType": { "enum": [ "client" ] }
}
},
{
"$ref": "#/definitions/version-source-previous-version"
}
]
},
"files": {
"type": "object",
"oneOf": [
{
"properties": {
"sourceType": { "enum": [ "upload" ] },
"sourceID": {
"type": "string"
}
}
},
{
"$ref": "#/definitions/version-source-previous-version"
}
]
}
}
}
},
"definitions": {
"version-source-previous-version": {
"properties": {
"sourceType": { "enum": [ "previous-version" ] },
"sourceID": {
"type": "integer",
"minimum": 1
}
}
}
}
}
</code></pre>
<p>What am I missing?</p>
| 0 | 3,079 |
How to get session array data CodeIgniter
|
<p>I'm not quite sure why the username didn't appear on view page if i change the session data into array (i'm new in CodeIgniter). I have <strong><code>auth</code> controller</strong> to make login process:</p>
<pre><code>function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('Login');
# code...
}
else {
$username = $this->input->post('username');
$password = $this->input->post('password');
$check = $this->M_login->check($username, $password);
// session data
if ($check->num_rows() == TRUE) {
foreach ($check->result() as $value) {
$sess_data['id'] = $value->id;
$sess_data['name'] = $value->name;
$sess_data['username'] = $value->username;
$sess_data['password'] = $value->password;
$sess_data['description'] = $value->description;
$this->session->set_userdata($sess_data);
}
redirect('Dashboard');
}
else {
$this->session->set_flashdata('result_login', '<br>Invalid username or password, try again.');
redirect('Login');
}
</code></pre>
<p>And here is my <strong>dashboard controller</strong>:</p>
<pre><code>public function __construct() {
parent::__construct();
if(!$this->session->userdata('id')){
redirect('login');
}
}
public function index() {
// Dashboard view
$username = $this->session->userdata('username');
$data['username']=$username;
$this->load->view('Dashboard', $data);
}
function logout() {
$this->session->sess_destroy('id');
redirect('login');
}
</code></pre>
<p>With above code, i can get the username on my dashboard view by <code>echo $username</code>. But when i change the session data like this:</p>
<pre><code>if ($check->num_rows() == TRUE) {
foreach ($check->result() as $value) {
// session data
$sess_data = array(
'id' => $value->id,
'username' => $value->username,
'password' => $value->password,
'name' => $value->name,
'description' => $value->description
);
$this->session->set_userdata('log',$sess_data);
}
}
</code></pre>
<p>And <strong>Dashboard controller</strong> changed like this:</p>
<pre><code>if(!$this->session->userdata('id')) {
$getdata= $this->session->userdata('log');
$data['username'] = $getdata['username'];
}
$this->load->view('Dashboard', $data);
</code></pre>
<p>Then the username disappeared from view page. How can i store username in session array and call it in view page. Please share your better suggestions or your experience guys.</p>
<p>Thanks.</p>
| 0 | 1,645 |
Merging Memory Streams to create a http PDF response in c#
|
<p>I am trying to merge 2 crystal reports into single pdf file and I'm using Itextsharp v5.1.1. But it says the document cannot be opened. It might be corrupted. There are no build errors. but the pdf is malformed and cant be opened. Here is the order I chose to accomplish this.</p>
<ol>
<li>Export the Crystal report to MemoryStream1 in pdf format</li>
<li>Export the second report into MemoryStream2.</li>
<li>Merge the Memory Streams</li>
<li>Send the Streams to Http Output Response as PDF.</li>
</ol>
<p>Here is the Code for each step in the order.</p>
<pre><code> /// Get the Dataset from Stored Procedure for the CSSource Report
dsCS = CSData.GetUSSourceXML(ds_input);
/// Create the Report of type CSsource
rptCS = ReportFactory.GetReport(typeof(CSsource));
rptCS .SetDataSource(dsCS);
/// Set the Parameters to the CS report
rptCS .ParameterFields["Parameterid"].CurrentValues.Clear();
rptCS .SetParameterValue("Parameterid", PID);
//// Serialize the Object as PDF
msCS=(MemoryStream)rptCS .ExportToStream(ExportFormatType.PortableDocFormat);
</code></pre>
<p>For Step 2</p>
<pre><code> /// Get the Dataset from Stored Procedure for the Aden Report
dsAd = CSData.GetAdden(ds_input);
/// Create the Report of type Aden
rptAd = ReportFactory.GetReport(typeof(Aden));
rptAd.SetDataSource(dsAd );
/// Set the Parameters to the Aden report
rptAd.ParameterFields["Parameterid"].CurrentValues.Clear();
rptAd.SetParameterValue("Parameterid", PID);
//// Serialize the Object as PDF
msAD = (MemoryStream)rptAd.ExportToStream(ExportFormatType.PortableDocFormat);
</code></pre>
<p>For Step 3 </p>
<pre><code> System.Collections.Generic.List<byte[]> sourceFiles = new List<byte[]>();
sourceFiles.Add(msCS.ToArray());
sourceFiles.Add(msAD.ToArray());
PdfMerger mpdfs = new PdfMerger();
/// ms is the Memory stream to which both the streams are added
ms=mpdfs.MergeFiles(sourceFiles);
</code></pre>
<p>MergeFiles method is as follows</p>
<pre><code> public MemoryStream MergeFiles(Generic.List<byte[]> sourceFiles)
{
Document document = new Document();
MemoryStream output = new MemoryStream();
try
{
// Initialize pdf writer
PdfWriter writer = PdfWriter.GetInstance(document, output);
//writer.PageEvent = new PdfPageEvents();
// Open document to write
document.Open();
PdfContentByte content = writer.DirectContent;
// Iterate through all pdf documents
for (int fileCounter = 0; fileCounter < sourceFiles.Count;
fileCounter++)
{
// Create pdf reader
PdfReader reader = new PdfReader(sourceFiles[fileCounter]);
int numberOfPages = reader.NumberOfPages;
// Iterate through all pages
for (int currentPageIndex = 1; currentPageIndex <=
numberOfPages; currentPageIndex++)
{
// Determine page size for the current page
document.SetPageSize(
reader.GetPageSizeWithRotation(currentPageIndex));
// Create page
document.NewPage();
PdfImportedPage importedPage =
writer.GetImportedPage(reader, currentPageIndex);
// Determine page orientation
int pageOrientation =
reader.GetPageRotation(currentPageIndex);
if ((pageOrientation == 90) || (pageOrientation == 270))
{
content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0,
reader.GetPageSizeWithRotation(currentPageIndex).Height);
}
else
{
content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
catch (Exception exception)
{
throw new Exception("There has an unexpected exception" +
" occured during the pdf merging process.", exception);
}
finally
{
// document.Close();
}
return output;
}
</code></pre>
<p>Step 4 to Serialize the Memory stream as PDF</p>
<pre><code> // ms is the memory stream which is to be converted to PDF
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.Charset = string.Empty;
Response.AddHeader("Content-Disposition",
"attachment; filename=" +
"Application of " + FullName.Trim() + ".pdf");
//Write the file directly to the HTTP content output stream.
Response.OutputStream.Write(ms.ToArray(), 0,
Convert.ToInt32(ms.Length));
Response.OutputStream.Flush();
Response.OutputStream.Close();
rptCS.Close();
rptCS.Dispose();
rptAd.Close();
rptAd.Dispose();
</code></pre>
<p>Thanks for all those Developers helping me with this.
This is Urgent because it has to go production in a day or 2.
Please respond.</p>
<p>Chandanan.</p>
| 0 | 2,312 |
Yii2 - Bad Request (#400) Unable to verify your data submission
|
<p>My yii2 application was working fine till yesterday however today on submiting form it is showing error. "Bad Request (#400) Unable to verify your data submission.".</p>
<p>I found many such questions on stackoverflow, where people are suggesting to disable csrf validation i tried disabling csrf validation also. i even updated my composer still it is not working.</p>
<p>please suggest any other possible solution.</p>
<p>This is my form code :-</p>
<pre><code><h2>Open an Account</h2>
<?php
$form = ActiveForm::begin([
'id' => 'live-account-form',
'enableClientValidation' => true,
'fieldConfig' => [
'template' => '{input}{error}',
'options' => [
'tag' => false,
]
],
'options' => [
'class' => 'form-horizontal'
]
]);
?>
<div class="form-group">
<label for="signupform-first_name" class="col-sm-3 control-label">First Name*</label>
<div class="col-sm-9 field-signupform-first_name">
<?= $form->field($model, 'first_name')->textInput(['placeholder' => "Enter First Name"]) ?>
</div>
</div>
<div class="form-group">
<label for="singupform-last_name" class="col-sm-3 control-label">Last Name*</label>
<div class="col-sm-9 field-signupform-last_name">
<?= $form->field($model, 'last_name')->textInput(['placeholder' => 'Enter Last Name']) ?>
</div>
</div>
<div class="form-group">
<label for="signupform-email" class="col-sm-3 control-label">Email*</label>
<div class="col-sm-9 field-signupform-email">
<?= $form->field($model, 'email')->textInput(['placeholder' => "Enter Email Address"]) ?>
</div>
</div>
<div class="form-group">
<label for="signupform-country" class="col-sm-3 control-label">Country*</label>
<div class="col-sm-9 field-signupform-country">
<?= $form->field($model, 'country')->dropDownList(
ArrayHelper::map(PhCountry::find()->all(), 'intid', 'country_name'),
[
'prompt' => 'Select Country',
'onchange' => '$( "select#signupform-country_code" ).html("showLoading");
$.get( "index.php/site/fetch-country-code?id='.'"+$(this).val(),
function(data) {
$( "#signupform-country_code" ).val(data);
});'
]
) ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Phone Number*</label>
<div class="col-sm-9 phone-number-div">
<div>
<?= $form->field($model, 'country_code')->textInput(['placeholder' => 'Code', 'class' => 'country-code form-control']) ?>
</div>
<div class="field-signupform-phone">
<?= $form->field($model, 'phone')->textInput(['placeholder' => 'Enter Phone Number', 'class' => 'enter-phone-number form-control']) ?>
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Create Account</button>
<?php
ActiveForm::end();
?>
</code></pre>
<p>and this is my action code inside controller:-</p>
<pre><code>public function actionIndex()
{
Yii::$app->controller->enableCsrfValidation = false;
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
//print_r($model);
if ($user = $model->signup()) {
if($model->sendRegistrationEmail($user)) {
Yii::$app->session->setFlash('emailSent', 'An email containing confirmation link is sent to your email Address.');
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
//exit;
}
return $this->render('index', [
'model' => $model,
]);
}
</code></pre>
| 0 | 3,127 |
Why is StringBuilder#append(int) faster in Java 7 than in Java 8?
|
<p>While investigating for a <a href="https://stackoverflow.com/q/23748186/507519">little debate</a> w.r.t. using <code>"" + n</code> and <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int%29" rel="nofollow noreferrer"><code>Integer.toString(int)</code></a> to convert an integer primitive to a string I wrote this <a href="http://openjdk.java.net/projects/code-tools/jmh/" rel="nofollow noreferrer">JMH</a> microbenchmark:</p>
<pre><code>@Fork(1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class IntStr {
protected int counter;
@GenerateMicroBenchmark
public String integerToString() {
return Integer.toString(this.counter++);
}
@GenerateMicroBenchmark
public String stringBuilder0() {
return new StringBuilder().append(this.counter++).toString();
}
@GenerateMicroBenchmark
public String stringBuilder1() {
return new StringBuilder().append("").append(this.counter++).toString();
}
@GenerateMicroBenchmark
public String stringBuilder2() {
return new StringBuilder().append("").append(Integer.toString(this.counter++)).toString();
}
@GenerateMicroBenchmark
public String stringFormat() {
return String.format("%d", this.counter++);
}
@Setup(Level.Iteration)
public void prepareIteration() {
this.counter = 0;
}
}
</code></pre>
<p>I ran it with the default JMH options with both Java VMs that exist on my Linux machine (up-to-date Mageia 4 64-bit, Intel i7-3770 CPU, 32GB RAM). The first JVM was the one supplied with Oracle JDK
8u5 64-bit:</p>
<pre><code>java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)
</code></pre>
<p>With this JVM I got pretty much what I expected:</p>
<pre><code>Benchmark Mode Samples Mean Mean error Units
b.IntStr.integerToString thrpt 20 32317.048 698.703 ops/ms
b.IntStr.stringBuilder0 thrpt 20 28129.499 421.520 ops/ms
b.IntStr.stringBuilder1 thrpt 20 28106.692 1117.958 ops/ms
b.IntStr.stringBuilder2 thrpt 20 20066.939 1052.937 ops/ms
b.IntStr.stringFormat thrpt 20 2346.452 37.422 ops/ms
</code></pre>
<p>I.e. using the <code>StringBuilder</code> class is slower due to the additional overhead of creating the <code>StringBuilder</code> object and appending an empty string. Using <code>String.format(String, ...)</code> is even slower, by an order of magnitude or so.</p>
<p>The distribution-provided compiler, on the other hand, is based on OpenJDK 1.7:</p>
<pre><code>java version "1.7.0_55"
OpenJDK Runtime Environment (mageia-2.4.7.1.mga4-x86_64 u55-b13)
OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)
</code></pre>
<p>The results here were <em>interesting</em>:</p>
<pre><code>Benchmark Mode Samples Mean Mean error Units
b.IntStr.integerToString thrpt 20 31249.306 881.125 ops/ms
b.IntStr.stringBuilder0 thrpt 20 39486.857 663.766 ops/ms
b.IntStr.stringBuilder1 thrpt 20 41072.058 484.353 ops/ms
b.IntStr.stringBuilder2 thrpt 20 20513.913 466.130 ops/ms
b.IntStr.stringFormat thrpt 20 2068.471 44.964 ops/ms
</code></pre>
<p>Why does <code>StringBuilder.append(int)</code> appear so much faster with this JVM? Looking at the <code>StringBuilder</code> class source code revealed nothing particularly interesting - the method in question is almost identical to <code>Integer#toString(int)</code>. Interestingly enough, appending the result of <code>Integer.toString(int)</code> (the <code>stringBuilder2</code> microbenchmark) does not appear to be faster.</p>
<p>Is this performance discrepancy an issue with the testing harness? Or does my OpenJDK JVM contain optimizations that would affect this particular code (anti)-pattern?</p>
<p><strong>EDIT:</strong></p>
<p>For a more straight-forward comparison, I installed Oracle JDK 1.7u55:</p>
<pre><code>java version "1.7.0_55"
Java(TM) SE Runtime Environment (build 1.7.0_55-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.55-b03, mixed mode)
</code></pre>
<p>The results are similar to those of OpenJDK:</p>
<pre><code>Benchmark Mode Samples Mean Mean error Units
b.IntStr.integerToString thrpt 20 32502.493 501.928 ops/ms
b.IntStr.stringBuilder0 thrpt 20 39592.174 428.967 ops/ms
b.IntStr.stringBuilder1 thrpt 20 40978.633 544.236 ops/ms
</code></pre>
<p>It seems that this is a more general Java 7 vs Java 8 issue. Perhaps Java 7 had more aggressive string optimizations?</p>
<p><strong>EDIT 2</strong>:</p>
<p>For completeness, here are the string-related VM options for both of these JVMs:</p>
<p>For Oracle JDK 8u5:</p>
<pre><code>$ /usr/java/default/bin/java -XX:+PrintFlagsFinal 2>/dev/null | grep String
bool OptimizeStringConcat = true {C2 product}
intx PerfMaxStringConstLength = 1024 {product}
bool PrintStringTableStatistics = false {product}
uintx StringTableSize = 60013 {product}
</code></pre>
<p>For OpenJDK 1.7:</p>
<pre><code>$ java -XX:+PrintFlagsFinal 2>/dev/null | grep String
bool OptimizeStringConcat = true {C2 product}
intx PerfMaxStringConstLength = 1024 {product}
bool PrintStringTableStatistics = false {product}
uintx StringTableSize = 60013 {product}
bool UseStringCache = false {product}
</code></pre>
<p>The <code>UseStringCache</code> option was removed in Java 8 with no replacement, so I doubt that makes any difference. The rest of the options appear to have the same settings.</p>
<p><strong>EDIT 3:</strong></p>
<p>A side-by-side comparison of the source code of the <code>AbstractStringBuilder</code>, <code>StringBuilder</code> and <code>Integer</code> classes from the <code>src.zip</code> file of reveals nothing noteworty. Apart from a whole lot of cosmetic and documentation changes, <code>Integer</code> now has some support for unsigned integers and <code>StringBuilder</code> has been slightly refactored to share more code with <code>StringBuffer</code>. None of these changes seem to affect the code paths used by <code>StringBuilder#append(int)</code>, although I may have missed something.</p>
<p>A comparison of the assembly code generated for <code>IntStr#integerToString()</code> and <code>IntStr#stringBuilder0()</code> is far more interesting. The basic layout of the code generated for <code>IntStr#integerToString()</code> was similar for both JVMs, although Oracle JDK 8u5 seemed to be more aggressive w.r.t. inlining some calls within the <code>Integer#toString(int)</code> code. There was a clear correspondence with the Java source code, even for someone with minimal assembly experience.</p>
<p>The assembly code for <code>IntStr#stringBuilder0()</code>, however, was radically different. The code generated by Oracle JDK 8u5 was once again directly related to the Java source code - I could easily recognise the same layout. On the contrary, the code generated by OpenJDK 7 was almost unrecognisable to the untrained eye (like mine). The <code>new StringBuilder()</code> call was seemingly removed, as was the creation of the array in the <code>StringBuilder</code> constructor. Additionaly, the disassembler plugin was not able to provide as many references to the source code as it did in JDK 8.</p>
<p>I assume that this is either the result of a much more aggressive optimization pass in OpenJDK 7, or more probably the result of inserting hand-written low-level code for certain <code>StringBuilder</code> operations. I am unsure why this optimization does not happen in my JVM 8 implementation or why the same optimizations were not implemented for <code>Integer#toString(int)</code> in JVM 7. I guess someone familiar with the related parts of the JRE source code would have to answer these questions...</p>
| 0 | 3,187 |
Link to specific tab Bootstrap
|
<p>I'm developing a site with Django Framework and I'm trying to create a way for when a user access a link like <a href="http://www.example.com/site/#users_rating">http://www.example.com/site/#users_rating</a> it opens a specific tab in the page.</p>
<p>I tried the following code that I found on the Internet (I'm new in JavaScript/JQuery), it isn't working:</p>
<pre><code><script type="text/javascript">
$(function() {
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ;
}
// Change hash for page-reload
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
window.location.hash = e.target.hash;
});
});
</script>
</code></pre>
<p>My template uses BootStrap 3, here is the HTML code (with some Django tags):</p>
<pre><code><div class="col-md-12" style="margin: 0 auto;">
<section class="panel">
<header class="panel-heading tab-bg-dark-navy-blue">
<ul class="nav nav-tabs nav-justified ">
<li class="active">
<a data-toggle="tab" href="#overview">
{% trans "Overview" %}
</a>
</li>
<li class="">
<a data-toggle="tab" href="#timeline">
{% trans "Timeline" %}
</a>
</li>
<li class="">
<a data-toggle="tab" href="#users_rating">
{% trans "Users Ratings" %} ({{ ptc.userrating.count }})
</a>
</li>
<li class="">
<a data-toggle="tab" href="#rating">
{% trans "Our Rating" %}
</a>
</li>
</ul>
</header>
<div class="panel-body">
<div class="tab-content tasi-tab">
<!-- Overview Tab-Pane -->
<div id="overview" class="tab-pane active">
{% include 'overview.html' %}
</div>
<!-- Timeline Tab-Pane -->
<div id="timeline" class="tab-pane">
{% include 'timeline.html' %}
</div>
<!-- User Rating Tab-Pane -->
<div id="users_rating" class="tab-pane">
{% include 'users_rating.html' %}
</div>
<!-- Our Rating Tab-Pane -->
<div id="rating" class="tab-pane">
{% include 'rating.html' %}
</div>
</div>
</div>
</section>
</div>
</code></pre>
<p>How can I open an specific tab according to an URL in my site?</p>
| 0 | 1,896 |
No view found for id ... for fragment PlaceholderFragment
|
<p>I have a simple app (based on <a href="http://developer.android.com/training/basics/firstapp/starting-activity.html" rel="nofollow">the Android First App sample</a>); the only thing it does is show one EditText and a button. The button creates another activity, and show the EditText message ... simple! ... But when running on the emulator, the app closes when I click on the button and i get this error:</p>
<blockquote>
<p>"No view found for id 0x7f05003c (com.example.testapp:id/container) for fragment PlaceholderFragment{4173ead8 #0 id=0x7f05003c}"</p>
</blockquote>
<p><strong>MainActivity.java</strong></p>
<pre><code>public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.testapp.MESSAGE";
public void SendMessage (View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edt_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
</code></pre>
<p><strong>activity_layout.xml</strong></p>
<pre><code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.testapp.MainActivity"
tools:ignore="MergeRootFrame" />
</code></pre>
<p><strong>fragment_main.xml</strong></p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText
android:id="@+id/edt_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/Message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/textButtom"
android:onClick="SendMessage" />
</LinearLayout>
</code></pre>
<p><strong>DisplayMessageActivity.java</strong></p>
<pre><code>public class DisplayMessageActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize (40);
textView.setText (message);
setContentView (textView);
}
@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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
</code></pre>
<p><strong>activity_display_message.xml</strong></p>
<pre><code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.testapp.DisplayMessageActivity"
tools:ignore="MergeRootFrame" />
</code></pre>
<p><strong>fragment_display_message.xml</strong></p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
</code></pre>
<p><strong>AndroidManifest.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.testapp.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.testapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.testapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.testapp.MainActivity" />
</activity>
</application>
</manifest>
</code></pre>
<p><strong>LogCat</strong></p>
<pre><code>> 03-22 11:02:42.755: E/AndroidRuntime(1722):FATAL EXCEPTION: main 03-22
> 11:02:42.755: E/AndroidRuntime(1722):java.lang.RuntimeException:
> Unable to start activity ComponentInfo{com.example.testapp/
> com.example.testapp.DisplayMessageActivity}:java.lang.IllegalArgumentException:
> No view found for id 0x7f05003c (com.example.testapp:id/container) for
> fragment PlaceholderFragment{417356c8 #0 id=0x7f05003c} 03-22
> 11:02:42.755: E/AndroidRuntime(1722):at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.app.ActivityThread.access$600(ActivityThread.java:141) 03-22
> 11:02:42.755: E/AndroidRuntime(1722):at
> android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.os.Handler.dispatchMessage(Handler.java:99) 03-22
> 11:02:42.755: E/AndroidRuntime(1722):at
> android.os.Looper.loop(Looper.java:137) 03-22 11:02:42.755:
> E/AndroidRuntime(1722):at
> android.app.ActivityThread.main(ActivityThread.java:5103) 03-22
> 11:02:42.755: E/AndroidRuntime(1722):at
> java.lang.reflect.Method.invokeNative(Native Method) 03-22
> 11:02:42.755: E/AndroidRuntime(1722):at
> java.lang.reflect.Method.invoke(Method.java:525) 03-22 11:02:42.755:
> E/AndroidRuntime(1722):at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-22
> 11:02:42.755: E/AndroidRuntime(1722):at
> dalvik.system.NativeStart.main(Native Method) 03-22 11:02:42.755:
> E/AndroidRuntime(1722):Caused by: java.lang.IllegalArgumentException:
> No view found for id 0x7f05003c (com.example.testapp:id/container) for
> fragment PlaceholderFragment{417356c8 #0 id=0x7f05003c} 03-22
> 11:02:42.755: E/AndroidRuntime(1722):at
> android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):at
> android.app.Activity.performStart(Activity.java:5143) 03-22
> 11:02:42.755: E/AndroidRuntime(1722):at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
> 03-22 11:02:42.755: E/AndroidRuntime(1722):... 11 more 03-22
> 11:02:42.965: D/dalvikvm(1722): GC_FOR_ALLOC freed 206K, 9% free
> 2808K/3076K, paused 54ms, total 92ms 03-22 11:02:44.764:
> I/Process(1722): Sending signal. PID: 1722 SIG: 9
</code></pre>
| 0 | 3,978 |
Setting Global Variables in VBA
|
<p>I'm currently making an "OS" in PowerPoint and I need to know how to set global variables for the settings.</p>
<p>I made a module called "Settings" containing:</p>
<pre><code>Public Sub Settings()
Option Explicit
Public UserName, UserIcon, Background, BrowserHomePage As String
Public SetupComplete As Boolean
SetupComplete = False
UserName = "Administrator"
UserIcon = Nothing
Background = Nothing
BrowserHomePage = Nothing
'Set the variables
UserName.Text = UserName
End Sub
</code></pre>
<p>Now on the "log in" screen, I have a text box named "UserName". I then made a button just to test out the variables. The button does this:</p>
<pre><code>Private Sub CommandButton1_Click()
UserName.Value = UserName
End Sub
</code></pre>
<p>The text box has no value when I click the button. I'm super new at VBA, and would like to know how to do this. Also, if anyone knows how to automatically execute codes when starting the PowerPoint, that would be fantastic.</p>
<p>EDIT: I'm trying to make a module containing only the settings. Can someone point out how to change the values from slides? Like if I click a button in slide 1, I want it to change the "UserName" value in module "Settings" to whatever I want.</p>
<p><strong>Solution</strong>: Okay, I found the one solution. I have to write the settings to a text file and retrieve it for reading.</p>
<p>My settings module:</p>
<pre><code>Public UserName As String, Password As String, UserIcon As String, DesktopBackground As String, LogInBackground As String, BrowserHomePage As String
Public InitialSetupCompleted As Boolean
Public Sub ReadSettings()
'Delcaring variables
TempDir = Environ("Temp")
SettingsFileName = "\OpenOSSettings.txt"
SettingsFile = TempDir & SettingsFileName
ReadFile = FreeFile()
'Read all settings from file
Open SettingsFile For Input As #ReadFile
Do While Not EOF(ReadFile)
Line Input #ReadFile, Read
If Read Like "UserName = *" Then
UserName = Replace(Read, "UserName = ", "")
End If
If Read Like "Password = *" Then
Password = Replace(Read, "Password = ", "")
End If
If Read Like "UserIcon = *" Then
UserIcon = Replace(Read, "UserIcon = ", "")
End If
If Read Like "DesktopBackground = *" Then
DesktopBackground = Replace(Read, "DesktopBackground = ", "")
End If
If Read Like "LogInBackground = *" Then
LogInBackground = Replace(Read, "LogInBackground = ", "")
End If
If Read Like "BrowserHomePage = *" Then
BrowserHomePage = Replace(Read, "BrowserHomePage = ", "")
End If
If Read Like "InitialSetupCompleted = *" Then
InitialSetupCompleted = Replace(Read, "InitialSetupCompleted = ", "")
End If
Loop
Close #ReadFile
'Applying settings to all elements
Slide5.UserName.Caption = UserName
End Sub
Public Sub SaveSettings()
'Declaring variables
TempDir = Environ("Temp")
SettingsFileName = "\OpenOSSettings.txt"
SettingsFile = TempDir & SettingsFileName
WriteFile = FreeFile()
'Write all settings to file
Open SettingsFile For Output As #WriteFile
Print #WriteFile, "UserName = " & UserName
Print #WriteFile, "Password = " & Password
Print #WriteFile, "UserIcon = " & UserIcon
Print #WriteFile, "DesktopBackground = " & DesktopBackground
Print #WriteFile, "LogInBackground = " & LogInBackground
Print #WriteFile, "BrowserHomePage = " & BrowserHomePage
Print #WriteFile, "InitialSetupCompleted = " & InitialSetupCompleted
Close #WriteFile
End Sub
</code></pre>
<p>Now to save the settings, I just use a textbox and a button.
Saving the value of TextBox1 to UserName in the file:</p>
<pre><code>Private Sub CommandButton1_Click()
UserName = TextBox1.Value
Settings.SaveSettings
End Sub
</code></pre>
<p>Reading the value of UserName and put it into TextBox1:</p>
<pre><code>Private Sub CommandButton2_Click()
Settings.ReadSettings
TextBox2.Value = UserName
End Sub
</code></pre>
<p>Very long code, but it works well. Thanks everyone!</p>
| 0 | 1,276 |
Running Jupyter Notebook from cmd raises ModuleNotFoundError: No module named pysqlite2
|
<p><strong>The problem:</strong></p>
<p>After reinstalling <a href="https://www.anaconda.com/download/#windows" rel="noreferrer">Anaconda</a> I can no longer navigate to a folder using the command window where I've got some <code>.pynb</code> files, type <code>jupyter notebook</code> and get things up and running. I'm getting these errors:</p>
<blockquote>
<p>C:\scripts\notebooks>jupyter notebook Traceback (most recent call
last): File
"C:\Users\MYUSERID\AppData\Local\Continuum\anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py",
line 10, in
import sqlite3 File "C:\Users\MYUSERID\AppData\Local\Continuum\anaconda3\lib\sqlite3__init__.py",
line 23, in
from sqlite3.dbapi2 import * File "C:\Users\MYUSERID\AppData\Local\Continuum\anaconda3\lib\sqlite3\dbapi2.py",
line 27, in
from _sqlite3 import * ImportError: DLL load failed: Procedyre not found</p>
<p>During handling of the above exception, another exception occurred:</p>
<p>Traceback (most recent call last): File
"C:\Users\MYUSERID\AppData\Local\Continuum\anaconda3\Scripts\jupyter-notebook-script.py",
line 6, in
from notebook.notebookapp import main File "C:\Users\MYUSERID\AppData\Local\Continuum\anaconda3\lib\site-packages\notebook\notebookapp.py",
line 86, in
from .services.sessions.sessionmanager import SessionManager File
"C:\Users\MYUSERID\AppData\Local\Continuum\anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py",
line 13, in
from pysqlite2 import dbapi2 as sqlite3 ModuleNotFoundError: No module named 'pysqlite2'</p>
</blockquote>
<hr>
<p><strong>What I've tried:</strong></p>
<hr>
<p>I've checked the fresh Anaconda folders, and everything seems to be where it should wrt <code>sqlite</code>, <code>sqlite3</code> and <code>pysqlite2</code>.</p>
<p>Since last time I downloaded Anaconda, it seems they've changed the default install folders, so I was sure everything would be OK after editing my user and system environment variables according to the post <a href="https://stackoverflow.com/questions/47318033/jupyter-notebook-will-not-open-from-command-prompt">Jupyter notebook will not open from command prompt</a> just in case checking the <code>Add to Path</code> option upon reinstalling Anaconda was not enough. But I'm still getting the same error messages.</p>
<p>When I launch Jupyter from the Anaconda Navigator, everything runs fine. </p>
<p>A similar question has been asked, but not answered, for Ubuntu here: <a href="https://stackoverflow.com/questions/47771364/2x-modulenotfounderror-jupyter-notebook">2x ModuleNotFoundError Jupyter notebook</a></p>
<hr>
<p><strong>Edit:</strong></p>
<hr>
<p>When I use and Anaconda Prompt, jupyter also starts running just fine when entering <code>jupyter notebook</code>. So why bother with the command window? The anaconda prompt command does not open ipynb files automatically in the deafault web browser. My earlier setup with the windows command window (and a batch file) did that and I think it was very useful.</p>
<hr>
<p><strong>System details:</strong></p>
<pre><code>Windows 7, 64 bit
Anaconda 2018.12
Jupyter Notebook 5.7.4
Python 3.7.1
IPython 7.2.0
</code></pre>
| 0 | 1,124 |
Put javascript on page from code behind
|
<p>I have some other javascript functions that are being set on the onfocus and onblur events of the textbox that I am using. In these functions it calls a generic javascript function that is not related to any controls. I want to know how to just simply spit this function out to the html of the page from the code behind. Something like this...</p>
<pre><code>Page.ClientScript.RegisterStartupScript(this.GetType(), "?????", getCounter);
</code></pre>
<p>EDIT: Here is what I mean</p>
<pre><code>public class MVADTextBox : TextBox
{
protected override void OnLoad(EventArgs e)
{
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetCounter(input)", getCounter);
var onBlur = "<script language=\"javascript\"> function PopulateField(input) {if (input.value == \"\") {input.value = input.defaultValue; input.className = 'sampleText'; } } </script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnBlur", onBlur);
}
}
</code></pre>
<p>The on blur method is getting sent to the page.</p>
| 0 | 1,404 |
Getting total values of a certain column from GridView
|
<p>Him</p>
<p>I am using a ASP.NET/VB.NET with SQL-Server-2012.</p>
<p>I have a a GridView column with 3 fields and 1 template field as shown below:</p>
<pre><code><asp:GridView ID="grdItems" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource3" Font-Names="Tahoma" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="item_name" HeaderText="Item" SortExpression="item_name" />
<asp:BoundField DataField="item_cost" HeaderText="Cost (inc. VAT)" SortExpression="item_cost" />
<asp:BoundField DataField="item_quantity" HeaderText="Quantity" SortExpression="item_quantity" />
<asp:TemplateField HeaderText="Sub-Total (inc. VAT)">
<ItemTemplate>
<asp:Label ID="TextBox3" runat="server" Text='<%# Convert.ToInt32(Eval("item_quantity")) * Convert.ToDouble(Eval("item_cost"))%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:Label ID="lblTotalPrice" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" VerticalAlign="Middle" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</code></pre>
<p>Code behind:</p>
<pre><code>Imports System.Data.SqlClient
Imports System.Data
Partial Class ProjectReport
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim ProjectID = Session("project_id")
Session("ProjectID") = ProjectID
End Sub
Protected Sub grdItems_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Dim totalPrice As Decimal = 0
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblPrice As Label = DirectCast(e.Row.FindControl("lblTotalPrice"), Label)
Dim price As Decimal = [Decimal].Parse(lblPrice.Text)
totalPrice += price
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lblTotalPrice As Label = DirectCast(e.Row.FindControl("lblTotalPrice"), Label)
lblTotalPrice.Text = totalPrice.ToString()
End If
End Sub
End Class
</code></pre>
<p><strong>DataBound()</strong></p>
<pre><code> Private Sub BindData()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim query As New SqlCommand("SELECT Items.item_name, Items.item_cost, project_items.item_quantity FROM Items INNER JOIN project_items ON items.item_id = project_items.item_id WHERE project_items.project_id = @parameter", conn)
query.Parameters.AddWithValue("@UserID", Session("ProjectID"))
Dim da As New SqlDataAdapter(query, conn)
da.SelectCommand = query
Dim table As New DataTable()
da.Fill(table)
grdItems.DataSource = table
grdItems.DataBind()
End Sub
</code></pre>
<p>The last column (the template field) multiplies the quantity field with the cost field.</p>
<p>How do I calculate all the values (by adding) in the template field?</p>
| 0 | 1,691 |
Javascript IE innerHTML of <select>
|
<p>I'm trying to change the innerHTML of a element based on the value of the previous element.</p>
<p>I have the javascript correctly grabbing the current value and everything works correctly in Firefox, Safari, Chrome and Opera. IE is a pain.</p>
<p>sample code:</p>
<pre><code><form action="soap.php" method="post">
<select name="circuitproduct" id="circuitproduct" onchange="bandwidthfunction();">
<option>Dedicated Voice</option>
<option>Frame Relay</option>
<option>ATM</option>
<option>Dedicated Internet</option>
<option>IP Solutions Private Port</option>
<option>IP Solutions Enhanced Port</option>
<option>Private Line – Domestic</option>
<option>Int’l Private Line</option>
<option>Qwest Metro Private Line (QMPL)</option>
<option>Qwest Metro Ethernet Private Line (QMEPL)</option>
</select><br />
<select name="term" id="term">
<option value="1-Year">1-Year</option>
<option value="2-Year">2-Year</option>
<option value="3-Year">3-Year</option>
</select>
<select id="bandwidth">
</select>
<select id="sublooptype">
</select>
</form>
</code></pre>
<p>sample javascript:</p>
<pre><code>function bandwidthfunction() {
var product = document.getElementById('circuitproduct').value;
if (product == 'Dedicated Voice') {
document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
document.getElementById('sublooptype').innerHTML = ('<option value="Special Access">Special Access</option><option>CO MtPt - Special Access</option><option>CPA Special Access</option>');
}
else if (product == 'Frame Relay') {
document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
document.getElementById('sublooptype').innerHTML = ('<option value="Special Access">Special Access</option><option>CO MtPt - Special Access</option><option>CPA Special Access</option>');
}
</code></pre>
| 0 | 1,128 |
Multiple selection in WPF MVVM ListBox
|
<p>I have a ListBox containing filenames. Now I need to get array of selected items from this ListBox. I found a few answers here, but none of them worked for me. I'am using Caliburn Micro framework.</p>
<p>Here is my View:</p>
<pre><code><Window x:Class="ProgramsAndUpdatesDesktop.Views.DeleteHistoryView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ProgramsAndUpdatesDesktop.Views"
mc:Ignorable="d"
ResizeMode="CanResizeWithGrip"
MaxWidth="300"
MinWidth="300"
MinHeight="500"
Title="DeleteHistoryView" Height="500" Width="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<StackPanel Grid.Column="0" Grid.Row="0">
<ListBox x:Name="DeleteHistoryListBox" SelectedItem="{Binding Path=DeleteHistorySelectedItem}"
ItemsSource="{Binding DeleteHistoryListBox, NotifyOnSourceUpdated=True}"
SelectionMode="Multiple">
</ListBox>
</StackPanel>
<StackPanel Grid.Column="0" Grid.Row="1">
<Button x:Name="DeleteHistoryButtonAction">Delete</Button>
</StackPanel>
</Grid>
</code></pre>
<p></p>
<p>And here is my ViewModel:</p>
<pre><code>class DeleteHistoryViewModel : Screen
{
string historyFolderPath = Environment.ExpandEnvironmentVariables(ConfigurationManager.AppSettings["HistoryFolderPath"]);
private ObservableCollection<string> deleteHistoryListBox = new ObservableCollection<string>();
public ObservableCollection<string> DeleteHistoryListBox
{
get { return deleteHistoryListBox; }
set { deleteHistoryListBox = value; NotifyOfPropertyChange(() => DeleteHistoryListBox); }
}
private List<string> deleteHistorySelectedItem = new List<string>();
public List<string> DeleteHistorySelectedItem
{
get { return deleteHistorySelectedItem; }
set { deleteHistorySelectedItem = value; }
}
public DeleteHistoryViewModel()
{
base.DisplayName = "Delete History";
}
protected override void OnInitialize()
{
FillListBox();
}
private void FillListBox()
{
string[] directory = Directory.GetFiles($"{historyFolderPath}\\", "*.json");
foreach (var item in directory)
{
string fileName = System.IO.Path.GetFileName(item).ToString();
if (!DeleteHistoryListBox.Contains(fileName))
{
DeleteHistoryListBox.Add(fileName);
}
}
}
#region ACTIONS REGION
// DELETE HISTORY ACTION
public void DeleteHistoryButtonAction()
{
foreach (var item in DeleteHistorySelectedItem)
{
MessageBox.Show(item);
}
}
#endregion
}
</code></pre>
| 0 | 1,329 |
Cannot create JDBC driver of class '' for connect URL 'null' : Tomcat & SQL Server JDBC driver
|
<p>I've tried just about everything I can find out there, if someone is able to help me out, I will be eternally grateful (and a lot more free in my time).</p>
<p>Basically, I have an error in Tomcat 7.0 (both when running within Eclipse and via startup.bat) that says this once data begins to be accessed by my dynamic web application:</p>
<pre><code>Cannot create JDBC driver of class '' for connect URL 'null'
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:507)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:476)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307)
</code></pre>
<p>I have the sqljdbc4.jar file in my tomcat\lib directory. I have also tried putting this in my WEB-INF/lib, and even my JDK lib directories. I don't think sqljdbc.jar will work, as it is intended for older JDK/JRE installs than mine.</p>
<p>I've heard the context.xml and web.xml files are crucial in getting this to work.</p>
<p>web.xml snippet:</p>
<pre><code><resource-ref>
<description>LBI DB Connection</description>
<res-ref-name>jdbc/LBIDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<resource-ref>
<description>OR DB Connection</description>
<res-ref-name>jdbc/ORDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</code></pre>
<p>context.xml</p>
<pre><code><Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/LBIDB" auth="Container"
type="javax.sql.DataSource" username="***" password="***" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver:localhost;DatabaseName=YYBackOffice;SelectMethod=cursor;"
maxActive="8" maxIdle="4"/>
<Resource name="jdbc/ORDB" auth="Container"
type="javax.sql.DataSource" username="***" password="***" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver:localhost;DatabaseName=XXBackOffice;SelectMethod=cursor;"
maxActive="8" maxIdle="4"/>
</code></pre>
<p>The Context tab does have a closing tab, eventually.</p>
<p>Please help! If you need any more information, please let me know. Also, I'm not sure which context.xml ought to be modified, there are 2 in the Tomcat directories, one in the /conf folder, and one in the webapps/appname/META-INF folder. Sorry if it sounds like I'm a bit of a rookie, that's because I am!</p>
<p>Also, I've seen many different examples of the url="..." part of the context.xml, some including port numbers. I have tried several things out online, but nothing seems to work (doesn't help nothing online is my exact data environment, also I suppose it's challenging that this app queries two different DBs at given times).</p>
<p>Thoughts?</p>
| 0 | 1,154 |
Twitter Bootstrap 2 modal form dialogs
|
<p>I have the following dialog form :</p>
<pre><code><div class='modal' id='myModal'>
<div class='modal-header'>
<a class='close' data-dismiss='modal'>×</a>
<h3>Add Tags</h3>
</div>
<div class='modal-body'>
<form accept-charset="UTF-8" action="/tagging" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="mCNvbvoPFWhD7SoJm9FPDh+BcRvCG3d16P+oOFACPuc=" /></div>
<input id="tags_string" name="tags_string" type="text" value="luca" />
<input id="id" name="id" type="hidden" value="4f1c95fd1d41c80ff200067f" />
</form>
</div>
<div class='modal-footer'>
<div class='btn btn-primary'><input name="commit" type="submit" value="Add tag" /></div>
</div>
</div>
</code></pre>
<p>and his JS :</p>
<pre><code><script>
//<![CDATA[
$(function() {
// wire up the buttons to dismiss the modal when shown
$("#myModal").bind("show", function() {
$("#myModal a.btn").click(function(e) {
// do something based on which button was clicked
// we just log the contents of the link element for demo purposes
console.log("button pressed: "+$(this).html());
// hide the dialog box
$("#myModal").modal('hide');
});
});
// remove the event listeners when the dialog is hidden
$("#myModal").bind("hide", function() {
// remove event listeners on the buttons
$("#myModal a.btn").unbind();
});
// finally, wire up the actual modal functionality and show the dialog
$("#myModal").modal({
"backdrop" : "static",
"keyboard" : true,
"show" : true // this parameter ensures the modal is shown immediately
});
});
//]]>
</script>
</code></pre>
<p>When I click x, which is <code><a class='close' data-dismiss='modal'>×</a></code>, the form close down leaving me on the current page, while I'd like to go on the hamepage. </p>
<p>Also "Add tag" botton, which is <code><div class='btn btn-primary'><input name="commit" type="submit" value="Add tag" /></div></code> don't do nothing, while clicking jaust ENTER on the keyboard do the job and I'd like clicking "Add tag" did the same.</p>
<p>I'm not so skilled on JS and front-end prog, so any help is welcome.</p>
| 0 | 1,114 |
Spring's LdapTemplate search: PartialResultException: Unprocessed Continuation Reference(s); remaining name '/'
|
<p>I add users through LDAP for a certain application, made with spring.</p>
<p>While this works for most of the cases, in some cases, it does not work...</p>
<p>The retrieve the users I use: </p>
<pre><code>public class LdapUserServiceImpl implements ILdapUserService {
@Override
public List<LdapUserVO> getUserNamesByQuery(String query) {
return ldapTemplate.search(
query().countLimit(15)
.where("objectClass").is("user")
.and("sAMAccountName").isPresent()
.and(query()
.where("sAMAccountName").like("*" + query + "*")
.or("sAMAccountName").is(query)
.or("displayName").like("*" + query + "*")
.or("displayName").is(query))
,
new AttributesMapper<LdapUserVO>() {
public LdapUserVO mapFromAttributes(Attributes attrs) throws NamingException {
LdapUserVO ldapUser = new LdapUserVO();
Attribute attr = attrs.get(ldapUserSearch);
if (attr != null && attr.get() != null) {
ldapUser.setUserName(attr.get().toString());
}
attr = attrs.get("displayName");
if (attr != null && attr.get() != null) {
ldapUser.setDisplayName(attr.get().toString());
}
return ldapUser;
}
});
}
}
</code></pre>
<p>So this works in most of the cases, but sometimes I get the following error:</p>
<pre><code>unprocessed continuation reference(s); remaining name "/"
</code></pre>
<p>I've searched a lot about this, and I explicitly set</p>
<pre><code>DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(ldapUrl);
ctxSrc.setReferral("follow");
</code></pre>
<p>Some more info:</p>
<ul>
<li>Search-query "admin_a" works, but "admin_ah" does not</li>
<li>Spring version is 4.2.5.RELEASE</li>
<li>Spring ldap-core version is 2.0.2.RELEASE</li>
</ul>
<p>I think it strange that the remaining name is the root directory... Does someone has any ideas how to fix this, or even where to start looking?</p>
<p>Thanks in advance!</p>
| 0 | 1,133 |
PrimeNG Form Validation
|
<p>I am using a mix of primeNG controls and html controls. The issue is the primeNG controls don't work properly for the phone mask and for he auto-complete the style is different .</p>
<p>for example:
<strong>html</strong> (phone is never showing as red if the user set focus on the control then just tab to the next control)</p>
<pre><code> <div class="form-group col-xs-3 col-md-3"
[ngClass]="{
'has-error':(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
!ersaForm.get('phone').valid
}">
<label for="phoneId" class="control-label">Phone</label><br />
<!--<input type="tel" class="form-control" id="phone" placeholder="Phone">-->
<p-inputMask mask="(999) 999-9999" formControlName="phone" id="nameId" required placeholder="Phone (required)"></p-inputMask>
<span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
ersaForm.get('phone').errors">
<span *ngIf="ersaForm.get('phone').errors">
Phone Number must be 9 charatcers.
</span>
</span>
</div>
</code></pre>
<p>for the auto complete it works , but the style is not consistent .</p>
<p><strong>html</strong></p>
<pre><code> <div class="form-group col-xs-3 col-md-3"
[ngClass]="{
'has-error':(ersaForm.get('costCenter').touched || ersaForm.get('costCenter').dirty ) &&
!ersaForm.get('costCenter').valid
}">
<label for="costCenterId" class="control-label">Cost Center</label>
<p-autoComplete formControlName="costCenter" id="costCenterId" [suggestions]="iCostCenter" placeholder="Cost Center (required)" (completeMethod)="searchCC($event)" [style]="{'width':'85%'}" [inputStyle]="{'width':'85%'}" field="cost_center_name" dataKey="cost_center_id" [dropdown]="true"></p-autoComplete>
</div>
<div class="form-group col-xs-3 col-md-3"
[ngClass]="{
'has-error':(ersaForm.get('gradeLevel').touched || ersaForm.get('gradeLevel').dirty ) &&
!ersaForm.get('gradeLevel').valid
}">
<label for="gradeLevelId" class="control-label">Grade Level</label>
<input type="text" class="form-control" id="gradeLevelId" formControlName="gradeLevel" maxlength="2" placeholder="Grade Level (required)">
<span class="help-block" *ngIf="(ersaForm.get('gradeLevel').touched || ersaForm.get('gradeLevel').dirty ) &&
ersaForm.get('gradeLevel').errors">
<span *ngIf="ersaForm.get('gradeLevel').errors.minlength">
Grade Level must be 2 characters.
</span>
</span>
</div>
<div class="form-group col-xs-3 col-md-3"
[ngClass]="{
'has-error':(ersaForm.get('manager').touched || ersaForm.get('manager').dirty ) &&
!ersaForm.get('manager').valid
}">
<label for="managerId" class="control-label">Manager</label>
<p-autoComplete
[![enter image description here][1]][1] [suggestions]="iManager" id="ManagerId" formControlName="manager" placeholder="Manager (required)" (completeMethod)="searchManager($event)" [style]="{'width':'85%'}" [inputStyle]="{'width':'85%'}" field="NT_USER_NM" dataKey="ORG_BRH_NO" [dropdown]="true"></p-autoComplete>
</div>
</div>
</code></pre>
<p>see the below image (the bottom boarder of the manager auto complete becomes red only if I select something then erase it </p>
<p><a href="https://i.stack.imgur.com/G80ev.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G80ev.jpg" alt="enter image description here"></a></p>
<p><strong>TS</strong></p>
<pre><code>this.ersaForm = this._fb.group({
gradeLevel: ['', [Validators.required, Validators.minLength(2)]],
manager: ['', Validators.required],
phone: ['', [Validators.required, Validators.minLength(9)]],
});
</code></pre>
| 0 | 2,832 |
how to change the Title in Navigation Drawer
|
<p>I would like that the title in the menu will change by the fragment name that was click. for the code below what i get is that, the actual title in each fragment is "Home" and its does not change. but i found that when i click on an item in the menu the title changing for a second and return back to the "Home" title. i implemented the ondrawer but still i don't know what could cause that.</p>
<p>my code:</p>
<pre><code> package com.example.matant.gpsportclient;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.matant.gpsportclient.Controllers.Fragments.CreateEventFragmentController;
import com.example.matant.gpsportclient.Controllers.DBcontroller;
import com.example.matant.gpsportclient.Controllers.Fragments.GoogleMapFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ManageEventFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ProfileFragmentController;
import com.example.matant.gpsportclient.InterfacesAndConstants.AsyncResponse;
import com.example.matant.gpsportclient.InterfacesAndConstants.Constants;
import com.example.matant.gpsportclient.Utilities.DrawerItem;
import com.example.matant.gpsportclient.Utilities.DrawerItemCustomAdapter;
import com.example.matant.gpsportclient.Utilities.SessionManager;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainScreen extends AppCompatActivity implements AsyncResponse {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DBcontroller dbController;
private ProgressDialog progress = null;
private SessionManager sm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
sm = SessionManager.getInstance(this);
mTitle = mDrawerTitle = "Home";
DrawerItem [] drawerItems = new DrawerItem[Constants.MENU_SIZE];
drawerItems[0] = new DrawerItem(R.drawable.home,"Home");
drawerItems[1] = new DrawerItem(R.drawable.profile,"Profile");
drawerItems[2] = new DrawerItem(R.drawable.search,"Search Events");
drawerItems[3] = new DrawerItem(R.drawable.create,"Create Event");
drawerItems[4] = new DrawerItem(R.drawable.manage,"Manage Event");
drawerItems[5] = new DrawerItem(R.drawable.attending,"Attending List");
drawerItems[6] = new DrawerItem(R.drawable.recent_search_24,"Recent Searches");
drawerItems[7] = new DrawerItem(R.drawable.logout,"Log Out");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[0]);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void handleResponse(String resStr) {
try
{
if((this.progress!= null )&& this.progress.isShowing())
{
this.progress.dismiss();
}
}catch (final IllegalArgumentException e){
Log.d("Dialog error",e.getMessage());
}catch (final Exception e){
Log.d("Dialog error",e.getMessage());
}
finally {
this.progress = null;
}
Log.d("handleResponse", resStr);
if(resStr!=null)
{
try {
JSONObject jsonObj = new JSONObject(resStr);
String flg = jsonObj.getString(Constants.TAG_FLG);
switch (flg) {
case "user logged out":
{
sm.logoutUser();
break;
}
case "query failed": {
Toast.makeText(getApplicationContext(),"Error Connection",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void sendDataToDBController() {
String user = sm.getUserDetails().get(Constants.TAG_EMAIL);
BasicNameValuePair tagReq = new BasicNameValuePair("tag","logout");
BasicNameValuePair userNameParam = new BasicNameValuePair("username",user);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(tagReq);
nameValuePairList.add(userNameParam);
dbController = new DBcontroller(this,this);
dbController.execute(nameValuePairList);
}
@Override
public void preProcess() {
this.progress = ProgressDialog.show(this, "Log Out",
"Logging out...", true,false);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0: //Home
fragment = new GoogleMapFragmentController();
break;
case 1: //Profile
fragment = new ProfileFragmentController();
break;
case 2: //Search Events
//fragment = new SearchEventFragmentController();
break;
case 3: //Create Events
fragment = new CreateEventFragmentController();
break;
case 4: //Manage Events
fragment = new ManageEventFragmentController();
break;
case 5: //Attending List
//fragment = new AttendingListFragmentController();
break;
case 6: //Recent Searches
//fragment = new RecentSearchesFragmentController();
break;
case 7: { //Log Out
logout();
finish(); //destroy the main activity
}
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void logout()
{
sendDataToDBController();
}
/*@Override
protected void onDestroy() {
super.onDestroy();
logout();
}*/
}
</code></pre>
| 0 | 4,314 |
Glide : How to find if the image is already cached and use the cached version?
|
<p><strong>Scenario</strong>: </p>
<p>I have a large GIF image which I want to cache the first time user opens the app using <a href="https://github.com/bumptech/glide" rel="noreferrer">Glide</a> - Image Loading and Caching library. After that whenever user opens the app, I want to show the cached version if present. This GIF URL will expire after a given interval. When it expires, I fetch the new GIF URL and display/cache that for future use.</p>
<p><strong>What I tried:</strong></p>
<p>I went through <a href="https://github.com/bumptech/glide/wiki/Caching-and-Cache-Invalidation" rel="noreferrer">Caching and Cache Invalidation</a> on Glide's github page. I also went though the Google Group thread <a href="https://groups.google.com/forum/#!topic/glidelibrary/TcFOy0tcxXA" rel="noreferrer">Ensuring That Images Loaded Only Come From Disk Cache</a>, which shows how to get the image form cache. I also went through <a href="https://stackoverflow.com/questions/31537669/how-to-invalidate-glide-cache-for-some-specific-images">How to invalidate Glide cache for some specific images</a> question.</p>
<p>From the links above I see the following code sniplet which shows how to load the image from cache. However this only tries to get the image from cache. If its not present in cache, it doesn't try to get from the network and fails:</p>
<pre><code>Glide.with(TheActivity.this)
.using(new StreamModelLoader<String>() {
@Override
public DataFetcher<InputStream> getResourceFetcher(final String model, int i, int i1) {
return new DataFetcher<InputStream>() {
@Override
public InputStream loadData(Priority priority) throws Exception {
throw new IOException();
}
@Override
public void cleanup() {
}
@Override
public String getId() {
return model;
}
@Override
public void cancel() {
}
};
}
})
.load("http://sampleurl.com/sample.gif")
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(theImageView);
</code></pre>
<p><strong>Questions:</strong></p>
<ol>
<li><p>Is there a cleaner way to achieve the following: Show the GIF image from the cache if present else download the GIF, cache it for later use and show it in the <code>ImageView</code>.</p></li>
<li><p>The caching article above mentions the following: </p>
<blockquote>
<p>In practice, the best way to invalidate a cache file is to change
your identifier when the content changes (url, uri, file path etc)</p>
</blockquote>
<p>The server sends a different URL to the app when the previous one expires. In this case, I believe the old image will eventually be Garbage Collected? Is there a way to force remove the image from the cache?</p></li>
<li><p>On a similar note, is there a way to prevent the Garbage Collection of an image with specific key (to prevent downloading the large file again) and then later instruct to delete the old image from cache when the URL changes?</p></li>
</ol>
| 0 | 1,232 |
Symfony2 UniqueConstraint and UniqueEntity (Integrity Violation)
|
<p>I've got a little problem with a Doctrine entity for a few days now. I've defined it with a UniqueConstraint on two fields with a UniqueEntity Validation on these two fields after that. But after validating of my form with a adding of an entity already in base, no way to obtain my error message in my form.</p>
<p>Just an error message from Symfony : </p>
<blockquote>
<p>SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '339057986-00012' for key 'SIRET'</p>
</blockquote>
<p>Here is my entity declaration, all seems fine to me but maybe have I forgotten or misunderstood something?</p>
<pre class="lang-php prettyprint-override"><code><?php
namespace Proetco\FrontBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Proetco\FrontBundle\Entity\Entreprise
*
* @ORM\Table(name="entreprise", uniqueConstraints={@ORM\UniqueConstraint(name="SIRET", columns={"SIREN", "NIC"})})
* @ORM\Entity(repositoryClass="Proetco\FrontBundle\Entity\EntrepriseRepository")
* @UniqueEntity(fields={"SIREN","NIC"}, message="Cette entreprise est déjà enregistrée")
*/
class Entreprise {
protected $Siret;
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $SIREN
*
* @ORM\Column(name="SIREN", type="string", length=9)
*/
private $SIREN;
/**
* @var string $NIC
*
* @ORM\Column(name="NIC", type="string", length=5)
*/
private $NIC;
/**
* @var string $RS
*
* @ORM\Column(name="RS", type="string", length=45, nullable=true)
*/
private $RS;
/**
* @var string $NCOM
*
* @ORM\Column(name="NCOM", type="string", length=45, nullable=true)
*/
private $NCOM;
/**
* @var string $CPOS
*
* @ORM\Column(name="CPOS", type="string", length=5, nullable=true)
*/
private $CPOS;
/**
* @var string $LCOM
*
* @ORM\Column(name="LCOM", type="string", length=45, nullable=true)
*/
private $LCOM;
/**
* @var string $INSEE
*
* @ORM\Column(name="INSEE", type="string", length=5, nullable=true, nullable=true)
*/
private $INSEE;
/**
* @var string $DEP
*
* @ORM\Column(name="DEP", type="string", length=2)
*/
private $DEP;
/**
* @var string $ARR
*
* @ORM\Column(name="ARR", type="string", length=1, nullable=true)
*/
private $ARR;
/**
* @var string $CAN
*
* @ORM\Column(name="CAN", type="string", length=2, nullable=true)
*/
private $CAN;
public function getSiret()
{
return $this->Siret;
}
public function setSiret($Siret)
{
$this->Siret = $Siret;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set SIREN
*
* @param string $sIREN
*/
public function setSIREN($sIREN)
{
$this->SIREN = $sIREN;
}
/**
* Get SIREN
*
* @return string
*/
public function getSIREN()
{
return $this->SIREN;
}
/**
* Set NIC
*
* @param string $nIC
*/
public function setNIC($nIC)
{
$this->NIC = $nIC;
}
/**
* Get NIC
*
* @return string
*/
public function getNIC()
{
return $this->NIC;
}
/**
* Set RS
*
* @param string $rS
*/
public function setRS($rS)
{
$this->RS = $rS;
}
/**
* Get RS
*
* @return string
*/
public function getRS()
{
return $this->RS;
}
/**
* Set NCOM
*
* @param string $nCOM
*/
public function setNCOM($nCOM)
{
$this->NCOM = $nCOM;
}
/**
* Get NCOM
*
* @return string
*/
public function getNCOM()
{
return $this->NCOM;
}
/**
* Set CPOS
*
* @param string $cPOS
*/
public function setCPOS($cPOS)
{
$this->CPOS = $cPOS;
}
/**
* Get CPOS
*
* @return string
*/
public function getCPOS()
{
return $this->CPOS;
}
/**
* Set LCOM
*
* @param string $lCOM
*/
public function setLCOM($lCOM)
{
$this->LCOM = $lCOM;
}
/**
* Get LCOM
*
* @return string
*/
public function getLCOM()
{
return $this->LCOM;
}
/**
* Set INSEE
*
* @param string $iNSEE
*/
public function setINSEE($iNSEE)
{
$this->INSEE = $iNSEE;
}
/**
* Get INSEE
*
* @return string
*/
public function getINSEE()
{
return $this->INSEE;
}
/**
* Set DEP
*
* @param string $dEP
*/
public function setDEP($dEP)
{
if (!isset($this->DEP))
$this->DEP = '02';
$this->DEP = $dEP;
}
/**
* Get DEP
*
* @return string
*/
public function getDEP()
{
if (!isset($this->DEP))
$this->DEP = '02';
return $this->DEP;
}
/**
* Set ARR
*
* @param string $aRR
*/
public function setARR($aRR)
{
$this->ARR = $aRR;
}
/**
* Get ARR
*
* @return string
*/
public function getARR()
{
return $this->ARR;
}
/**
* Set CAN
*
* @param string $cAN
*/
public function setCAN($cAN)
{
$this->CAN = $cAN;
}
/**
* Get CAN
*
* @return string
*/
public function getCAN()
{
return $this->CAN;
}
public function retrieveSiren($siret)
{
return substr($siret, 0, 9);
}
public function retrieveNic($siret)
{
return substr($siret, -5, 5);
}
//contraintes de validation
//TODO : valider les champs avec Regex
public function isSIREN()
{
}
public function isNIC()
{
}
}
</code></pre>
| 0 | 2,155 |
Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext
|
<p>Anyon know Why I keeo getting this error in Jupyter Notebooks??? I've been trying to load my Tensorflow model into Apache Spark vis SparlFlowbut I can't seem to figure out how to get past this error. Any help would be much appreciated.</p>
<p>First Jupyter cell: </p>
<pre><code>from sparkflow.graph_utils import build_graph
from sparkflow.tensorflow_async import SparkAsyncDL
import tensorflow as tf
from pyspark.ml.feature import VectorAssembler, OneHotEncoder
from pyspark.ml.pipeline import Pipeline
from pyspark.sql import SparkSession
from tensorflow.keras import layers
from tensorflow.keras import losses
</code></pre>
<p>Second Jupyter cell: </p>
<pre><code>def lstm_model(X_train, y_train):
# Reshapes to input neuron
inputs= keras.Input(shape = (X_train.shape[1], 1))\
#Training Layers
x_1 = layers.LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1))(inputs)
x_1 = layers.Dropout(0.2)(x_1)
x_1 = layers.LSTM(units = 50, return_sequences = True)(x_1)
x_1 = layers.Dropout(0.2)(x_1)
x_1 = layers.LSTM(units = 50, return_sequences = True)(x_1)
x_1 = layers.Dropout(0.2)(x_1)
x_1 = layers.LSTM(units = 50, return_sequences = True)(x_1)
x_1 = layers.Dropout(0.2)(x_1)
x_1 = layers.Flatten()(x_1)
# 1 output neuron for each column prediction
output = Dense(units=1)(x_1)
return losses.MeanSquaredError(y_train,output)
</code></pre>
<p>Third Jupyter Cell:</p>
<pre><code>def dataframe_input(pandas_dataframe):
train_data = pandas_dataframe[self.column_name].values
# Reshaping to a 2D array
train_data = train_data.reshape(-1,1)
print(train_data.dtype)
print(type(train_data))
print(train_data.shape)
# Feature Scaling
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_train_data =scaler.fit_transform(train_data)
# Initialzing each x_train and y_train datasets for each column
X_train = []
y_train = []
# Appending scaled training data to each dataset
for i in range(self.timesteps, len(train_data)):
X_train.append(scaled_train_data[i - self.timesteps:i, 0])
y_train.append(scaled_train_data[i, 0])
# Numpy array creation, Keras requires numpy arrays for Inputs
X_train, y_train = np.array(X_train, dtype=int), np.array(y_train)
print(X_train.shape)
print(X_train.dtype)
# Reshaping to a 3D matrix (970, 30, 1)
#X_train = np.reshape(X_train, (X_train[0], X_train[1], 1))
print(X_train.shape)
return X_train, y_train
</code></pre>
<p><strong>Fourth Jupyter Cell( Where Im getting the error):</strong></p>
<pre><code># Spark Session
# In order to use APIs of SQL, HIVE, and Streaming, no need to create separate contexts as sparkSession includes all the APIs.
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.getOrCreate()
# Reading CSVto a Spark DataFrame
df = spark.read.option("inferSchema", "true").csv('"../csv_test_files/stats.csv"')
# Convert the Spark dataframe into a Pandas Dataframe
pandas_dataframe = df.select("*").toPandas()
# Get the input and ouput data for passing to the model
X_train, y_train = dataframe_input(pandas_dataframe)
</code></pre>
<p><strong>Error Output:</strong> </p>
<pre><code>---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
<ipython-input-25-5143cc437b69> in <module>
3 spark = SparkSession \
4 .builder \
----> 5 .appName("Python Spark SQL basic example") \
6 .getOrCreate()
7
~/anaconda3/lib/python3.7/site-packages/pyspark/sql/session.py in getOrCreate(self)
171 for key, value in self._options.items():
172 sparkConf.set(key, value)
--> 173 sc = SparkContext.getOrCreate(sparkConf)
174 # This SparkContext may be an existing one.
175 for key, value in self._options.items():
~/anaconda3/lib/python3.7/site-packages/pyspark/context.py in getOrCreate(cls, conf)
365 with SparkContext._lock:
366 if SparkContext._active_spark_context is None:
--> 367 SparkContext(conf=conf or SparkConf())
368 return SparkContext._active_spark_context
369
~/anaconda3/lib/python3.7/site-packages/pyspark/context.py in __init__(self, master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, gateway, jsc, profiler_cls)
134 try:
135 self._do_init(master, appName, sparkHome, pyFiles, environment, batchSize, serializer,
--> 136 conf, jsc, profiler_cls)
137 except:
138 # If an error occurs, clean up in order to allow future SparkContext creation:
~/anaconda3/lib/python3.7/site-packages/pyspark/context.py in _do_init(self, master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, jsc, profiler_cls)
196
197 # Create the Java SparkContext through Py4J
--> 198 self._jsc = jsc or self._initialize_context(self._conf._jconf)
199 # Reset the SparkConf to the one actually used by the SparkContext in JVM.
200 self._conf = SparkConf(_jconf=self._jsc.sc().conf())
~/anaconda3/lib/python3.7/site-packages/pyspark/context.py in _initialize_context(self, jconf)
304 Initialize SparkContext in function to allow subclass specific initialization
305 """
--> 306 return self._jvm.JavaSparkContext(jconf)
307
308 @classmethod
~/anaconda3/lib/python3.7/site-packages/py4j/java_gateway.py in __call__(self, *args)
1523 answer = self._gateway_client.send_command(command)
1524 return_value = get_return_value(
-> 1525 answer, self._gateway_client, None, self._fqn)
1526
1527 for temp_arg in temp_args:
~/anaconda3/lib/python3.7/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
326 raise Py4JJavaError(
327 "An error occurred while calling {0}{1}{2}.\n".
--> 328 format(target_id, ".", name), value)
329 else:
330 raise Py4JError(
Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.net.BindException: Can't assign requested address: Service 'sparkDriver' failed after 16 retries (on a random free port)! Consider explicitly setting the appropriate binding address for the service 'sparkDriver' (for example spark.driver.bindAddress for SparkDriver) to the correct binding address.
at java.base/sun.nio.ch.Net.bind0(Native Method)
at java.base/sun.nio.ch.Net.bind(Net.java:461)
at java.base/sun.nio.ch.Net.bind(Net.java:453)
at java.base/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:227)
at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:128)
at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:558)
at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1283)
at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:501)
at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:486)
at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:989)
at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:254)
at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:364)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:463)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
at java.base/java.lang.Thread.run(Thread.java:834)
</code></pre>
| 0 | 3,346 |
Retrofit : java.lang.IllegalStateException: closed
|
<p>I am using two kind of interceptor, one is <strong>HttpLoggingInterceptor</strong> and another one is my custom <strong>AuthorizationInterceptor</strong></p>
<p>I am using below updated retrofit version library,</p>
<pre><code>def retrofit_version = "2.7.2"
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.0'
</code></pre>
<p>below is code</p>
<pre><code>private fun makeOkHttpClient(): OkHttpClient {
val logger = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
return OkHttpClient.Builder()
.addInterceptor(AuthorizationInterceptor(context)) <---- To put Authorization Barrier
.addInterceptor(logger) <---- To log Http request and response
.followRedirects(false)
.connectTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.writeTimeout(50, TimeUnit.SECONDS)
.build()
}
</code></pre>
<p>When I try to execute below code, in file named SynchronizationManager.kt, it gives me an error.</p>
<pre><code>var rulesResourcesServices = RetrofitInstance(context).buildService(RulesResourcesServices::class.java)
val response = rulesResourcesServices.getConfigFile(file).execute() <---In this line I am getting an exception... (which is at SynchronizationManager.kt:185)
</code></pre>
<p>My RulesResourcesServices class is here</p>
<p>After debug I found that when below function called, at that time I am getting an exception</p>
<pre><code>@GET("users/me/configfile")
fun getConfigFile(@Query("type") type: String): Call<ResponseBody>
</code></pre>
<p>I am getting following error</p>
<pre><code>java.lang.IllegalStateException: closed
at okio.RealBufferedSource.read(RealBufferedSource.kt:184)
at okio.ForwardingSource.read(ForwardingSource.kt:29)
at retrofit2.OkHttpCall$ExceptionCatchingResponseBody$1.read(OkHttpCall.java:288)
at okio.RealBufferedSource.readAll(RealBufferedSource.kt:293)
at retrofit2.Utils.buffer(Utils.java:316)<------- ANDROID IS HIGH-LIGHTING
at retrofit2.BuiltInConverters$BufferingResponseBodyConverter.convert(BuiltInConverters.java:103)
at retrofit2.BuiltInConverters$BufferingResponseBodyConverter.convert(BuiltInConverters.java:96)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:225)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:188)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall.execute(DefaultCallAdapterFactory.java:97)
at android.onetap.SynchronizationManager.downloadFile(SynchronizationManager.kt:185)
at android.base.repository.LoginRepository.downloadConfigFilesAndLocalLogin(LoginRepository.kt:349)
at android.base.repository.LoginRepository.access$downloadConfigFilesAndLocalLogin(LoginRepository.kt:48)
at android.base.repository.LoginRepository$loginTask$2.onSRPLoginComplete(LoginRepository.kt:210)
at android.base.repository.LoginRepository$performSyncLogin$srpLogin$1$1.onSRPLogin(LoginRepository.kt:478)
at android.srp.SRPManager$SRPLoginOperation$execute$1.invokeSuspend(SRPManager.kt:323)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:561)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:727)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:667)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:655)
</code></pre>
<p>Below is screenshot, in that you can see that, I am getting output of file but don't know why it is throwing an exception. </p>
<p><a href="https://i.stack.imgur.com/fmyQH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fmyQH.png" alt="enter image description here"></a></p>
<p>checked Retrofit's Utils class</p>
<p><a href="https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Utils.java" rel="noreferrer">https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Utils.java</a></p>
<pre><code>static ResponseBody buffer(final ResponseBody body) throws IOException {
Buffer buffer = new Buffer();
body.source().readAll(buffer); <-This line throws an error.
return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
}
</code></pre>
<p><strong>Update</strong></p>
<p>Same thing is working fine with enqueue method.</p>
<pre><code>response.enqueue(object : Callback<ResponseBody?> {
override fun onResponse(call: Call<ResponseBody?>, response: retrofit2.Response<ResponseBody?>) {
}
})
</code></pre>
<p>I have post same issue with Retrofit team, lets see.</p>
<p><a href="https://github.com/square/retrofit/issues/3336" rel="noreferrer">https://github.com/square/retrofit/issues/3336</a></p>
| 0 | 1,835 |
WildFly: Error on start up
|
<p>I keep getting this silly error, when trying to start up a wildfly server:</p>
<p><img src="https://i.stack.imgur.com/OzN61.png" alt="WildFyl error"></p>
<p>How to fix it? I was googling for like 2 hours now and could not find any solution.
My JAVA_HOME is set to C:\Apps\Java\jdk1.7.0_51
I tried with changing it to jre folder but same error. I also have jdk\bin folder in PATH. </p>
<p>Help me please. </p>
<p>EDIT: Here is the code of batch script. I did not touch it, it camed with the wildfly:</p>
<pre><code>@echo off
rem -------------------------------------------------------------------------
rem JBoss Bootstrap Script for Windows
rem -------------------------------------------------------------------------
rem Use --debug to activate debug mode with an optional argument to specify the port
rem Usage : standalone.bat --debug
rem standalone.bat --debug 9797
@if not "%ECHO%" == "" echo %ECHO%
@if "%OS%" == "Windows_NT" setlocal
rem By default debug mode is disable.
set DEBUG_MODE=false
set DEBUG_PORT=8787
rem Set to all parameters by default
set "SERVER_OPTS=%*"
rem Get the program name before using shift as the command modify the variable ~nx0
if "%OS%" == "Windows_NT" (
set "PROGNAME=%~nx0%"
) else (
set "PROGNAME=standalone.bat"
)
if "%OS%" == "Windows_NT" (
set "DIRNAME=%~dp0%"
) else (
set DIRNAME=.\
)
rem Read command-line args.
:READ-ARGS
if "%1" == "" (
goto MAIN
) else if "%1" == "--debug" (
goto READ-DEBUG-PORT
) else (
rem This doesn't work as Windows splits on = and spaces by default
rem set SERVER_OPTS=%SERVER_OPTS% %1
shift
goto READ-ARGS
)
:READ-DEBUG-PORT
set "DEBUG_MODE=true"
set DEBUG_ARG="%2"
if not "x%DEBUG_ARG" == "x" (
if x%DEBUG_ARG:-=%==x%DEBUG_ARG% (
shift
set DEBUG_PORT=%DEBUG_ARG%
)
shift
goto READ-ARGS
)
:MAIN
rem $Id$
)
pushd "%DIRNAME%.."
set "RESOLVED_JBOSS_HOME=%CD%"
popd
if "x%JBOSS_HOME%" == "x" (
set "JBOSS_HOME=%RESOLVED_JBOSS_HOME%"
)
pushd "%JBOSS_HOME%"
set "SANITIZED_JBOSS_HOME=%CD%"
popd
if /i "%RESOLVED_JBOSS_HOME%" NEQ "%SANITIZED_JBOSS_HOME%" (
echo.
echo WARNING: JBOSS_HOME may be pointing to a different installation - unpredictable results may occur.
echo.
echo JBOSS_HOME: "%JBOSS_HOME%"
echo.
)
rem Read an optional configuration file.
if "x%STANDALONE_CONF%" == "x" (
set "STANDALONE_CONF=%DIRNAME%standalone.conf.bat"
)
if exist "%STANDALONE_CONF%" (
echo Calling "%STANDALONE_CONF%"
call "%STANDALONE_CONF%" %*
) else (
echo Config file not found "%STANDALONE_CONF%"
)
rem Set debug settings if not already set
if "%DEBUG_MODE%" == "true" (
echo "%JAVA_OPTS%" | findstr /I "\-agentlib:jdwp" > nul
if errorlevel == 1 (
set "JAVA_OPTS=%JAVA_OPTS% -agentlib:jdwp=transport=dt_socket,address=%DEBUG_PORT%,server=y,suspend=n"
) else (
echo Debug already enabled in JAVA_OPTS, ignoring --debug argument
)
)
set DIRNAME=
rem Setup JBoss specific properties
set "JAVA_OPTS=-Dprogram.name=%PROGNAME% %JAVA_OPTS%"
if "x%JAVA_HOME%" == "x" (
set JAVA=java
echo JAVA_HOME is not set. Unexpected results may occur.
echo Set JAVA_HOME to the directory of your local JDK to avoid this message.
) else (
if not exist "%JAVA_HOME%" (
echo JAVA_HOME "%JAVA_HOME%" path doesn't exist
goto END
) else (
echo Setting JAVA property to "%JAVA_HOME%\bin\java"
set "JAVA=%JAVA_HOME%\bin\java"
)
)
if not "%PRESERVE_JAVA_OPTS%" == "true" (
rem Add -client to the JVM options, if supported (32 bit VM), and not overriden
echo "%JAVA_OPTS%" | findstr /I \-server > nul
if errorlevel == 1 (
"%JAVA%" -client -version 2>&1 | findstr /I /C:"Client VM" > nul
if not errorlevel == 1 (
set "JAVA_OPTS=-client %JAVA_OPTS%"
)
)
)
if not "%PRESERVE_JAVA_OPTS%" == "true" (
rem Add compressed oops, if supported (64 bit VM), and not overriden
echo "%JAVA_OPTS%" | findstr /I "\-XX:\-UseCompressedOops \-client" > nul
if errorlevel == 1 (
"%JAVA%" -XX:+UseCompressedOops -version > nul 2>&1
if not errorlevel == 1 (
set "JAVA_OPTS=-XX:+UseCompressedOops %JAVA_OPTS%"
)
)
)
rem Find jboss-modules.jar, or we can't continue
if exist "%JBOSS_HOME%\jboss-modules.jar" (
set "RUNJAR=%JBOSS_HOME%\jboss-modules.jar"
) else (
echo Could not locate "%JBOSS_HOME%\jboss-modules.jar".
echo Please check that you are in the bin directory when running this script.
goto END
)
rem Setup JBoss specific properties
rem Setup directories, note directories with spaces do not work
set "CONSOLIDATED_OPTS=%JAVA_OPTS% %SERVER_OPTS%"
:DIRLOOP
echo(%CONSOLIDATED_OPTS% | findstr /r /c:"^-Djboss.server.base.dir" > nul && (
for /f "tokens=1,2* delims==" %%a IN ("%CONSOLIDATED_OPTS%") DO (
for /f %%i IN ("%%b") DO set "JBOSS_BASE_DIR=%%~fi"
)
)
echo(%CONSOLIDATED_OPTS% | findstr /r /c:"^-Djboss.server.config.dir" > nul && (
for /f "tokens=1,2* delims==" %%a IN ("%CONSOLIDATED_OPTS%") DO (
for /f %%i IN ("%%b") DO set "JBOSS_CONFIG_DIR=%%~fi"
)
)
echo(%CONSOLIDATED_OPTS% | findstr /r /c:"^-Djboss.server.log.dir" > nul && (
for /f "tokens=1,2* delims==" %%a IN ("%CONSOLIDATED_OPTS%") DO (
for /f %%i IN ("%%b") DO set "JBOSS_LOG_DIR=%%~fi"
)
)
for /f "tokens=1* delims= " %%i IN ("%CONSOLIDATED_OPTS%") DO (
if %%i == "" (
goto ENDDIRLOOP
) else (
set CONSOLIDATED_OPTS=%%j
GOTO DIRLOOP
)
)
:ENDDIRLOOP
rem Set default module root paths
if "x%JBOSS_MODULEPATH%" == "x" (
set "JBOSS_MODULEPATH=%JBOSS_HOME%\modules"
)
rem Set the standalone base dir
if "x%JBOSS_BASE_DIR%" == "x" (
set "JBOSS_BASE_DIR=%JBOSS_HOME%\standalone"
)
rem Set the standalone log dir
if "x%JBOSS_LOG_DIR%" == "x" (
set "JBOSS_LOG_DIR=%JBOSS_BASE_DIR%\log"
)
rem Set the standalone configuration dir
if "x%JBOSS_CONFIG_DIR%" == "x" (
set "JBOSS_CONFIG_DIR=%JBOSS_BASE_DIR%\configuration"
)
echo ===============================================================================
echo.
echo JBoss Bootstrap Environment
echo.
echo JBOSS_HOME: "%JBOSS_HOME%"
echo.
echo JAVA: "%JAVA%"
echo.
echo JAVA_OPTS: "%JAVA_OPTS%"
echo.
echo ===============================================================================
echo.
:RESTART
"%JAVA%" %JAVA_OPTS% ^
"-Dorg.jboss.boot.log.file=%JBOSS_LOG_DIR%\server.log" ^
"-Dlogging.configuration=file:%JBOSS_CONFIG_DIR%/logging.properties" ^
-jar "%JBOSS_HOME%\jboss-modules.jar" ^
-mp "%JBOSS_MODULEPATH%" ^
org.jboss.as.standalone ^
"-Djboss.home.dir=%JBOSS_HOME%" ^
%SERVER_OPTS%
if ERRORLEVEL 10 goto RESTART
:END
if "x%NOPAUSE%" == "x" pause
:END_NO_PAUSE
</code></pre>
| 0 | 2,740 |
Problems with createImage(int width, int height)
|
<p>I have the following code, which is run every 10ms as part of a game:</p>
<pre><code>private void gameRender()
{
if(dbImage == null)
{
//createImage() returns null if GraphicsEnvironment.isHeadless()
//returns true. (java.awt.GraphicsEnvironment)
dbImage = createImage(PWIDTH, PHEIGHT);
if(dbImage == null)
{
System.out.println("dbImage is null"); //Error recieved
return;
}
else
dbg = dbImage.getGraphics();
}
//clear the background
dbg.setColor(Color.white);
dbg.fillRect(0, 0, PWIDTH, PHEIGHT);
//draw game elements...
if(gameOver)
{
gameOverMessage(dbg);
}
}
</code></pre>
<p>The problem is that it enters the if statement which checks for the Image being null, even after I attempt to define the image. I looked around, and it seems that createImage() will return null if GraphicsEnvironment.isHeadless() returns true.</p>
<p>I don't understand exactly what the isHeadless() method's purpose is, but I thought it might have something to do with the compiler or IDE, so I tried on two, both of which get the same error (Eclipse, and BlueJ). Anyone have any idea what the source of the error is, and how I might fix it?</p>
<p>Thanks in advance</p>
<p>Jonathan</p>
<p>...................................................................</p>
<p>EDIT:
I am using java.awt.Component.createImage(int width, int height). The purpose of this method is to ensure the creation of, and edit an Image that will contain the view of the player of the game, that will later be drawn to the screen by means of a JPanel.
Here is some more code if this helps at all:</p>
<pre><code>public class Sim2D extends JPanel implements Runnable
{
private static final int PWIDTH = 500;
private static final int PHEIGHT = 400;
private volatile boolean running = true;
private volatile boolean gameOver = false;
private Thread animator;
//gameRender()
private Graphics dbg;
private Image dbImage = null;
public Sim2D()
{
setBackground(Color.white);
setPreferredSize(new Dimension(PWIDTH, PHEIGHT));
setFocusable(true);
requestFocus(); //Sim2D now recieves key events
readyForTermination();
addMouseListener( new MouseAdapter() {
public void mousePressed(MouseEvent e)
{ testPress(e.getX(), e.getY()); }
});
} //end of constructor
private void testPress(int x, int y)
{
if(!gameOver)
{
gameOver = true; //end game at mousepress
}
} //end of testPress()
private void readyForTermination()
{
addKeyListener( new KeyAdapter() {
public void keyPressed(KeyEvent e)
{ int keyCode = e.getKeyCode();
if((keyCode == KeyEvent.VK_ESCAPE) ||
(keyCode == KeyEvent.VK_Q) ||
(keyCode == KeyEvent.VK_END) ||
((keyCode == KeyEvent.VK_C) && e.isControlDown()) )
{
running = false; //end process on above list of keypresses
}
}
});
} //end of readyForTermination()
public void addNotify()
{
super.addNotify(); //creates the peer
startGame(); //start the thread
} //end of addNotify()
public void startGame()
{
if(animator == null || !running)
{
animator = new Thread(this);
animator.start();
}
} //end of startGame()
//run method for world
public void run()
{
while(running)
{
long beforeTime, timeDiff, sleepTime;
beforeTime = System.nanoTime();
gameUpdate(); //updates objects in game (step event in game)
gameRender(); //renders image
paintScreen(); //paints rendered image to screen
timeDiff = (System.nanoTime() - beforeTime) / 1000000;
sleepTime = 10 - timeDiff;
if(sleepTime <= 0) //if took longer than 10ms
{
sleepTime = 5; //sleep a bit anyways
}
try{
Thread.sleep(sleepTime); //sleep by allotted time (attempts to keep this loop to about 10ms)
}
catch(InterruptedException ex){}
beforeTime = System.nanoTime();
}
System.exit(0);
} //end of run()
private void gameRender()
{
if(dbImage == null)
{
dbImage = createImage(PWIDTH, PHEIGHT);
if(dbImage == null)
{
System.out.println("dbImage is null");
return;
}
else
dbg = dbImage.getGraphics();
}
//clear the background
dbg.setColor(Color.white);
dbg.fillRect(0, 0, PWIDTH, PHEIGHT);
//draw game elements...
if(gameOver)
{
gameOverMessage(dbg);
}
} //end of gameRender()
} //end of class Sim2D
</code></pre>
<p>Hope this helps clear things up a bit,
Jonathan</p>
| 0 | 1,876 |
How to enable code hinting using codemirror?
|
<p>I am using codemirror to allow the user to type anycode like css/html/js.</p>
<p>I need to enable if the user type something like in css mode</p>
<pre><code>div {
padding-
}
</code></pre>
<p>It should hint the user to chose the available options from the list like</p>
<pre><code>div {
padding-top
padding-left
padding-right
padding-bottom
}
</code></pre>
<p>Something like sublime editor using codemirror. Please see the attached image for the demo of sublime auto hinting</p>
<p><a href="https://i.stack.imgur.com/S6lvJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/S6lvJ.png" alt="enter image description here"></a></p>
<p>Here is my code: </p>
<pre><code> <script src="codemirror-5.4/mode/javascript/javascript.js"></script>
<script src="codemirror-5.4/mode/css/css.js"></script>
<script src="codemirror-5.4/mode/htmlmixed/htmlmixed.js"></script>
<script src="codemirror-5.4/addon/display/fullscreen.js"></script>
<script src="codemirror-5.4/keymap/sublime.js"></script>
<script src="codemirror-5.4/addon/hint/show-hint.js"></script>
<script src="codemirror-5.4/addon/hint/css-hint.js"></script>
<script src="codemirror-5.4/addon/hint/javascript.js"></script>
<h3>Editor</h3>
<div class="control-group">
<label class="control-label" for="textarea2">HTML</label>
<div class="controls">
<textarea class="code" name="code" id="codert" cols="40" rows="5" placeholder="Enter code here ..." style="width: 810px; height: 200px">
</textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="textarea3">CSS</label>
<div class="controls">
<textarea id="code" class="code" name="codeCSS" cols="40" rows="5" placeholder="Enter code here ..." style="width: 810px; height: 200px">
</textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="textarea3">javascript</label>
<div class="controls">
<textarea id="codeJS" class="code" name="codeJS" cols="40" rows="5" placeholder="Enter code here ..." style="width: 0px; height: 0px">
</textarea>
</div>
</div>
</code></pre>
<p><strong>JavaScript code for codemirror</strong></p>
<pre><code><script>
function loadCSS() {
var $head = $("#preview").contents().find("head");
$head.html("<style>" + editor.getValue() + "</style>");
};
function loadJS() {
var scriptTag = "<script>"+editorJS.getValue()+"<";
scriptTag += "/script>";
var previewFrame2 = document.getElementById('preview');
var preview2 = previewFrame2.contentDocument || previewFrame2.contentWindow.document;
preview2.open();
preview2.write(editor2.getValue()+scriptTag);
preview2.close();
loadCSS();
};
var delay;
// Initialize CodeMirror editor with a nice html5 canvas demo.
// css editor
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
lineNumbers: true,
styleActiveLine: true,
matchBrackets: true,
mode: "text/x-scss",
keyMap: "sublime",
theme: 'monokai',
autoCloseTags: true,
lineWrapping: true,
extraKeys: {"Ctrl-Space": "autocomplete"}
});
editor.on("change", function() {
clearTimeout(delay);
delay = setTimeout(updatePreview, 0);
});
function updatePreview() {
loadCSS();
}
setTimeout(updatePreview, 0);
var delay2;
// Initialize CodeMirror editor with a nice html5 canvas demo.
var editor2 = CodeMirror.fromTextArea(document.getElementById('codert'), {
lineNumbers: true,
styleActiveLine: true,
matchBrackets: true,
mode: "text/html",
keyMap: "sublime",
theme: 'monokai',
autoCloseTags: true,
lineWrapping: true,
extraKeys: {"Ctrl-Space": "autocomplete"}
});
editor2.on("change", function() {
clearTimeout(delay2);
delay2 = setTimeout(updatePreview2, 0);
});
function updatePreview2() {
var scriptTag = "<script>"+editorJS.getValue()+"<";
scriptTag += "/script>";
var previewFrame2 = document.getElementById('preview');
var preview2 = previewFrame2.contentDocument || previewFrame2.contentWindow.document;
preview2.open();
preview2.write(editor2.getValue()+scriptTag);
preview2.close();
loadCSS();
}
setTimeout(updatePreview2, 0);
var delayJS;
// Initialize CodeMirror editor with a nice html5 canvas demo.
var editorJS = CodeMirror.fromTextArea(document.getElementById('codeJS'), {
lineNumbers: true,
styleActiveLine: true,
matchBrackets: true,
mode: 'javascript',
keyMap: "sublime",
theme: 'monokai',
autoCloseTags: true,
lineWrapping: true,
extraKeys: {"Ctrl-Space": "autocomplete"}
});
editorJS.on("change", function() {
clearTimeout(delayJS);
delayJS = setTimeout(updatePreviewJS, 0);
});
function updatePreviewJS() {
loadJS();
}
setTimeout(updatePreviewJS, 0);
</script>
</code></pre>
| 0 | 2,130 |
JAXB not available on Tomcat 9 and Java 9/10
|
<p><strong>TLDR</strong>: On Java 9/10, a web app in Tomcat has no access to JAXB even though its reference implementation is present on the class path.</p>
<p><strong>Edit</strong>: No, this is not a duplicate of <a href="https://stackoverflow.com/q/43574426/2525313">How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException in Java 9</a> - as you can tell by the <em>What I tried</em> section, I already tried the proposed solutions.</p>
<h1>The Situation</h1>
<p>We have a web app that runs on Tomcat and depends on JAXB. During our migration to Java 9 we opted for adding <a href="https://stackoverflow.com/a/48204154/2525313">the JAXB reference implementation as a regular dependency</a>.</p>
<p>Everything worked when launching the app from the IDE <a href="https://tomcat.apache.org/tomcat-9.0-doc/api/org/apache/catalina/startup/Tomcat.html" rel="noreferrer">with embedded Tomcat</a>, but when running it on a real Tomcat instance, I get this error:</p>
<pre><code>Caused by: java.lang.RuntimeException: javax.xml.bind.JAXBException:
Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
at [... our-code ...]
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ContextFinder.find(ContextFinder.java:421) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662) ~[jaxb-api-2.3.0.jar:2.3.0]
at [... our-code ...]
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
at jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582) ~[?:?]
at jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190) ~[?:?]
at java.lang.ClassLoader.loadClass(ClassLoader.java:499) ~[?:?]
at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:276) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ContextFinder.find(ContextFinder.java:421) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662) ~[jaxb-api-2.3.0.jar:2.3.0]
at [... our-code ...]
</code></pre>
<p>Note:</p>
<blockquote>
<p>Implementation of JAXB-API has not been found on module path or classpath.</p>
</blockquote>
<p>These are the relevant files in <code>webapps/$app/WEB-INF/lib</code>:</p>
<pre><code>jaxb-api-2.3.0.jar
jaxb-core-2.3.0.jar
jaxb-impl-2.3.0.jar
</code></pre>
<p>What is going on here?</p>
<h1>What I tried</h1>
<h2>Adding JARs to Tomca's <code>CLASSPATH</code></h2>
<p>Maybe it helps to add the JARs to Tomcat's class path in <code>setenv.sh</code>?</p>
<pre><code>CLASSPATH=
.../webapps/$app/WEB-INF/lib/jaxb-api-2.3.0.jar:
.../webapps/$app/WEB-INF/lib/jaxb-impl-2.3.0.jar:
.../webapps/$app/WEB-INF/lib/jaxb-core-2.3.0.jar:
.../webapps/$app/WEB-INF/lib/javax.activation-1.2.0.jar
</code></pre>
<p>Nope:</p>
<pre><code>Caused by: javax.xml.bind.JAXBException: ClassCastException: attempting to cast
jar:file:.../webapps/$app/WEB-INF/lib/jaxb-api-2.3.0.jar!/javax/xml/bind/JAXBContext.class to
jar:file:.../webapps/$app/WEB-INF/lib/jaxb-api-2.3.0.jar!/javax/xml/bind/JAXBContext.class.
Please make sure that you are specifying the proper ClassLoader.
at javax.xml.bind.ContextFinder.handleClassCastException(ContextFinder.java:157) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:300) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:286) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ContextFinder.find(ContextFinder.java:409) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662) ~[jaxb-api-2.3.0.jar:2.3.0]
at de.disy.gis.webmapserver.factory.DefaultWmsRequestFactory.initializeCommandExtractor(DefaultWmsRequestFactory.java:103) ~[cadenza-gis-webmapserver-7.7-SNAPSHOT.jar:7.6]
at de.disy.gis.webmapserver.factory.DefaultWmsRequestFactory.lambda$new$0(DefaultWmsRequestFactory.java:87) ~[cadenza-gis-webmapserver-7.7-SNAPSHOT.jar:7.6]
</code></pre>
<p>That's clearly the same class, so apparently it has been loaded by two class loaders. I suspect <a href="https://tomcat.apache.org/tomcat-9.0-doc/class-loader-howto.html#Class_Loader_Definitions" rel="noreferrer">the system class loader and the app's class loader</a>, but why would loading <code>JAXBContext</code> be delegated to the system class loader once but not always? It almost looks as if the delegation behavior of the app's class loader changes while the program runs.</p>
<h2>Adding the module</h2>
<p>I don't really want to add <em>java.xml.bind</em>, but I tried it anyways by adding this to <code>catalina.sh</code>:</p>
<pre><code>JDK_JAVA_OPTIONS="$JDK_JAVA_OPTIONS --add-modules=java.xml.bind"
</code></pre>
<p>Doesn't work either, though:</p>
<pre><code>Caused by: java.lang.ClassCastException:
java.xml.bind/com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl
cannot be cast to com.sun.xml.bind.v2.runtime.JAXBContextImpl
at [... our-code ...]
</code></pre>
<p>Apart from the different class and stack trace, this is in line with what happened earlier: The class <code>JAXBContextImpl</code> was loaded twice, once from <em>java.xml.bind</em> (must have been the system class loader) and one other time (I assume by the app's loader from the JAR).</p>
<h2>Searching for bugs</h2>
<p><a href="https://bz.apache.org/bugzilla/query.cgi" rel="noreferrer">Searching Tomcat's bug database</a> I found <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=62559" rel="noreferrer">#62559</a>. Could that be the same error?</p>
<h2>Adding JAR's to Tomcat's <code>lib</code></h2>
<p>Following <a href="http://mail-archives.apache.org/mod_mbox/tomcat-users/201807.mbox/%3cb1ca948e-f8d3-5c5e-9aaf-0c8c6c9f84d0@christopherschultz.net%3e" rel="noreferrer">advice given on the Tomcat user mailing list</a>, I added the JAXB JARs to Tomcat's <code>CATALINA_BASE/lib</code> directory, but got the same error as in the application's lib folder.</p>
| 0 | 2,826 |
Eject USB device via C#
|
<p>I was looking for a short way to eject USB-devices via C#-code, so I coded a little class myself, yet it simply doesn't work. Since there's no popup that says "Lock success!" I assume that the problem relies within the "LockVolume"-function, but I don't know where.</p>
<p>Does anybody see the mistake I made?</p>
<pre><code>class USBEject
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
uint nInBufferSize,
IntPtr lpOutBuffer,
uint nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped
);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
byte[] lpInBuffer,
uint nInBufferSize,
IntPtr lpOutBuffer,
uint nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped
);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
private IntPtr handle = IntPtr.Zero;
const int GENERIC_READ = 0x80000000;
const int GENERIC_WRITE = 0x40000000;
const int FILE_SHARE_READ = 0x1;
const int FILE_SHARE_WRITE = 0x2;
const int FSCTL_LOCK_VOLUME = 0x00090018;
const int FSCTL_DISMOUNT_VOLUME = 0x00090020;
const int IOCTL_STORAGE_EJECT_MEDIA = 0x2D4808;
const int IOCTL_STORAGE_MEDIA_REMOVAL = 0x002D4804;
/// <summary>
/// Constructor for the USBEject class
/// </summary>
/// <param name="driveLetter">This should be the drive letter. Format: F:/, C:/..</param>
public USBEject(string driveLetter)
{
string filename = @"\\.\" + driveLetter[0] + ":";
handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, 0x3, 0, IntPtr.Zero);
}
public bool Eject()
{
if (LockVolume(handle) && DismountVolume(handle))
{
PreventRemovalOfVolume(handle, false);
return AutoEjectVolume(handle);
}
return false;
}
private bool LockVolume(IntPtr handle)
{
uint byteReturned;
for (int i = 0; i < 10; i++)
{
if (DeviceIoControl(handle, FSCTL_LOCK_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, out byteReturned, IntPtr.Zero))
{
System.Windows.Forms.MessageBox.Show("Lock success!");
return true;
}
Thread.Sleep(500);
}
return false;
}
private bool PreventRemovalOfVolume(IntPtr handle, bool prevent)
{
byte[] buf = new byte[1];
uint retVal;
buf[0] = (prevent) ? (byte)1 : (byte)0;
return DeviceIoControl(handle, IOCTL_STORAGE_MEDIA_REMOVAL, buf, 1, IntPtr.Zero, 0, out retVal, IntPtr.Zero);
}
private bool DismountVolume(IntPtr handle)
{
uint byteReturned;
return DeviceIoControl(handle, FSCTL_DISMOUNT_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, out byteReturned, IntPtr.Zero);
}
private bool AutoEjectVolume(IntPtr handle)
{
uint byteReturned;
return DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, out byteReturned, IntPtr.Zero);
}
private bool CloseVolume(IntPtr handle)
{
return CloseHandle(handle);
}
}
</code></pre>
| 0 | 1,740 |
Record Audio on Website that works on all browsers and iOS
|
<p>I have wasted a ton of time implementing multiple audio recording options in a website I'm building but each one either only works in Chrome, only in Firefox, both but not Safari, and none work on iOS. </p>
<p>The website needs to allows the user to record their message and save it in a form state for submission. </p>
<p>All the current articles I am reading are a few months old and mention that iOS doesn't/will support it soon. I've tried mobile Chrome on iOS and it still didn't work. </p>
<p>Has anyone found a way to simply record audio in a browser as well as mobile website??</p>
<p>Things I've tried:</p>
<ul>
<li>Francium Voice (An abandoned javascript project, works for Chrome. Records and saves and I am able to send the audio file through the form data. <a href="https://subinsb.com/html5-record-mic-voice/" rel="noreferrer">https://subinsb.com/html5-record-mic-voice/</a>. But this uses the < audio > tag which shows as "error" and doesn't allow you to record. </li>
<li>I started trying getUserMedia() as that seems to be the new standard and says it's supported on more devices/browsers but the mic wouldn't work on iOS either. <a href="https://www.html5rocks.com/en/tutorials/getusermedia/intro/" rel="noreferrer">https://www.html5rocks.com/en/tutorials/getusermedia/intro/</a></li>
<li>Many articles say to use the Record.js, <a href="https://github.com/mattdiamond/Recorderjs" rel="noreferrer">https://github.com/mattdiamond/Recorderjs</a>, but that is also an abandoned project. I could only get the audio to record, but it wasn't saving it. Again not working in Safari or iOS. </li>
<li>I tried using the audio/* technique but couldn't get it to work right. It would only show an upload button, couldn't get the mic option to show. Based on the documentation it seems like the one that "should" work though. <a href="https://developers.google.com/web/fundamentals/media/recording-audio/" rel="noreferrer">https://developers.google.com/web/fundamentals/media/recording-audio/</a></li>
</ul>
<p>Currently using the following code which works, for Chrome and Firefox.</p>
<p>HTML</p>
<p><code><audio controls src="" id="audio"></audio>
<a class="button" id="record">Record</a>
<input type="hidden" id="audiofile" name="audiofile" value="" aria-hidden="true"/></code></p>
<p>Using the Francium Voice library:</p>
<p>Javascript</p>
<pre><code> // Audio Recording for Phone Calls
$(document).on("click", "#record:not(.stop)", function(){
elem = $(this);
$("#audio").attr("src","");
$("#audiofile").val("");
Fr.voice.record($("#live").is(":checked"), function(){
elem.addClass("stop");
});
elem.html("Stop <label id='minutes'>00</label>:<label id='seconds'>00</label>");
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
});
$(document).on("click", ".stop", function(){
elem = $(this);
elem.html("Record");
elem.removeClass("stop");
Fr.voice.export(function(base64){
$("#audio").attr("src", base64);
$("#audiofile").val(base64);
$("#audio")[0].play();
}, "base64");
Fr.voice.stop();
});
</code></pre>
| 0 | 1,279 |
JavaFx USE_COMPUTED_SIZE for Stage without using FXML
|
<p>In the JavaFX Scene Builder, I can select a value for the minimum, maximum and preferred width and height of a <code>Control</code> or <code>Container</code>. There are predefined values like <code>USE_COMPUTED_SIZE</code>.</p>
<p>I came to the conclusion, that I don't like to use FXML for my current project, for several reasons and now I am wondering how to set those values when not using FXML.</p>
<p>How do I do this?</p>
<p>I've tried the following code:</p>
<pre><code>initializeControls();
addControls();
setMinHeight(Control.USE_COMPUTED_SIZE);
setMinWidth(Control.USE_COMPUTED_SIZE);
addActionListeners();
addFocusChangeListeners();
</code></pre>
<p>However, that results in an Exception when trying to create the Stage:</p>
<pre><code>Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: The width and height must be >= 0. Got: width=-1; height=-1
at com.sun.glass.ui.Window.setMinimumSize(Window.java:984)
at com.sun.javafx.tk.quantum.WindowStage.setMinimumSize(WindowStage.java:291)
at javafx.stage.Stage.impl_visibleChanging(Stage.java:1154)
at javafx.stage.Window$9.invalidated(Window.java:743)
at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:143)
at javafx.stage.Window.setShowing(Window.java:841)
at javafx.stage.Window.show(Window.java:856)
at javafx.stage.Stage.show(Stage.java:255)
at dictionary.MainApp.trainVocablesButtonActionPerformed(MainApp.java:281)
at dictionary.MainApp.lambda$addActionListeners$2(MainApp.java:240)
at dictionary.MainApp$$Lambda$281/81350454.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8216)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
at com.sun.glass.ui.View.notifyMouse(View.java:925)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$45(GtkApplication.java:126)
at com.sun.glass.ui.gtk.GtkApplication$$Lambda$42/379110473.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>I guess, that I took the <code>USE_COMPUTED_SIZE</code> value from the wrong class or something, but where do I get the correct value from? Or is this whole approach somehow wrong?</p>
<p>My ultimate goal is to make the stage take as much space as is needed to display all the controls and containers in it, but not more.</p>
<p>EDIT#1:
Correction: It should take as much space as needed as a <em>Minimum</em> width and height, so that the window is still resizeable but cannot be made so small that controls are not displayed any more.</p>
<p>EDIT#2:
Result of trying to set the minimum width + height on a smaller example app:
<img src="https://i.stack.imgur.com/ImbIH.png" alt="enter image description here"></p>
<p>Code:</p>
<pre><code>package javafxapplication3;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.paint.RadialGradientBuilder;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
public class GridPaneExample extends Application {
private final Paint background = RadialGradientBuilder.create()
.stops(new Stop(0d, Color.TURQUOISE), new Stop(1, Color.web("3A5998")))
.centerX(0.5d).centerY(0.5d).build();
@Override
public void start(Stage primaryStage) {
GridPane root = new GridPane();
root.setPadding(new Insets(5));
root.setHgap(2);
root.setVgap(2);
root.setAlignment(Pos.CENTER);
final TextField tex = new TextField();
tex.setPrefWidth(250);
tex.setPrefHeight(50);
tex.setPromptText("Press the buttons to Display text here");
tex.setFocusTraversable(false);
GridPane.setColumnSpan(tex, 7);
GridPane.setRowSpan(tex, 2);
root.add(tex, 0, 0);
GridPane.setHalignment(tex, HPos.CENTER);
final Button[][] btn = new Button[5][5];
char ch = 'A';
for ( int i = 0; i < btn.length; i++) {
for ( int j = 0; j < btn.length; j++) {
btn[i][j] = new Button("" + ch);
btn[i][j].setPrefSize(50, 50);
root.add(btn[i][j], j, i+2);
ch++;
btn[i][j].setOnMouseClicked((mouseEvent) -> {
Button b = (Button) mouseEvent.getSource();
tex.appendText(b.getText());
});
}
}
Scene scene = new Scene(root,background);
primaryStage.setTitle("Grid Pane Example");
primaryStage.setScene(scene);
primaryStage.setWidth(Control.USE_COMPUTED_SIZE);
primaryStage.setHeight(Control.USE_COMPUTED_SIZE);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
| 0 | 3,258 |
Connect remotely to an H2 Database using a Java Application
|
<p>I'm having the following problem:
When I try to createTcpServer with my external IP address (the PC's IP and not my local IP = the one we see as an output after running ipconfig in cmd.exe) the following error occurs:</p>
<p>Error with Server: Exception opening port "9092" (port may be in use), cause: "java.net.BindException: Cannot assign requested address: JVM_Bind" [90061-169]</p>
<p>However, the port is not in use. I've checked that using netstat -a -n .
I have enabled my external IP and I have disabled the firewall from the router. My external IP can now be pinged.</p>
<p>Please help me.</p>
<p>Update: Here is my code to start the tcp server.</p>
<pre><code>package businessApp;
import org.h2.tools.Server; //imports the server utility
public class startTcpServerForH2 {
Server server; //the server's instance variable
private static final String SERVER_IP = "192.168.1.101"; //fixed IP of the server
private static final String SERVER_PORT = "9092"; //fixed port the server is listening to
public void tcpServer() { //method responsible to create the tcp server
optionPane optPane = new optionPane(); //option pane for debugging purposes, shows the server's status
try { //catches any server related errors, if the connection is broken etc.
//server uses the IP and port defined earlier, allows other computers in the LAN to connect and implements the secure socket layer (SSL) feature
server = Server.createTcpServer( //create tcp server
new String[] { "-tcpPort" , SERVER_PORT , "-tcpAllowOthers" , "-tcpSSL" }).start();
System.out.println(server.getStatus()); //prints out the server's status
optPane.checkServerStatus(server.getStatus()); //prints out the server's status on the option pane as well
} catch(Exception ex){
System.out.println("Error with Server: " + ex.getMessage());
}
}
public static void main(String[] args){
startTcpServerForH2 tcpServ = new startTcpServerForH2(); //create a new server object
tcpServ.tcpServer(); //starts the tcp server
}
}
</code></pre>
<p>Second Update: here is the h2Connection code.</p>
<p>package businessApp;</p>
<p>import java.sql.*; //imports sql features</p>
<p>//Class responsible for connection with H2 Database Engine
public class h2Connection {</p>
<pre><code>Connection conn; //connection variable
DatabaseMetaData dbmd; /** Metadata variable which include methods such as the following:
* 1) Database Product Name
* 2) Database Product Version
* 3) URL where the database files are located (in TCP mode)
*/
Statement stm; //statements variable
ResultSet rst; //result sets variable
private static final String SERVER_IP = "..."; //here I enter my WAN_IP
private static final String SERVER_PORT = "9092";
public Connection connectionToH2(Connection connt) {
optionPane optPane = new optionPane(); //create new option pane object
String outputConn = null; //declare & initialize string which will hold important messages
try {
Class.forName("org.h2.Driver"); //Driver's name
/** The String URL is pertained of the following:
* 1) jdbc which java implements so that it can take advantage of the SQL features
* 2) Which Database Engine will be used
* 3) URL where the files will be stored (as this is a TCP connection)
* 4) Schema: businessApp
* 5) Auto server is true means that other computers can connect with the same databse at any time
* 6) Port number of the server is also defined
*/
String url = "jdbc:h2:tcp://" + SERVER_IP + ":" + SERVER_PORT + "/C:/Databases/businessApp;IFEXISTS=TRUE";
System.out.println(url); //prints out the url the database files are located as well as the h2 features used (SSL)
connt = DriverManager.getConnection(url, "sa", ""); //Driver Manager defines the username & password of the database
System.out.println(connt.getCatalog()); //prints out the database schema
optPane.checkServerStatus(connt.getCatalog()); //prints out the database schema on the option pane as well
connt.setAutoCommit(false); //set AutoCommit to false to control commit actions manually
//outputs H2 version and the URL of the database files which H2 is reading from, for confirmation
dbmd = connt.getMetaData(); //get MetaData to confirm connection
outputConn = "Connection to "+dbmd.getDatabaseProductName()+" "+
dbmd.getDatabaseProductVersion()+ " with the URL " + dbmd.getURL()+" was successful.\n";
System.out.println(outputConn); //outputs the message on the system (NetBeans compiler)
optPane.checkH2Connection(outputConn); //outputs the message on top of the frame
} catch (ClassNotFoundException ex){ //In case there is an error for creating the class for the Driver to be used
System.out.println("Error creating class: " + ex.getMessage());
} catch(SQLException ex){ //Any error associated with the Database Engine
System.out.println("SQL error: " + ex.getMessage());
optPane.checkServerStatus("SQL error: " + ex.getMessage());
}
return connt; //As the method is not void, a connection variable must be returned
}
</code></pre>
<p>}</p>
<p>When I want to connect to the h2 database, I make a new h2Connection object and use it to connect. I have followed the H2 manual word by word. What more do you need?</p>
| 0 | 1,916 |
The server response was: 5.7.0 Authentication Required. Learn more at
|
<p>I tried to run this code and it shows this error.This is reset password where user is required to insert the email address. When the email address is valid, the admin will send the link to the user to do resetting password. <a href="https://i.stack.imgur.com/E7i3x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/E7i3x.png" alt="enter image description here"></a></p>
<pre><code> protected void btnResetPwd_Click(object sender, EventArgs e)
{
string emailAddress = txtEmail.Text;
User u = db.Users.Single(x => x.EmailAddress == emailAddress);
if (u != null)
{
lblMessage.ForeColor = System.Drawing.Color.LimeGreen;
MailMessage mailMessage = new MailMessage();
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("Dear " + u.Name + ",<br/><br/>");
sbEmailBody.Append("Please click on the following link to reset your password");
sbEmailBody.Append("<br/>"); sbEmailBody.Append("http://localhost/Assignment/Registration/ChangePwd.aspx?uid=" +u.Id);
sbEmailBody.Append("<br/><br/>");
sbEmailBody.Append("<b>Pragim Technologies</b>");
mailMessage.IsBodyHtml = true;
mailMessage.Body = sbEmailBody.ToString();
mailMessage.Subject = "Reset Your Password";
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "YourEmail@gmail.com",
Password = "YourPassword"
};
string to = u.EmailAddress;
string from = "potato@gmail.com";
smtpClient.EnableSsl = true;
mailMessage.From = new MailAddress(from);
mailMessage.To.Add(to);
smtpClient.Send(mailMessage);
smtpClient.UseDefaultCredentials = false;
lblMessage.Text = "An email with instructions to reset your password is sent to your registered email";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Email Address not found!";
}
}
</code></pre>
<p>And this is my web.config</p>
<pre><code> <system.net>
<mailSettings>
<smtp from="Admin &lt;potato@gmail.com&gt;">
<network host="smt.gmail.com"
port="587"
enableSsl="true"
userName="potato@gmail.com"
password="password"/>
</smtp>
</mailSettings>
</system.net>
</code></pre>
| 0 | 1,286 |
How to fix: Data path "" should have required property 'browserTarget' error in Angular 8 when running ng serve or npm start
|
<p>I'm trying to run either 'ng serve' or 'npm start' to run my angular 8 server on localhost:4200 in cmd on a windows machine. I get a Schema error I think I know where the problem is but no idea how to fix it.</p>
<p>Another point to note is this was working perfectly fine until windows restarted my computer to do an update.</p>
<p>I'm also running tailwind through a webpack.</p>
<p>The main part of the error is: Data path "" should have required property 'browserTarget'</p>
<pre><code>"serve": {
"builder": "@angular-builders/custom-webpack:dev-server",
"options": {
"customWebpackConfig": {
"path": "./webpack.config.js"
}
}
},
</code></pre>
<p>I assume I need to add browserTarget in the options here, when I do that I get an error saying I need main in there too.</p>
<p>Am I on the right track?
If I am, what are the values that should be attributed to these properties?</p>
<p>Any help would be greatly appreciated. </p>
<p>I've tried:</p>
<ul>
<li><p>Upgrading my packages.</p></li>
<li><p>Upgrading Angular</p></li>
<li><p>Deleting the node modules folder and npm installing</p></li>
</ul>
<p>angular.json:</p>
<pre><code>
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"bjjcastle": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.config.js"
}
}
},
"serve": {
"builder": "@angular-builders/custom-webpack:dev-server",
"options": {
"customWebpackConfig": {
"path": "./webpack.config.js"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "bjjcastle:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss",
"node_modules/font-awesome/scss/font-awesome.scss"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "bjjcastle:serve"
},
"configurations": {
"production": {
"devServerTarget": "bjjcastle:serve:production"
}
}
}
}
}},
"defaultProject": "bjjcastle"
}
</code></pre>
<p>package.json:</p>
<pre><code>
{
"name": "bjjcastle",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~8.2.2",
"@angular/common": "~8.2.2",
"@angular/compiler": "~8.2.2",
"@angular/core": "~8.2.2",
"@angular/forms": "~8.2.2",
"@angular/platform-browser": "~8.2.2",
"@angular/platform-browser-dynamic": "~8.2.2",
"@angular/router": "~8.2.2",
"@fortawesome/angular-fontawesome": "^0.5.0",
"@fortawesome/fontawesome-svg-core": "^1.2.21",
"@fortawesome/free-brands-svg-icons": "^5.10.1",
"@fortawesome/free-solid-svg-icons": "^5.10.1",
"rxjs": "~6.5.2",
"tslib": "^1.10.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-builders/custom-webpack": "^8.1.0",
"@angular-devkit/build-angular": "~0.802.2",
"@angular/cli": "~8.2.2",
"@angular/compiler-cli": "~8.2.2",
"@angular/language-service": "~8.2.2",
"@types/jasmine": "~3.3.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"postcss-import": "^12.0.1",
"postcss-loader": "^3.0.0",
"postcss-scss": "^2.0.0",
"protractor": "~5.4.0",
"tailwindcss": "^1.1.1",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.5.3"
}
}
</code></pre>
<p>webpack.config.js:</p>
<pre><code>
module.exports = {
module : {
rules: [
{
test : /\.scss$/,
loader : 'postcss-loader',
options: {
ident : 'postcss',
syntax: 'postcss-scss',
plugins: () => [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
]
}
}
]
}
};
</code></pre>
<p>The Error I receive:</p>
<pre><code> Schema validation failed with the following errors:
Data path "" should have required property 'browserTarget'.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! bjjcastle@0.0.0 start: `ng serve`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bjjcastle@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional
logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\MyRoute\AppData\Roaming\npm-cache\_logs\2019-08-16T05_27_51_621Z-debug.log
</code></pre>
| 0 | 3,863 |
Execute a string of PHP code on the command line
|
<p>I'd like to be able to run a line of PHP code on the command line similar to how the following options work:</p>
<pre><code>perl -e "print 'hi';"
python -c "print 'hi'"
ruby -e "puts 'hi'"
</code></pre>
<p>I'd like to be able to do:</p>
<pre><code>php "echo 'hi';"
</code></pre>
<p>I've read that there is a <code>-r</code> option that can do what I need for php, however it doesn't appear to be available when I try to use it. I've tried using PHP 5.2.13 and PHP 4.4.9 and neither have an <code>-r</code> option available.</p>
<p>I wrote this script (that I called run_php.php) - which works, but I'm not a huge fan of it just because I feel like there should be a more "correct" way to do it.</p>
<pre><code>#!/usr/bin/php5 -q
<?php echo eval($argv[1]); ?>
</code></pre>
<p>Is there a <code>-r</code> option? If so, why is it not available when I run <code>--help</code>? If there is no <code>-r</code> option, what is the best way to do this (without writing an intermediary script if possible)?</p>
<hr/>
<p>Because I don't think it was very clear above, the <code>-r</code> option is <em>not</em> available to me. Here is the <code>php -h</code> output for both versions of PHP that I'm running.</p>
<p>PHP 4.4.9</p>
<pre class="lang-none prettyprint-override"><code>Usage: php [-q] [-h] [-s] [-v] [-i] [-f <file>]
php <file> [args...]
-a Run interactively
-C Do not chdir to the script's directory
-c <path>|<file> Look for php.ini file in this directory
-n No php.ini file will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f <file> Parse <file>. Implies `-q'
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-q Quiet-mode. Suppress HTTP Header output.
-s Display colour syntax highlighted source.
-v Version number
-w Display source with stripped comments and whitespace.
-z <file> Load Zend extension <file>.
</code></pre>
<p>PHP 5.2.13</p>
<pre class="lang-none prettyprint-override"><code>Usage: php [-q] [-h] [-s] [-v] [-i] [-f <file>]
php <file> [args...]
-a Run interactively
-C Do not chdir to the script's directory
-c <path>|<file> Look for php.ini file in this directory
-n No php.ini file will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f <file> Parse <file>. Implies `-q'
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-q Quiet-mode. Suppress HTTP Header output.
-s Display colour syntax highlighted source.
-v Version number
-w Display source with stripped comments and whitespace.
-z <file> Load Zend extension <file>.
</code></pre>
<p>There is <em>no</em> -r option. When I try to use the <code>-r</code> option I get:</p>
<blockquote>
<p>Error in argument 1, char 2: option not found r</p>
</blockquote>
<p>Sorry for the confusion.</p>
| 0 | 1,514 |
How to return Observable inside a subscription
|
<p>I want to call http request inside a observable which makes select operation from database. I made two services, <strong>DbService</strong> and <strong>BackendService</strong>. </p>
<p>BackendService makes http post requests and returns response data. In my design BackendService should subscribe to DbService for getting url, after that make http post request then return response data. </p>
<p>BackendService can take url from DbService and try to make http request but couldn't. response data is (Json format)</p>
<pre><code>{"_isScalar":false,"source":{"_isScalar":false},"operator":{}}
</code></pre>
<p>I don't understand what happening here. My services and AppComponent file is below.</p>
<p><strong>There is BackendService</strong></p>
<pre><code>import { Injectable } from "@angular/core";
import { getString, setString } from "application-settings";
import { Headers, Http, Response, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/of';
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";
import "rxjs/add/observable/throw";
import "rxjs/add/operator/catch";
import { DbService } from "./db.service";
@Injectable()
export class BackendService {
static BaseUrl= "http://blabla.com"
constructor(public http: Http, private db: DbService) {
}
sendPost(key: string, requestObj: Object):Observable<any>{
console.log("sendPost: ");
return new Observable(obs=> {
let obs1 = this.db.getActionUrl(key);
obs1.subscribe(value => {
let url = BackendService.BaseUrl + value;
console.log("key: ", key);
console.log("url: ", url);
var h = BackendService.getHeaders();
obs.next(this.http.post(
url,
JSON.stringify(requestObj),
{ headers: h }
).map((res: Response) => res.json()));
// .catch((error: any) => Observable.throw(error.json())));
obs.complete();
}
, error => {
console.error("send post error: "+ error);
obs.error(error);
}
);
});
}
static getHeaders() {
let headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("SESSION-ID", this.sessionId);
// headers.append("Authorization", BackendService.appUserHeader);
return headers;
}
}
</code></pre>
<p><strong>There is DbService</strong></p>
<pre><code>import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/of';
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";
import "rxjs/add/observable/throw";
import "rxjs/add/operator/catch";
import 'rxjs/add/operator/toPromise';
var Sqlite = require("nativescript-sqlite");
@Injectable()
export class DbService {
private tableActions = "actions";
private columnActionName = "name";
private columnActionUrl = "url";
private database: any;
constructor() {
console.log("DbService Constructor");
(new Sqlite("my_app.db")).then(db => {
db.execSQL("CREATE TABLE IF NOT EXISTS " + this.tableActions + " (" + this.columnActionName + " TEXT PRIMARY KEY, " + this.columnActionUrl +" TEXT)").then(id => {
this.database = db;
console.log("DB SERVICE READY");
}, error => {
console.log("CREATE TABLE ERROR", error);
});
}, error => {
console.log("OPEN DB ERROR", error);
});
}
public getActionUrl(key: string):Observable<any>{
return new Observable(observer => {
if (key === "getApiMap") {
observer.next("/getApiMap");
observer.complete();
return;
}
console.log("getActionUrl :" + key);
this.database.all("SELECT * FROM " + this.tableActions).then(
rows => {
console.log(rows);
observer.next(rows[0][this.columnActionUrl]);
observer.complete();
}, error => {
console.log("SELECT ERROR: getActionUrl: ", error);
observer.error(error);
})
});
}
}
</code></pre>
<p><strong>And there is my AppComponent which makes http requests...</strong></p>
<pre><code>//some imports
export class AppComponent {
public resp: Observable<ModelMainGetApiMapRes>;
public constructor(private bs: BackendService, private db: DbService) {
let req = new ModelMainGetApiMapReq()
bs.sendPost("getApiMap", req, false).subscribe(
(res: ModelMainGetApiMapRes) => {
console.log("getapimap response received!");
console.log(JSON.stringify(res));
console.log("apimap version:" + res.api_version);
},
err => {
console.error("error!", err);
}
);
}
//some functions
}
</code></pre>
<p>the console output of app.component is</p>
<pre><code>CONSOLE LOG file:///app/shared/backend.service.js:61:20: sendPost:
CONSOLE LOG file:///app/shared/backend.service.js:66:28: key: getApiMap
CONSOLE LOG file:///app/shared/backend.service.js:67:28: url: http://blabla.com/getApiMap
CONSOLE LOG file:///app/app.component.js:55:36: getapimap response received!
CONSOLE LOG file:///app/app.component.js:56:36: {"_isScalar":false,"source":{"_isScalar":false},"operator":{}}
CONSOLE LOG file:///app/tns_modules/tns-core-modules/profiling/profiling.js:10:16: ANGULAR BOOTSTRAP DONE. 7805.849
CONSOLE ERROR file:///app/tns_modules/@angular/core/bundles/core.umd.js:1486:24: ERROR Error: Uncaught (in promise): TypeError: undefined is not an object (evaluating 'res.api_version')
</code></pre>
| 0 | 2,504 |
Angular JS table with ng-repeat and radio buttons
|
<p>I am trying to make a table using ng-repeat that has a radio button selector at the start of each row. The table looks like this:</p>
<pre><code><table>
<tbody>
<tr ng-repeat="model in modelList">
<td>
<input type="radio" ng-model="model.select"></input>
</td>
<td>{{ model.NDPName }}</td>
<td>{{ model.OEM }}</td>
<td>{{ model.version }}</td>
<td>{{ model.dateAdded }}</td>
<td>{{ model.validUntil }}</td>
</tr>
</tbody>
</table>
</code></pre>
<p>The ng-repeat is taking from a modelList that looks like:</p>
<pre><code> $scope.modelList =
[
{
select: false,
NDPName: "NDP1",
OEM: "CHOAM Inc.",
version: "01",
dateAdded: "Jan 1, 2013",
validUntil: "Jan 1, 2014",
},
{
select: false,
NDPName: "NDP2",
OEM: "Tyrell Corp.",
version: "01",
dateAdded: "Jan 1, 2014",
validUntil: "Jan 1, 2015",
},
{
select: false,
NDPName: "NDP3",
OEM: "Stark Industries",
version: "01",
dateAdded: "Jan 1, 2015",
validUntil: "Jan 1, 2016",
},
{
select: false,
NDPName: "NDP4",
OEM: "Monsters Inc.",
version: "01",
dateAdded: "Jan 1, 2016",
validUntil: "Jan 1, 2017",
},
{
select: false,
NDPName: "NDP5",
OEM: "ACME Corp",
version: "01",
dateAdded: "Jan 1, 2017",
validUntil: "Jan 1, 2018",
}
];
</code></pre>
<p>The problem I am running into is that the radio buttons are not behaving like radio buttons. They are each in a separate scope and will therefore allow multiple rows in the table to be selected. How can I fix this?</p>
| 0 | 1,170 |
Spring Boot deployment - NoClassDefFoundError
|
<p>I'm trying to deploy Spring Boot application. I build a jar file through maven plugins. But I get an error saying:</p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
at com.spring-boot.example.AppConfig.main(AppConfig.java:18)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
</code></pre>
<p>I tried adding additional plugins to the pom.xml file, but none of it worked. Any help will be very appreciated.</p>
<p>This is my pom.xml file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring-boot.example</groupId>
<artifactId>spring-boot-example</artifactId>
<version>0.1</version>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.spring-boot.example.AppConfig</start-class>
<spring.version>4.0.7.RELEASE</spring.version>
<log4j.version>1.2.17</log4j.version>
<jdk.version>1.7</jdk.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
| 0 | 2,086 |
Spark and Java: Exception thrown in awaitResult
|
<p>I am trying to connect a Spark cluster running within a virtual machine with IP <code>10.20.30.50</code> and port <code>7077</code> from within a Java application and run the word count example:</p>
<pre><code>SparkConf conf = new SparkConf().setMaster("spark://10.20.30.50:7077").setAppName("wordCount");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<String> textFile = sc.textFile("hdfs://localhost:8020/README.md");
String result = Long.toString(textFile.count());
JavaRDD<String> words = textFile.flatMap((FlatMapFunction<String, String>) s -> Arrays.asList(s.split(" ")).iterator());
JavaPairRDD<String, Integer> pairs = words.mapToPair((PairFunction<String, String, Integer>) s -> new Tuple2<>(s, 1));
JavaPairRDD<String, Integer> counts = pairs.reduceByKey((Function2<Integer, Integer, Integer>) (a, b) -> a + b);
counts.saveAsTextFile("hdfs://localhost:8020/tmp/output");
sc.stop();
return result;
</code></pre>
<p>The Java application shows the following stack trace:</p>
<pre><code>Running Spark version 2.0.1
Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Changing view acls to: lii5ka
Changing modify acls to: lii5ka
Changing view acls groups to:
Changing modify acls groups to:
SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(lii5ka); groups with view permissions: Set(); users with modify permissions: Set(lii5ka); groups with modify permissions: Set()
Successfully started service 'sparkDriver' on port 61267.
Registering MapOutputTracker
Registering BlockManagerMaster
Created local directory at /private/var/folders/4k/h0sl02993_99bzt0dzv759000000gn/T/blockmgr-51de868d-3ba7-40be-8c53-f881f97ced63
MemoryStore started with capacity 2004.6 MB
Registering OutputCommitCoordinator
Logging initialized @48403ms
jetty-9.2.z-SNAPSHOT
Started o.s.j.s.ServletContextHandler@1316e7ec{/jobs,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@782de006{/jobs/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@2d0353{/jobs/job,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@381e24a0{/jobs/job/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@1c138dc8{/stages,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@b29739c{/stages/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@63f6de31{/stages/stage,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@2a04ddcb{/stages/stage/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@2af9688e{/stages/pool,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@6a0c5bde{/stages/pool/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@3f5e17f8{/storage,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@33b86f5d{/storage/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@5264dcbc{/storage/rdd,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@5a3ebf85{/storage/rdd/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@159082ed{/environment,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@6522c585{/environment/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@115774a1{/executors,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@3e3a3399{/executors/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@2f2c5959{/executors/threadDump,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@5c51afd4{/executors/threadDump/json,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@76893a83{/static,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@19c07930{/,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@54eb0dc0{/api,null,AVAILABLE}
Started o.s.j.s.ServletContextHandler@5953786{/stages/stage/kill,null,AVAILABLE}
Started ServerConnector@2eeb8bd6{HTTP/1.1}{0.0.0.0:4040}
Started @48698ms
Successfully started service 'SparkUI' on port 4040.
Bound SparkUI to 0.0.0.0, and started at http://192.168.0.104:4040
Connecting to master spark://10.20.30.50:7077...
Successfully created connection to /10.20.30.50:7077 after 25 ms (0 ms spent in bootstraps)
Connecting to master spark://10.20.30.50:7077...
Still have 2 requests outstanding when connection from /10.20.30.50:7077 is closed
Failed to connect to master 10.20.30.50:7077
org.apache.spark.SparkException: Exception thrown in awaitResult
at org.apache.spark.rpc.RpcTimeout$$anonfun$1.applyOrElse(RpcTimeout.scala:77) ~[spark-core_2.11-2.0.1.jar:2.0.1]
at org.apache.spark.rpc.RpcTimeout$$anonfun$1.applyOrElse(RpcTimeout.scala:75) ~[spark-core_2.11-2.0.1.jar:2.0.1]
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36) ~[scala-library-2.11.8.jar:na]
at org.apache.spark.rpc.RpcTimeout$$anonfun$addMessageIfTimeout$1.applyOrElse(RpcTimeout.scala:59) ~[spark-core_2.11-2.0.1.jar:2.0.1]
at org.apache.spark.rpc.RpcTimeout$$anonfun$addMessageIfTimeout$1.applyOrElse(RpcTimeout.scala:59) ~[spark-core_2.11-2.0.1.jar:2.0.1]
at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167) ~[scala-library-2.11.8.jar:na]
at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:83) ~[spark-core_2.11-2.0.1.jar:2.0.1]
at org.apache.spark.rpc.RpcEnv.setupEndpointRefByURI(RpcEnv.scala:88) ~[spark-core_2.11-2.0.1.jar:2.0.1]
at org.apache.spark.rpc.RpcEnv.setupEndpointRef(RpcEnv.scala:96) ~[spark-core_2.11-2.0.1.jar:2.0.1]
at org.apache.spark.deploy.client.StandaloneAppClient$ClientEndpoint$$anonfun$tryRegisterAllMasters$1$$anon$1.run(StandaloneAppClient.scala:106) ~[spark-core_2.11-2.0.1.jar:2.0.1]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_102]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_102]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_102]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_102]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_102]
Caused by: java.io.IOException: Connection from /10.20.30.50:7077 closed
at org.apache.spark.network.client.TransportResponseHandler.channelInactive(TransportResponseHandler.java:128) ~[spark-network-common_2.11-2.0.1.jar:2.0.1]
at org.apache.spark.network.server.TransportChannelHandler.channelInactive(TransportChannelHandler.java:109) ~[spark-network-common_2.11-2.0.1.jar:2.0.1]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:208) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:194) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.ChannelInboundHandlerAdapter.channelInactive(ChannelInboundHandlerAdapter.java:75) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.handler.timeout.IdleStateHandler.channelInactive(IdleStateHandler.java:257) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:208) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:194) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.ChannelInboundHandlerAdapter.channelInactive(ChannelInboundHandlerAdapter.java:75) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:208) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:194) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.ChannelInboundHandlerAdapter.channelInactive(ChannelInboundHandlerAdapter.java:75) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at org.apache.spark.network.util.TransportFrameDecoder.channelInactive(TransportFrameDecoder.java:182) ~[spark-network-common_2.11-2.0.1.jar:2.0.1]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:208) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:194) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:828) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.AbstractChannel$AbstractUnsafe$7.run(AbstractChannel.java:621) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:357) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:357) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111) ~[netty-all-4.0.29.Final.jar:4.0.29.Final]
... 1 common frames omitted
</code></pre>
<p>In the Spark Master log on <code>10.20.30.50</code>, I get the following error message:</p>
<pre><code>16/11/05 14:47:20 ERROR OneForOneStrategy: Error while decoding incoming Akka PDU of length: 1298
akka.remote.transport.AkkaProtocolException: Error while decoding incoming Akka PDU of length: 1298
Caused by: akka.remote.transport.PduCodecException: Decoding PDU failed.
at akka.remote.transport.AkkaPduProtobufCodec$.decodePdu(AkkaPduCodec.scala:167)
at akka.remote.transport.ProtocolStateActor.akka$remote$transport$ProtocolStateActor$$decodePdu(AkkaProtocolTransport.scala:580)
at akka.remote.transport.ProtocolStateActor$$anonfun$4.applyOrElse(AkkaProtocolTransport.scala:375)
at akka.remote.transport.ProtocolStateActor$$anonfun$4.applyOrElse(AkkaProtocolTransport.scala:343)
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:33)
at akka.actor.FSM$class.processEvent(FSM.scala:604)
at akka.remote.transport.ProtocolStateActor.processEvent(AkkaProtocolTransport.scala:269)
at akka.actor.FSM$class.akka$actor$FSM$$processMsg(FSM.scala:598)
at akka.actor.FSM$$anonfun$receive$1.applyOrElse(FSM.scala:592)
at akka.actor.Actor$class.aroundReceive(Actor.scala:467)
at akka.remote.transport.ProtocolStateActor.aroundReceive(AkkaProtocolTransport.scala:269)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516)
at akka.actor.ActorCell.invoke(ActorCell.scala:487)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:238)
at akka.dispatch.Mailbox.run(Mailbox.scala:220)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:397)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: com.google.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
at com.google.protobuf.InvalidProtocolBufferException.invalidTag(InvalidProtocolBufferException.java:89)
at com.google.protobuf.CodedInputStream.readTag(CodedInputStream.java:108)
at akka.remote.WireFormats$AkkaProtocolMessage.<init>(WireFormats.java:6643)
at akka.remote.WireFormats$AkkaProtocolMessage.<init>(WireFormats.java:6607)
at akka.remote.WireFormats$AkkaProtocolMessage$1.parsePartialFrom(WireFormats.java:6703)
at akka.remote.WireFormats$AkkaProtocolMessage$1.parsePartialFrom(WireFormats.java:6698)
at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:141)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:176)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:188)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:193)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
at akka.remote.WireFormats$AkkaProtocolMessage.parseFrom(WireFormats.java:6821)
at akka.remote.transport.AkkaPduProtobufCodec$.decodePdu(AkkaPduCodec.scala:168)
... 19 more
</code></pre>
<p><strong>Additional Information</strong></p>
<ul>
<li>The example works fine when I use <code>new SparkConf().setMaster("local")</code> instead</li>
<li>I can connect to the Spark Master with <code>spark-shell --master spark://10.20.30.50:7077</code> on the very same machine</li>
</ul>
| 0 | 5,136 |
Remove node from TreeView
|
<p>I want to create this simple example of javaFX TreeView with context menu which can remove nodes from the tree:</p>
<pre><code>public class TreeViewSample extends Application {
private final Node rootIcon = new ImageView(
new Image(getClass().getResourceAsStream("folder_16.png"))
);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Tree View Sample");
TreeItem<String> rootItem = new TreeItem<String> ("Inbox", rootIcon);
rootItem.setExpanded(true);
for (int i = 1; i < 6; i++) {
TreeItem<String> item = new TreeItem<String> ("Message" + i);
rootItem.getChildren().add(item);
}
TreeView<String> tree = new TreeView<String> (rootItem);
StackPane root = new StackPane();
root.getChildren().add(tree);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
</code></pre>
<p>I tested this context menu to remove right click selected node:</p>
<pre><code>final ContextMenu contextMenu = new ContextMenu();
MenuItem item1 = new MenuItem("About");
item1.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("About");
}
});
MenuItem item2 = new MenuItem("Preferences");
item2.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("Preferences");
}
});
MenuItem item3 = new MenuItem("Remove");
item3.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
DynamicTreeNodeModel c = treeView.getSelectionModel().getSelectedItem().getValue();
boolean remove = treeView.getSelectionModel().getSelectedItem().getChildren().remove(c);
System.out.println("Remove");
}
});
contextMenu.getItems().addAll(item1, item2, item3);
treeView.setContextMenu(contextMenu);
</code></pre>
<p>For some reason the code is not working. Can you help me to fix this issue?</p>
| 0 | 1,098 |
Print Data from database in django
|
<p>I want to display data of two joined tables with a foreign key in django ,i have set it all up but it isn't displaying anything , here are my files:</p>
<p>models.py:</p>
<pre><code>from django.db import models
from django.utils.encoding import smart_unicode
class Course (models.Model):
Course_name=models.CharField(max_length=120,null=False,blank=False)
course_id=models.AutoField(primary_key=True)
course_idtomatch=models.IntegerField(max_length=2)
def __unicode__(self):
return smart_unicode(self.Course_name)
class Subjectsnames(models.Model):
subject_name=models.CharField(max_length=50)
course=models.ForeignKey(Course)
def List item__unicode__(self):
return smart_unicode(self.subject_name)
</code></pre>
<p>views.py:</p>
<pre><code>from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from .models import Subjectsnames
from .models import Course
def Subjects(request):
Subject = Subjectsnames.objects.get(id=id)
subjects_data = {
"subjects_names":Subject
}
print subjects_data
return render_to_response("code.html",subjects_data,context_instance=RequestContext(request))
</code></pre>
<p>code.html:</p>
<pre><code><html>
{% for name in Subjectsnames %}
Name:{{name.subject_name}}
Id:{{name.id}}
{% endfor %}
</html>
</code></pre>
<p>And i have these data in my database:</p>
<p><strong>Subjectsnames:</strong></p>
<pre><code>+----+-----------------+-----------+
| id | subject_name | course_id |
+----+-----------------+-----------+
| 2 | Organic | 1 |
| 3 | inorganic | 1 |
| 4 | thermodynacmics | 2 |
| 5 | vectors | 2 |
| 6 | trigo | 3 |
| 7 | algebra | 3 |
| 8 | relational | 3 |
| 9 | c++ | 4 |
| 10 | c# | 4 |
+----+-----------------+-----------+
</code></pre>
<p><strong>Course:</strong></p>
<pre><code>+-------------+-----------+------------------+
| Course_name | course_id | course_idtomatch |
+-------------+-----------+------------------+
| chemistry | 1 | 1 |
| pyhics | 2 | 2 |
| maths | 3 | 3 |
| computers | 4 | 4 |
+-------------+-----------+------------------+
</code></pre>
<p><strong>Ignore course_idtomatch</strong></p>
<p>As much as i know, i might have done something wrong in for loop in code.html.
If anyone knows please help me in solving it, Thanks in advance .</p>
<p>I have updated my views.py something like this :</p>
<pre><code>from django.conf import settings
settings.configure()
from django.shortcuts import render, render_to_response, RequestContext
from django.db import models
from .models import Course
from .models import Subjectsnames
def Subjects(request):
Subject = Subjectsnames.objects.get(id=id)
subjects_data = {
"subjects_names":Subject
}
print subjects_data
return render_to_response("code.html",subjects_data,context_instance=RequestContext(request))
print Subject
</code></pre>
<p>but now when i run python views.py on terminal i get an error like:</p>
<pre><code>Traceback (most recent call last):
File "views.py", line 7, in <module>
from .models import Course
ValueError: Attempted relative import in non-package
</code></pre>
| 0 | 1,301 |
Merge content of multiple Excel files into one using PowerShell
|
<p>I have multiple Excel files with different names in path. </p>
<p>e.g. <code>C:\Users\XXXX\Downloads\report</code></p>
<p>Each file has a fixed number of columns.</p>
<p>e.g. <code>Date | Downtime | Response</code></p>
<p>I want to create a new Excel file with merge of all Excel data. New column should be added with client name in which i want to enter file name. Then each Excel file data append below one by one.</p>
<p>e.g. <code>Client name | Date | Downtime | Response</code></p>
<p>Below code can able to append all excel data but now need to add Client name column.</p>
<pre><code>$path = "C:\Users\XXXX\Downloads\report"
#Launch Excel, and make it do as its told (supress confirmations)
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False
$Files = Get-ChildItem -Path $path
#Open up a new workbook
$Dest = $Excel.Workbooks.Add()
#Loop through files, opening each, selecting the Used range, and only grabbing the first 5 columns of it. Then find next available row on the destination worksheet and paste the data
ForEach($File in $Files)
{
$Source = $Excel.Workbooks.Open($File.FullName,$true,$true)
If(($Dest.ActiveSheet.UsedRange.Count -eq 1) -and ([String]::IsNullOrEmpty($Dest.ActiveSheet.Range("A1").Value2)))
{
#If there is only 1 used cell and it is blank select A1
[void]$source.ActiveSheet.Range("A1","E$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy()
[void]$Dest.Activate()
[void]$Dest.ActiveSheet.Range("A1").Select()
}
Else
{
#If there is data go to the next empty row and select Column A
[void]$source.ActiveSheet.Range("A2","E$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy()
[void]$Dest.Activate()
[void]$Dest.ActiveSheet.Range("A$(($Dest.ActiveSheet.UsedRange.Rows|Select -last 1).row+1)").Select()
}
[void]$Dest.ActiveSheet.Paste()
$Source.Close()
}
$Dest.SaveAs("$path\Merge.xls")
$Dest.close()
$Excel.Quit()
</code></pre>
<p>Suggest any effective way to do this. Please provide links if available.</p>
<p>Convert XLS to XLSX :</p>
<pre><code>$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
$excel = New-Object -ComObject excel.application
$excel.visible = $true
$folderpath = "C:\Users\xxxx\Downloads\report\*"
$filetype ="*xls"
Get-ChildItem -Path $folderpath -Include $filetype |
ForEach-Object `
{
$path = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
"Converting $path to $filetype..."
$workbook = $excel.workbooks.open($_.fullname)
$workbook.saveas($path, $xlFixedFormat)
$workbook.close()
}
$excel.Quit()
$excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
</code></pre>
| 0 | 1,057 |
Shared x and y axis labels ggplot2 with ggarrange
|
<p>I have a number off ggplot objects created based off dichotomous count data. I have combined them together using ggarrange. In this function, there is an option to create a shared legend, but as far as I can see no way to create shared x and y axis labels. In addition, the spacing of the figures is very weird - there is a huge gap between the two figure columns, and in addition a large amount of vertical space before the shared legend. So in sum I would like to be able to create shared x and y axes and minimise the unnecessary vertical and horizontal space.</p>
<p>I checked out the following threads:
<a href="https://stackoverflow.com/questions/46201091/ggplot2-grid-arrange-shared-legend-share-axis-labels">ggplot2 grid_arrange_shared_legend share axis labels</a></p>
<p><a href="https://stackoverflow.com/questions/39011020/ggplot-align-plots-together-and-add-common-labels-and-legend">ggplot: align plots together and add common labels and legend</a></p>
<p><a href="https://stackoverflow.com/questions/57812266/add-common-axis-titles-with-lines-arrows-for-multiple-plots-in-ggplot">Add common axis titles with lines/arrows for multiple plots in ggplot</a></p>
<p><a href="https://stackoverflow.com/questions/39008773/ggplot-how-to-add-common-x-and-y-labels-to-a-grid-of-plots">ggplot: how to add common x and y labels to a grid of plots</a></p>
<p>But I think what I want to do is quite a bit simpler, and I don't know how to combine ggarrange with facet.grid which was suggested a few times.</p>
<p>I have copied a reproducible example below.</p>
<pre><code>require(tidyverse)
require(ggpubr)
require(reshape2)
condition <- c("a", "a", "a", "b", "b", "b", "c", "c", "c", "c")
binary_1 <- c(0,0,0,0,0,1,1,1,1,1)
binary_2 <- c(1,1,1,1,1,1,0,0,0,0)
binary_3 <- c(0,1,1,1,1,1,1,1,0,0)
binary_4 <- c(1,1,1,0,0,0,0,0,0,0)
df <- data.frame(condition, binary_1, binary_2, binary_3, binary_4)
df
gg_df <- df %>%
mutate(binary_1 = as.factor(binary_1), binary_2 = as.factor(binary_2), binary_3 = as.factor(binary_3), binary_4 = as.factor(binary_4))
gg_melt <- melt(gg_df)
gg_1 <- ggplot(gg_melt, aes(x=condition, fill = binary_1)) +
geom_bar(stat="count") +
scale_fill_manual(values = c("#FDAE61", "#9E0142"), name = "Behaviour Observed", labels = c("0" = "Absent", "1" = "Present")) +
scale_x_discrete(labels = c(a = "Condition A", b = "Condition B", c = "Condition C")) +
xlab("Condition") +
ylab("Number of Participants") +
ggtitle("Binary 1") +
theme(plot.title = element_text(size = 10, face="bold", hjust = 0.5)) +
theme(aspect.ratio = 1) +
theme(legend.title=element_text(size=10, face = "bold"), axis.title = element_text(size=10, face = "bold"), axis.text = element_text(size=10))+
theme(legend.box.just = "center")
gg_2 <- ggplot(gg_melt, aes(x=condition, fill = binary_2)) +
geom_bar(stat="count") +
scale_fill_manual(values = c("#FDAE61", "#9E0142"), name = "Behaviour Observed", labels = c("0" = "Absent", "1" = "Present")) +
scale_x_discrete(labels = c(a = "Condition A", b = "Condition B", c = "Condition C")) +
xlab("Condition") +
ylab("Number of Participants") +
ggtitle("Binary 2") +
theme(plot.title = element_text(size = 10, face="bold", hjust = 0.5)) +
theme(aspect.ratio = 1) +
theme(legend.title=element_text(size=10, face = "bold"), axis.title = element_text(size=10, face = "bold"), axis.text = element_text(size=10))+
theme(legend.box.just = "center")
gg_3 <- ggplot(gg_melt, aes(x=condition, fill = binary_3)) +
geom_bar(stat="count") +
scale_fill_manual(values = c("#FDAE61", "#9E0142"), name = "Behaviour Observed", labels = c("0" = "Absent", "1" = "Present")) +
scale_x_discrete(labels = c(a = "Condition A", b = "Condition B", c = "Condition C")) +
xlab("Condition") +
ylab("Number of Participants") +
ggtitle("Binary 3") +
theme(plot.title = element_text(size = 10, face="bold", hjust = 0.5)) +
theme(aspect.ratio = 1) +
theme(legend.title=element_text(size=10, face = "bold"), axis.title = element_text(size=10, face = "bold"), axis.text = element_text(size=10))+
theme(legend.box.just = "center")
gg_4 <- ggplot(gg_melt, aes(x=condition, fill = binary_4)) +
geom_bar(stat="count") +
scale_fill_manual(values = c("#FDAE61", "#9E0142"), name = "Behaviour Observed", labels = c("0" = "Absent", "1" = "Present")) +
scale_x_discrete(labels = c(a = "Condition A", b = "Condition B", c = "Condition C")) +
xlab("Condition") +
ylab("Number of Participants") +
ggtitle("Binary 4") +
theme(plot.title = element_text(size = 10, face="bold", hjust = 0.5)) +
theme(aspect.ratio = 1) +
theme(legend.title=element_text(size=10, face = "bold"), axis.title = element_text(size=10, face = "bold"), axis.text = element_text(size=10))+
theme(legend.box.just = "center")
figure <- ggarrange(gg_1, gg_2, gg_3, gg_4,
labels = NULL,
ncol = 2, nrow = 4,
common.legend = TRUE, legend = "bottom",
align = "hv",
font.label = list(size = 10, color = "black", face = "bold", family = NULL, position = "top"))
pdf("figure.pdf")
figure
dev.off()
</code></pre>
| 0 | 2,688 |
How to define max_queue_size, workers and use_multiprocessing in keras fit_generator()?
|
<p>I am applying transfer-learning on a pre-trained network using the GPU version of keras. I don't understand how to define the parameters <strong><code>max_queue_size</code></strong>, <strong><code>workers</code></strong>, and <strong><code>use_multiprocessing</code></strong>. If I change these parameters (primarily to speed-up learning), I am unsure whether all data is still seen per epoch.</p>
<p><strong><code>max_queue_size</code></strong>:</p>
<ul>
<li><p>maximum size of the internal training queue which is used to "precache" samples from the generator </p></li>
<li><p><em>Question:</em> Does this refer to how many batches are prepared on CPU? How is it related to <code>workers</code>? How to define it optimally?</p></li>
</ul>
<p><strong><code>workers</code></strong>: </p>
<ul>
<li><p>number of threads generating batches in parallel. Batches are computed in parallel on the CPU and passed on the fly onto the GPU for neural network computations </p></li>
<li><p><em>Question:</em> How do I find out how many batches my CPU can/should generate in parallel?</p></li>
</ul>
<p><strong><code>use_multiprocessing</code></strong>: </p>
<ul>
<li><p>whether to use process-based threading</p></li>
<li><p><em>Question:</em> Do I have to set this parameter to true if I change <code>workers</code>? Does it relate to CPU usage?</p></li>
</ul>
<p><strong>Related questions</strong> can be found here:</p>
<ul>
<li><a href="https://github.com/keras-team/keras/issues/8540" rel="noreferrer">Detailed explanation of model.fit_generator() parameters: queue size, workers and use_multiprocessing</a></li>
<li><p><a href="https://stackoverflow.com/questions/51790943/what-does-worker-mean-in-fit-generator-in-keras">What does worker mean in fit_generator in Keras?</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/36986815/what-is-the-parameter-max-q-size-used-for-in-model-fit-generator/36989864#36989864">What is the parameter “max_q_size” used for in “model.fit_generator”?</a></p></li>
<li><p><a href="https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly" rel="noreferrer">A detailed example of how to use data generators with Keras</a>.</p></li>
</ul>
<p>I am using <code>fit_generator()</code> as follows:</p>
<pre><code> history = model.fit_generator(generator=trainGenerator,
steps_per_epoch=trainGenerator.samples//nBatches, # total number of steps (batches of samples)
epochs=nEpochs, # number of epochs to train the model
verbose=2, # verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch
callbacks=callback, # keras.callbacks.Callback instances to apply during training
validation_data=valGenerator, # generator or tuple on which to evaluate the loss and any model metrics at the end of each epoch
validation_steps=
valGenerator.samples//nBatches, # number of steps (batches of samples) to yield from validation_data generator before stopping at the end of every epoch
class_weight=classWeights, # optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function
max_queue_size=10, # maximum size for the generator queue
workers=1, # maximum number of processes to spin up when using process-based threading
use_multiprocessing=False, # whether to use process-based threading
shuffle=True, # whether to shuffle the order of the batches at the beginning of each epoch
initial_epoch=0)
</code></pre>
<p>The specs of my machine are:</p>
<pre><code>CPU : 2xXeon E5-2260 2.6 GHz
Cores: 10
Graphic card: Titan X, Maxwell, GM200
RAM: 128 GB
HDD: 4TB
SSD: 512 GB
</code></pre>
| 0 | 1,756 |
In ReactJS, why does `setState` behave differently when called synchronously?
|
<p>I am trying to understand the underlying cause for some somewhat "magical" behavior I am seeing that I cannot fully explain, and which is not apparent from reading the ReactJS source code.</p>
<p>When calling the <code>setState</code> method synchronously in response to an <code>onChange</code> event on an input, everything works as expected. The "new" value of the input is already present, and so the DOM is not actually updated. This is highly desirable because it means the cursor will not jump to the end of the input box.</p>
<p>However, when running a component with exactly the same structure but that calls <code>setState</code> <em>asynchronously</em>, the "new" value of the input does not appear to be present, causing ReactJS to actually touch the DOM, which causes the cursor to jump to the end of the input.</p>
<p>Apparently, something is intervening to "reset" the input back to its prior <code>value</code> in the asynchronous case, which it is not doing in the synchronous case. What is this mechanic?</p>
<p><strong>Synchronous Example</strong></p>
<pre class="lang-js prettyprint-override"><code>var synchronouslyUpdatingComponent =
React.createFactory(React.createClass({
getInitialState: function () {
return {value: "Hello"};
},
changeHandler: function (e) {
this.setState({value: e.target.value});
},
render: function () {
var valueToSet = this.state.value;
console.log("Rendering...");
console.log("Setting value:" + valueToSet);
if(this.isMounted()) {
console.log("Current value:" + this.getDOMNode().value);
}
return React.DOM.input({value: valueToSet,
onChange: this.changeHandler});
}
}));
</code></pre>
<p>Note that the code will log in the <code>render</code> method, printing out the current <code>value</code> of the actual DOM node.</p>
<p>When typing an "X" between the two Ls of "Hello", we see the following console output, and the cursor stays where expected:</p>
<pre class="lang-none prettyprint-override"><code>Rendering...
Setting value:HelXlo
Current value:HelXlo
</code></pre>
<p><strong>Asynchronous Example</strong></p>
<pre class="lang-js prettyprint-override"><code>var asynchronouslyUpdatingComponent =
React.createFactory(React.createClass({
getInitialState: function () {
return {value: "Hello"};
},
changeHandler: function (e) {
var component = this;
var value = e.target.value;
window.setTimeout(function() {
component.setState({value: value});
});
},
render: function () {
var valueToSet = this.state.value;
console.log("Rendering...");
console.log("Setting value:" + valueToSet);
if(this.isMounted()) {
console.log("Current value:" + this.getDOMNode().value);
}
return React.DOM.input({value: valueToSet,
onChange: this.changeHandler});
}
}));
</code></pre>
<p>This is precisely the same as the above, except that the call to <code>setState</code> is in a <code>setTimeout</code> callback.</p>
<p>In this case, typing an X between the two Ls yields the following console output, and the cursor jumps to the end of the input:</p>
<pre class="lang-none prettyprint-override"><code>Rendering...
Setting value:HelXlo
Current value:Hello
</code></pre>
<hr>
<p><strong>Why is this?</strong></p>
<p>I understand React's concept of a <a href="http://facebook.github.io/react/docs/forms.html#controlled-components">Controlled Component</a>, and so it makes sense that user changes to the <code>value</code> are ignored. But it looks like the <code>value</code> is in fact changed, and then explicitly reset. </p>
<p>Apparently, calling <code>setState</code> synchronously ensures that it takes effect <em>before</em> the reset, while calling <code>setState</code> at any other time happens <em>after</em> the reset, forcing a re-render.</p>
<p>Is this in fact what's happening?</p>
<p><strong>JS Bin Example</strong></p>
<p><a href="http://jsbin.com/sogunutoyi/1/">http://jsbin.com/sogunutoyi/1/</a></p>
| 0 | 1,427 |
Get footer row cell values of gridview
|
<p>I have a gridview with two textboxes in the footer. What's required is get the textbox values, store it to a datatable and then bind the same to the gridview.
I am unable to get the textbox values. They show up empty (as you can see). Where am I going wrong.</p>
<p><img src="https://i.stack.imgur.com/Mvvvj.jpg" alt="enter image description here"></p>
<p>ASPX:</p>
<pre><code><asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
ShowFooter="true" OnRowDataBound="gv_RowDataBound"
OnRowCommand="gv_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit">
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update"
CommandName="Update"></asp:LinkButton>
&nbsp;<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel"
CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<%#Container.DataItemIndex %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbId" runat="server" Text='<%#Eval("id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtId" runat="server" Text='<%#Eval("id") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtNewId"
SetFocusOnError="true"
ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text='<%#Eval("name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtNewName" SetFocusOnError="true"
ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete"
CommandName="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkInsert" runat="server" Text="Insert"
CommandName="Insert" ></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</code></pre>
<p>CS:</p>
<pre><code>protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable dt = new DataTable();
switch (e.CommandName)
{
case "Insert":
GridViewRow fRow = gv.FooterRow;
dt.Columns.Add("id");
dt.Columns.Add("name");
dt = (DataTable)ViewState["students"];
DataRow dr = dt.NewRow();
dr["id"] = ((TextBox)fRow.FindControl("txtNewId")).Text;
dr["name"] = ((TextBox)fRow.FindControl("txtNewName")).Text;
dt.Rows.Add(dr);
ViewState["students"] = dt;
gv.DataSource = ViewState["students"];
gv.DataBind();
break;
}
}
</code></pre>
<p>The textboxes are txtNewId, txtNewName.</p>
| 0 | 1,930 |
[01000][unixODBC][Driver Manager]Can't open lib '/usr/local/easysoft/oracle/InstantClient112/lib/libsqora.so' : file not found
|
<p>I am trying to acces oracle from linux server. I am using unixODBC.</p>
<p>When i try to acces oracle using isql and i get error that driver manager can't open libsqora.so.12.1.</p>
<p>odbc.ini</p>
<pre><code>[NAME]
Application Attributes = T
Attributes = W
BatchAutocommitMode = IfAllSuccessful
BindAsFLOAT = F
CloseCursor = F
DisableDPM = F
DisableMTS = T
Driver = Oracle 11g ODBC driver
DSN = DSN_NAME
EXECSchemaOpt =
EXECSyntax = T
Failover = T
FailoverDelay = 10
FailoverRetryCount = 10
FetchBufferSize = 64000
ForceWCHAR = F
Lobs = T
Longs = T
MaxLargeData = 0
MetadataIdDefault = F
QueryTimeout = T
ResultSets = T
ServerName = ServerName
SQLGetData extensions = F
Translation DLL =
Translation Option = 0
DisableRULEHint = T
UserID = xxxx
Password=<password>
StatementCache=F
CacheBufferSize=20
UseOCIDescribeAny=F
</code></pre>
<p>odbcinst.ini</p>
<pre><code> [Oracle 11g ODBC driver]
Description=Oracle ODBC driver for Oracle 11g
Driver=/usr/local/easysoft/oracle/InstantClient112/lib/libsqora.so
FileUsage=1
</code></pre>
<p>Then, when i use isql to acces oracle i get the following error:</p>
<pre><code> [root@xxxxx lib]# isql -v NAME
[01000][unixODBC][Driver Manager]Can't open lib '/usr/local/easysoft/oracle/InstantClient112/lib/libsqora.so' : file not found
[ISQL]ERROR: Could not SQLConnect
</code></pre>
<p>I had typo in odbcinst.ini. I have corrected but still same error.</p>
<pre><code> [root@xxxxx tmp]# isql -v NAME
[01000][unixODBC][Driver Manager]Can't open lib '/usr/local/easysoft/oracle/InstantClient112/lib/libsqora.so.11.1' : file not found
[ISQL]ERROR: Could not SQLConnect
[root@xxxxx tmp]# ls -l /usr/local/easysoft/oracle/InstantClient112/lib/libsqora.so.11.1
-rw-r--r-- 1 bin bin 996363 Sep 5 2010 /usr/local/easysoft/oracle/InstantClient112/lib/libsqora.so.11.1
[Oracle 11g ODBC driver]
Description=Oracle ODBC driver for Oracle 11g
Driver=/usr/local/easysoft/oracle/InstantClient112/lib/libsqora.so.11.1
FileUsage=1
</code></pre>
<p>ENV</p>
<pre><code> [root@xxxxx tmp]# env
HOSTNAME=xxxxx
SSH2_TTY=/dev/pts/0
SHELL=/bin/bash
TERM=xterm
HISTSIZE=1000
ODBC_DIR=/usr/local/easysoft/unixODBC
OLDPWD=/usr/local/easysoft
SSH_SESSION_ID=1424
SSH_TTY=/dev/pts/0
LD_LIBRARY_PATH=/usr/local/easysoft/lib:/usr/local/easysoft/unixODBC/lib
A__z="*SHLVL
TNS_ADMIN=/usr/local/easysoft/oracle/InstantClient112/network/
INPUTRC=/etc/inputrc
PWD=/tmp
LANG=en_US.UTF-8
ODBCSYSINI=/etc/
HOME=/root
SHLVL=3
ODBCINI=/etc
LESSOPEN=|/usr/bin/lesspipe.sh %s
ORACLE_HOME=/usr/local/easysoft/oracle/InstantClient112/
G_BROKEN_FILENAMES=1
_=/bin/env
PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/X11R6/bin:/usr/local/easysoft/unixODBC/bin:/opt/oraClient/11.2.0.4/bin
</code></pre>
<p>Fixed original issue with LD_LIBRARY_PATH updates but now it is broken again since I am trying to use the 32bit Oracle client.</p>
<p>Installed 32bit oracle client in directory /opt/oraClient/11.2.0.4_32/.</p>
<p>Modified the odbcinst.ini:</p>
<pre><code>[Oracle 11g ODBC driver]
Description=Oracle ODBC driver for Oracle 11g
#Driver=/usr/local/easysoft/oracle/InstantClient112/lib/libsqora.so.11.1
Driver=/opt/oraClient/11.2.0.4_32/lib/libsqora.so.11.1
FileUsage=1
</code></pre>
<p>Error:</p>
<pre><code>[root@xxxxx lib]# /usr/local/bin/isql -v NAME
[01000][unixODBC] [Driver Manager]Can't open lib '/opt/oraClient/11.2.0.4_32/lib/libsqora.so.11.1' : file not found
[ISQL]ERROR: Could not SQLConnect
</code></pre>
<p>If I need to use the 32bit Oracle client, what am i doing wrong...I know it is something in environmental variables.</p>
<pre><code> [root@xxxxx lib]# file /opt/oraClient/11.2.0.4_32/lib/libsqora.so.11.1
/opt/oraClient/11.2.0.4_32/lib/libsqora.so.11.1: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), not stripped
</code></pre>
<p>I enable trace but am not able to attach document here. I can email.</p>
<p>More debug info:</p>
<pre><code> [root@xxxxx bin]# ldd /opt/oraClient/11.2.0.4_32/lib/libsqora.so.11.1
ldd: warning: you do not have execution permission for `/opt/oraClient/11.2.0.4_32/lib/libsqora.so.11.1'
linux-gate.so.1 => (0xffffe000)
libdl.so.2 => /lib/libdl.so.2 (0xf7f2b000)
libm.so.6 => /lib/libm.so.6 (0xf7f02000)
libpthread.so.0 => /lib/libpthread.so.0 (0xf7ee8000)
libnsl.so.1 => /lib/libnsl.so.1 (0xf7ecf000)
libclntsh.so.11.1 => not found
libodbcinst.so.1 => not found
libc.so.6 => /lib/libc.so.6 (0xf7d71000)
/lib/ld-linux.so.2 (0x00134000)
</code></pre>
<p>I don't get one the "not found" which may be causing some problems:</p>
<pre><code> [root@xxxxx bin]# ls /opt/oraClient/11.2.0.4_32/lib/libclntsh.so.11.1
/opt/oraClient/11.2.0.4_32/lib/libclntsh.so.11.1
</code></pre>
<p>Below is the most recent env output:</p>
<pre><code> [root@xxxxx]# env
HOSTNAME=xxxxx
SSH2_TTY=/dev/pts/0
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
ODBC_DIR=/usr/local/easysoft/unixODBC
SSH_TTY=/dev/pts/0
LD_LIBRARY_PATH=/opt/oraClient/11.2.0.4_32/:/opt/oraClient/11.2.0.4_32/lib/:/usr/local/easysoft/oracle/InstantClient112:/usr/local/easysoft/oracle/InstantClient112/lib/
TNS_ADMIN=/opt/oraClient/11.2.0.4_32/network/
PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/X11R6/bin:/usr/local/easysoft/unixODBC/bin:/opt/oraClient/11.2.0.4_32/bin
INPUTRC=/etc/inputrc
LANG=en_US.UTF-8
ODBCSYSINI=/etc/
SHLVL=4
HOME=/root
ODBCINI=/etc
ORACLE_HOME=/opt/oraClient/11.2.0.4_32/
G_BROKEN_FILENAMES=1
_=/bin/env
</code></pre>
| 0 | 2,490 |
java.lang.IllegalStateException: Not on the main thread
|
<p>I am trying to delete the markers from the Goolge map in the FragmentActivity Map when there is no data available in the table for the makers on the serverside also the data object is empty but I am getting the error below. How can I fix it?</p>
<p><strong>Error:</strong></p>
<pre><code>07-12 20:53:05.697: E/AndroidRuntime(26364): FATAL EXCEPTION: IntentService[IntentService]
07-12 20:53:05.697: E/AndroidRuntime(26364): Process: com.bustracker, PID: 26364
07-12 20:53:05.697: E/AndroidRuntime(26364): java.lang.IllegalStateException: Not on the main thread
07-12 20:53:05.697: E/AndroidRuntime(26364): at com.google.l.a.ce.b(Unknown Source)
07-12 20:53:05.697: E/AndroidRuntime(26364): at com.google.maps.api.android.lib6.d.ct.a(Unknown Source)
07-12 20:53:05.697: E/AndroidRuntime(26364): at com.google.maps.api.android.lib6.d.aq.a(Unknown Source)
07-12 20:53:05.697: E/AndroidRuntime(26364): at com.google.android.gms.maps.model.internal.t.onTransact(SourceFile:51)
07-12 20:53:05.697: E/AndroidRuntime(26364): at android.os.Binder.transact(Binder.java:380)
07-12 20:53:05.697: E/AndroidRuntime(26364): at com.google.android.gms.maps.model.internal.zzi$zza$zza.remove(Unknown Source)
07-12 20:53:05.697: E/AndroidRuntime(26364): at com.google.android.gms.maps.model.Marker.remove(Unknown Source)
07-12 20:53:05.697: E/AndroidRuntime(26364): at com.bustracker.GetLLRD.onHandleIntent(GetLLRD.java:120)
07-12 20:53:05.697: E/AndroidRuntime(26364): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
07-12 20:53:05.697: E/AndroidRuntime(26364): at android.os.Handler.dispatchMessage(Handler.java:102)
07-12 20:53:05.697: E/AndroidRuntime(26364): at android.os.Looper.loop(Looper.java:145)
07-12 20:53:05.697: E/AndroidRuntime(26364): at android.os.HandlerThread.run(HandlerThread.java:61)
</code></pre>
<p><strong>onHandleIntent method in the GetLLRD IntentService class:</strong></p>
<pre><code>protected void onHandleIntent(Intent intent) {
if (data != null && !data.isEmpty()) {
Intent intent1 = new Intent(this, Map.class);
intent1.putExtra("list_data", data);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent1);
} else if (Map.markerMap != null
&& !Map.markerMap.isEmpty()) {
Iterator<HashMap.Entry<Integer, Marker>> it = Map.markerMap
.entrySet().iterator();
while (it.hasNext()) {
HashMap.Entry<Integer, Marker> entery = it
.next();
int key = entery.getKey();
Map.marker = Map.markerMap.get(key);
System.out.println("test marker " + Map.marker );
//Line 120.
Map.marker .remove();
Map.markerMap.remove(key);
// Marker value = entery.getValue();
}
}
</code></pre>
<p><strong>Map fragmentActivity:</strong></p>
<pre><code>public class Map extends FragmentActivity implements OnMapReadyCallback {
GoogleMap map;
static HashMap<Integer, Marker> markerMap = new HashMap<Integer, Marker>();
static Marker marker = null;
...
}
</code></pre>
| 0 | 1,893 |
How to save Scikit-Learn-Keras Model into a Persistence File (pickle/hd5/json/yaml)
|
<p>I have the following code, using <a href="https://github.com/fchollet/keras/blob/master/keras/wrappers/scikit_learn.py">Keras Scikit-Learn Wrapper</a>:</p>
<pre><code>from keras.models import Sequential
from sklearn import datasets
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
from sklearn import preprocessing
import pickle
import numpy as np
import json
def classifier(X, y):
"""
Description of classifier
"""
NOF_ROW, NOF_COL = X.shape
def create_model():
# create model
model = Sequential()
model.add(Dense(12, input_dim=NOF_COL, init='uniform', activation='relu'))
model.add(Dense(6, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# evaluate using 10-fold cross validation
seed = 7
np.random.seed(seed)
model = KerasClassifier(build_fn=create_model, nb_epoch=150, batch_size=10, verbose=0)
return model
def main():
"""
Description of main
"""
iris = datasets.load_iris()
X, y = iris.data, iris.target
X = preprocessing.scale(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
model_tt = classifier(X_train, y_train)
model_tt.fit(X_train,y_train)
#--------------------------------------------------
# This fail
#--------------------------------------------------
filename = 'finalized_model.sav'
pickle.dump(model_tt, open(filename, 'wb'))
# load the model from disk
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)
#--------------------------------------------------
# This also fail
#--------------------------------------------------
# from keras.models import load_model
# model_tt.save('test_model.h5')
#--------------------------------------------------
# This works OK
#--------------------------------------------------
# print model_tt.score(X_test, y_test)
# print model_tt.predict_proba(X_test)
# print model_tt.predict(X_test)
# Output of predict_proba
# 2nd column is the probability that the prediction is 1
# this value is used as final score, which can be used
# with other method as comparison
# [ [ 0.25311464 0.74688536]
# [ 0.84401423 0.15598579]
# [ 0.96047372 0.03952631]
# ...,
# [ 0.25518912 0.74481088]
# [ 0.91467732 0.08532269]
# [ 0.25473493 0.74526507]]
# Output of predict
# [[1]
# [0]
# [0]
# ...,
# [1]
# [0]
# [1]]
if __name__ == '__main__':
main()
</code></pre>
<p>As stated in the code there it fails at this line:</p>
<pre><code>pickle.dump(model_tt, open(filename, 'wb'))
</code></pre>
<p>With this error:</p>
<pre><code>pickle.PicklingError: Can't pickle <function create_model at 0x101c09320>: it's not found as __main__.create_model
</code></pre>
<p>How can I get around it?</p>
| 0 | 1,276 |
Symfony - How to access entity's repository
|
<p>There are several ways that we can access the entity's repository in Symfony2 controllers or services which each has its advantage and disadvantage. First I list them here and then asking if there is any better solution or these are the only options that we have and we should choose one or some based on our preferences. I also want to know if method 5 (which I've started to use it recently) can be good and doesn't break any rule or having any side effects.</p>
<p><strong>Basic Method:</strong> Use entity manager in the controller or Inject it to a service and then accessing any repository that I want. This is the basic way of accessing a Repository in controller or service.</p>
<pre><code>class DummyController
{
public function dummyAction($id)
{
$em = $this->getDoctrine()->getManager();
$em->getRepository('ProductBundle:Product')->loadProduct($id);
}
}
</code></pre>
<p>But there are some problems related to this method. The first problem is that I cannot do Ctrl + click on for example loadProduct function and go directly to its implementation (Unless there is a way that I don't know). The other problem is that I will end up repeating this part of code over and over.</p>
<p><strong>Method 2:</strong> The other method is just to define a getter in my service or controller to access my repository.</p>
<pre><code>class DummyService
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function dummyFunction($id)
{
$this->getProductRepository()->loadProduct($id);
}
/**
* @return \ProductBundle\Entity\Repository\ProductRepository
*/
public function getProductRepository()
{
return $this->em->getRepository('ProductBundle:Product');
}
}
</code></pre>
<p>This method solves the first problem and somehow the second but still, I have
to repeat all getters that I need in my service or controller, also I will have several getters in my services and controllers just for accessing to repositories</p>
<p><strong>Method 3:</strong> Another way is to inject a repository to my service, it is nice especially if we have a good control on our code and we are not involved with other developers who inject the entire Container into your service.</p>
<pre><code>class DummyService
{
protected $productRepository;
public function __construct(ProductRepository $productRepository)
{
$this->productRepository = $productRepository;
}
public function dummyFunction($id)
{
$this->productRepository->loadProduct($id);
}
}
</code></pre>
<p>This method solves the first and second problem, but if my service is big
and it needs to deal with a lot of repositories then it is not a nice idea to
inject for example 10 repository to my service.</p>
<p><strong>Method 4:</strong> Another way is to have a service to wrap all of my repositories and inject this service to other services.</p>
<pre><code>class DummyService
{
protected $repositoryService;
public function __construct(RepositoryService $repositoryService)
{
$this->repositoryService = $repositoryService;
}
public function dummyFunction($id)
{
$this->repositoryService->getProductRepository()->loadProduct($id);
}
}
</code></pre>
<p>RepositoryService:</p>
<pre><code>class RepositoryService
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* @return \ProductBundle\Entity\Repository\ProductRepository
*/
public function getProductRepository()
{
return $this->em->getRepository('ProductBundle:Product');
}
/**
* @return \CmsBundle\Entity\Repository\PageRepository
*/
public function getPageRepository()
{
return $this->em->getRepository('CmsBundle:Page');
}
}
</code></pre>
<p>This method also solves the first and second problem. But RepositoryService can become so big when we have for example 200 entities.</p>
<p><strong>Method 5:</strong> Finally I can define a static method in each entity which returns its repository.</p>
<pre><code>class DummyService
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function dummyFunction($id)
{
Product::getRepository($this->em)->loadProduct($id);
}
}
</code></pre>
<p>My Entity:</p>
<pre><code>/**
* Product
*
* @ORM\Table(name="saman_product")
* @ORM\Entity(repositoryClass="ProductBundle\Entity\ProductRepository")
*/
class Product
{
/**
*
* @param \Doctrine\ORM\EntityManagerInterface $em
* @return \ProductBundle\Entity\ProductRepository
*/
public static function getRepository(EntityManagerInterface $em)
{
return $em->getRepository(__CLASS__);
}
}
</code></pre>
<p>This method solves the first and second problem also I do not need to define a
service to access repositories. I've used it recently and so far its the best method for me. I don’t think this method will break the rule of entities since it's defined in the class scope and also is so thine. But still I am not sure about it and whether or not it has any side effects.</p>
| 0 | 1,764 |
How to stop all the running threads, if one of those throws an Exception?
|
<p>In one of my application I'm using the <code>ExecutorService</code> class to create a fixed thread pool and <code>CountDownLatch</code> to wait for the threads to complete. This is working fine if the process didn't throw any exception . If there is an exception occurred in any of the threads, I need to stop all the running thread and report the error to the main thread. Can any one please help me to solve this? </p>
<p>This is the sample code I'm using for executing multiple threads.</p>
<pre><code> private void executeThreads()
{
int noOfThreads = 10;
ExecutorService executor = Executors.newFixedThreadPool(noOfThreads);
try
{
CountDownLatch latch = new CountDownLatch(noOfThreads);
for(int i=0; i< noOfThreads; i++){
executor.submit(new ThreadExecutor(latch));
}
latch.await();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
executor.shutDown();
}
}
</code></pre>
<p>This is the Executor Class</p>
<pre><code> public class ThreadExecutor implements Callable<String> {
CountDownLatch latch ;
public ThreadExecutor(CountDownLatch latch){
this.latch = latch;
}
@Override
public String call() throws Exception
{
doMyTask(); // process logic goes here!
this.latch.countDown();
return "Success";
}
</code></pre>
<p>=============================================================================</p>
<p>Thank you all :)</p>
<p>I have corrected my class as given below and that is working now.</p>
<pre><code>private void executeThreads()
{
int noOfThreads = 10;
ExecutorService executor = Executors.newFixedThreadPool(noOfThreads);
ArrayList<Future<Object>> futureList = new ArrayList<Future<Object>>(noOfThreads );
try
{
userContext = BSF.getMyContext();
CountDownLatch latch = new CountDownLatch(noOfComponentsToImport);
for(ImportContent artifact:artifactList){
futureList.add(executor.submit(new ThreadExecutor(latch)));
}
latch.await();
for(Future<Object> future : futureList)
{
try
{
future.get();
}
catch(ExecutionException e)
{ //handle it
}
}
}
catch (Exception e) {
//handle it
}
finally
{
executor.shutdown();
try
{
executor.awaitTermination(90000, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
//handle it
}
}
}
</code></pre>
<p>Executor Class :</p>
<pre><code>public class ThreadExecutor implements Callable<String> {
private static volatile boolean isAnyError;
CountDownLatch latch ;
public ThreadExecutor(CountDownLatch latch){
this.latch = latch;
}
@Override
public String call() throws Exception
{
try{
if(!isAnyError)
{
doMyTask(); // process logic goes here!
}
}
catch(Exception e)
{
isAnyError = true ;
throw e;
}
finally
{
this.latch.countDown();
}
return "Success";
}
</code></pre>
| 0 | 1,658 |
Android studio with experimental gradle 0.2.0
|
<p>I am trying to setup a basic ndk build with the latest version of android studio at this moment. Trying to follow <a href="http://tools.android.com/tech-docs/new-build-system/gradle-experimental" rel="nofollow noreferrer">this tutorial</a> </p>
<p><a href="https://i.stack.imgur.com/vU5y0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vU5y0.png" alt="enter image description here"></a></p>
<p>This is my <strong>gradle-wrapper.properties</strong></p>
<pre><code>#Thu Sep 17 14:22:34 CST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-all.zip
</code></pre>
<p>This is the project build.gradle</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle-experimental:0.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>Here is my module's build.gradle</p>
<pre><code>apply plugin: 'com.android.model.application'
model {
android {
compileSdkVersion = 23
buildToolsVersion = "23.0.1"
defaultConfig.with {
applicationId = "me.blubee.testnative_exp"
minSdkVersion = 10
targetSdkVersion = 23
versionCode = 1
versionName = "1.0"
}
buildConfigFields.with {
create() {
type = "int"
name = "VALUE"
value = "1"
}
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles += file('proguard-rules.pro')
}
}
android.productFlavors {
create("flavor1") {
applicationId = 'com.app'
}
}
android.sources {
main {
java {
source {
srcDir 'src'
}
}
}
}
}
}
</code></pre>
<p>my project structure looks like this:</p>
<pre><code>APP
Java/
Java/android.support
Java/com.test.test_experimental
Java/com.test.test_experimental/R
Java/com.test.test_experimental
Java/com.test.test_experimentalBuildConfig
Java/com.test.test_experimental
Java/com.test.test_experimental/MainActivity
tests/
tests/com.test.test_experimental
tests/com.test.test_experimental/ApplicationTest.java
tests/com.test.test_experimental
tests/com.test.test_experimental/BuildConfig.java
resources/
test-resources
gradle/scripts/
</code></pre>
<p>I am getting these errors:</p>
<pre><code>2:51:31 PM Gradle sync started
2:51:34 PM Gradle sync failed: Unable to load class 'com.android.build.gradle.managed.ProductFlavor_Impl'.
Consult IDE log for more details (Help | Show Log)
Error:Unable to load class 'com.android.build.gradle.managed.ProductFlavor_Impl'.
Possible causes for this unexpected error include:<ul><li>Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
<a href="syncProject">Re-download dependencies and sync project (requires network)</a></li><li>The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
<a href="stopGradleDaemons">Stop Gradle build processes (requires restart)</a></li><li>Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.</li></ul>In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.
Brother:TestNative_exp blubee$ ./gradlew clean --stacktrack
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/bb/TestNative_exp/app/build.gradle' line: 10
* What went wrong:
A problem occurred configuring project ':app'.
> Exception thrown while executing model rule: model.android
> Cannot set readonly property: minSdkVersion for class: com.android.build.gradle.managed.ProductFlavor_Impl
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 2.619 secs
</code></pre>
<p><strong>line #10 is: minSdkVersion = 10</strong>
You can see the whole file in the <code>build.gradle</code> that i put above.</p>
<p><strong>edit</strong></p>
<p>As @unbekant pointed out in his comment and the link to <a href="http://tools.android.com/tech-docs/new-build-system/gradle-experimental" rel="nofollow noreferrer">this post</a></p>
<p>The min and target sdk values should be set like this:</p>
<pre><code>minSdkVersion.apiLevel = 15
targetSdkVersion.apiLevel = 22
</code></pre>
<p>I tried that as well, I get this error:</p>
<pre><code>* What went wrong:
A problem occurred configuring project ':app'.
> Exception thrown while executing model rule: model.android
> No such property: buildConfigFields for class: com.android.build.gradle.managed.AndroidConfig
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
</code></pre>
<p>What am I doing wrong?</p>
| 0 | 2,334 |
SASS/CSS: :first-child selector not working
|
<p>I'm trying to style a certain <code><div></code> in my markup with CSS/SASS, and I'm clueless as to why it's not applying the rules. This is my markup:</p>
<pre><code><div class="row addon-header">
<div class="col-sm-3">
// something here
</div>
<div class="col-sm-9">
<h2>Title</h2>
<h6><em>Slogan</em></h6>
<div class="col-xs-1">
// I want to access this
</div>
<div class="col-xs-1"></div>
<div class="col-xs-1"></div>
<div class="col-xs-1"></div>
</div>
</div>
</code></pre>
<p>And this is the SASS I'm trying to use for it:</p>
<pre><code>div.addon-header {
color: white;
> div.col-sm-9 > div.col-xs-1:first-child {
background-color: black;
padding-left: 0px !important;
}
}
</code></pre>
<p>If I remove the <code>:first-child</code> selector in my SASS, it's working, but obvious for every <code><div class="col-xs-1"></code> not just the first one, which is not what I want.</p>
<p>I also tried playing around and doing something like</p>
<pre><code>div.addon-header {
color: white;
> div.col-sm-9 > div.col-xs-1 {
&:first-child {
background-color: black;
padding-left: 0px !important;
}
}
}
</code></pre>
<p>or</p>
<pre><code>div.addon-header {
color: white;
> div.col-sm-9 {
> div.col-xs-1:first-child {
background-color: black;
padding-left: 0px !important;
}
}
}
</code></pre>
<p>or using <code>:nth-child(1)</code> instead. Nothing works. I'm clueless. Somewhere else in my SASS, I have the following:</p>
<pre><code>.tab-content {
>.tab-pane:first-child > form > div.row > div {
// rules here
> div.picture-container {
// rules here
}
}
>.tab-pane {
// rules here
}
>.tab-pane:nth-child(4) > form {
// rules here
}
}
</code></pre>
<p>Which is working just fine. So I really don't get what I'm doing wrong in the first example. Anyone able to help?</p>
| 0 | 1,098 |
Set image maximum file size with validator
|
<p>I am implementing image upload in Yii2 using File Input Widget as shown in <a href="http://demos.krajee.com/widget-details/fileinput" rel="noreferrer">http://demos.krajee.com/widget-details/fileinput</a>. May I know how to set the uploaded file size limit?</p>
<p>I have added: </p>
<pre><code>['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1024],
</code></pre>
<p>inside the model's <code>rules()</code> but it does not seem to work.</p>
<p>Hope someone can advise. Thanks. </p>
<p>In View:</p>
<pre><code><?php $form = ActiveForm::begin(['enableClientValidation' => false, 'options' => [ 'enctype' => 'multipart/form-data']]); ?>
<?php
echo $form->field($model, 'image')->widget(FileInput::classname(), [
'options'=>['accept'=>'image/*', 'multiple'=>true],
'pluginOptions'=>['allowedFileExtensions'=>['jpg', 'jpeg', 'gif','png']]
]);
?>
<?php ActiveForm::end(); ?>
</code></pre>
<p>In Controller:</p>
<pre><code> $model = new IMAGEMODEL();
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/PROJECT/';
if ($model->load(Yii::$app->request->post())) {
// get the uploaded file instance. for multiple file uploads
// the following data will return an array
$image = UploadedFile::getInstance($model, 'image');
// store the source file name
$model->FILENAME = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name
$model->AVATAR = Yii::$app->security->generateRandomString().".{$ext}";
$model->STD_ID=$_POST['IMAGEMODEL']['STD_ID'];
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
$path = Yii::$app->params['uploadPath'] . $model->AVATAR;
if($model->save()){
$image->saveAs($path);
Yii::$app->session->setFlash('success', 'Image uploaded successfully');
return $this->redirect(['view', 'id'=>$id]);
} else {
Yii::$app->session->setFlash('error', 'Fail to save image');
}
}
</code></pre>
<p>In Model:</p>
<pre><code>public function rules()
{
return [
[['STD_ID', 'FILENAME'], 'required'],
[['FILENAME'], 'string'],
[['LAST_UPD_ON'], 'safe'],
[['STD_ID'], 'string', 'max' => 50],
[['LAST_UPDATE_BY'], 'string', 'max' => 150],
[['image', 'FILENAME'], 'safe'],
['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1],
];
}
</code></pre>
| 0 | 1,227 |
Redirect child process's stdin and stdout to pipes
|
<hr>
<p>EDIT:
The solution is </p>
<pre><code> int c1=dup2(pipes[0][1],STDOUT_FILENO);
int c2=dup2(pipes[1][0],STDIN_FILENO);
setvbuf(stdout,NULL,_IONBF,0);
</code></pre>
<p>It is SETVBUF to set stdout to be non-buffered. Even though I was printing the newline character if the destination is not an actual screen, I guess, it becomes buffered. </p>
<hr>
<hr>
<p>EDIT:
When I put <strong>fflush(stdout)</strong> after LINE 1 and <strong>fflush(fout)</strong> after LINE 4 it works as expected. However, it does not work without the <strong>fflush(stdout)</strong> after LINE 1. The problem is that I would not be able to put <strong>fflush</strong> in the program which I am planning to run.</p>
<hr>
<p>I am trying to start another program from my process. I don't have access to its code but I know it uses stdin and stdout for user interaction. I am trying to start that program by creating 2 pipes, fork-ing and redirecting the child's stdin/stdout to the proper pipe ends. The points is that the parent should be able communicate with the child via file descriptors, while its stdin/stdout should be intact. The POPEN syscall only opens unidirectional pipe. The following code almost works. </p>
<p>There are 4 lines marked as LINE 1..4.</p>
<p>LINE 1 is child sending to pipe,
LINE 2 is child receiving from pipe,
LINE 3 is parent sending to pipe,
LINE 4 is parent receiving from pipe,</p>
<p>This is just a toy example to make sure things work. The issue is that is all 4 lines LINE1..4 are uncommented the output I see on the terminal is </p>
<pre><code>PARENT1: -1
FD: 1 0 4 5 0 1
DEBUG1: 0
DEBUG2: 0
</code></pre>
<p>While if LINE 1 and LINE 3 are uncommented only I see a continuous stream of data. Same happens if if only LINE 2 and LINE 4 are uncommented. However, I want a full bidirectional communication. Also adding the commented SLEEP does not change the behavior. </p>
<p>What could be the issue here. I wonder why is there no bidirectional POPEN.</p>
<pre><code>int pid;
int pipes[2][2];
pipe(pipes[0]);
pipe(pipes[1]);
pid=fork();
if(pid==0)
{
//usleep(1000000);
close(pipes[0][0]);
close(pipes[1][1]);
int c1=dup2(pipes[0][1],STDOUT_FILENO);
int c2=dup2(pipes[1][0],STDIN_FILENO);
//int c2=dup2(STDIN_FILENO,pipes[1][0]);
fprintf(stderr,"FD: %d %d %d %d %d %d\n",c1,c2,pipes[0][1],pipes[1][0],STDIN_FILENO,STDOUT_FILENO);
//FILE*fout=fdopen(pipes[0][1],"w");
//FILE*fin =fdopen(pipes[1][0],"r");
while(1)
{
static int c1=0;
fprintf(stderr,"DEBUG1: %d\n",c1);
printf("%d\n",c1); // LINE 1
fprintf(stderr,"DEBUG2: %d\n",c1);
scanf("%d",&c1); // LINE 2
fprintf(stderr,"DEBUG3: %d\n",c1);
c1++;
}
//fclose(fout);
//fclose(fin);
return 0;
}
close(pipes[0][1]);
close(pipes[1][0]);
char buffer[100];
FILE*fin=fdopen(pipes[0][0],"r");
FILE*fout=fdopen(pipes[1][1],"w");
while(1)
{
int c1=-1;
printf("PARENT1: %d\n",c1);
fscanf(fin,"%d",&c1); // LINE 3
printf("Recv: %d\n",c1);
fprintf(fout,"%d\n",c1+1); // LINE 4
printf("PARENT3: %d\n",c1+1);
}
fclose(fin);
fclose(fout);
</code></pre>
| 0 | 1,331 |
How to download .m3u8 in once time
|
<p>I have a <code>.m3u8</code> file on remote host, with contain fixed numbers of chunk <code>.ts</code> file name, and not stream:</p>
<pre><code>#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:11
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:9.736,
media_0.ts
#EXTINF:9.96,
media_1.ts
#EXTINF:10.0,
media_2.ts
#EXTINF:10.0,
media_3.ts
#EXTINF:10.0,
media_4.ts
#EXTINF:10.2,
media_5.ts
#EXTINF:10.0,
</code></pre>
<p>When I use this command:</p>
<pre><code># ffmpeg -i "http://example.com/chunklist.m3u8" file.mp4
frame= 582 fps=9.4 q=28.0 size= 1536kB time=00:00:23.21 bitrate= 542.1kbits/s dup=2 drop=4 speed=0.375x
</code></pre>
<p>It works. But It get frame by frame video and very long time needed. (It takes time almost to playback the video.)</p>
<p>But since the path of all the <code>.ts</code> files are known. (<a href="http://example.com/media_0.ts" rel="noreferrer">http://example.com/media_0.ts</a>, <a href="http://example.com/media_1.ts" rel="noreferrer">http://example.com/media_1.ts</a>, ...) There must be a way to get and merge them all at the same time.</p>
<p>But How in <a href="http://ffmpeg.org/" rel="noreferrer"><code>ffmpeg</code></a> directly?!</p>
<h3>EDIT (try a solution):</h3>
<p>For one solution, I know how can concatenation files with ffmpeg.</p>
<pre><code>ffmpeg -i "concat:0.ts|1.ts|2.ts|3.ts|4.ts|5.ts" -c copy output.mp4
</code></pre>
<p>This ffmpeg command was great, and works in less 1 sec time!</p>
<p>So try to download all <code>.ts</code> files with CURL with this command:</p>
<pre><code>curl \
http://example.com/media_0.ts -o 0.ts \
http://example.com/media_1.ts -o 1.ts \
http://example.com/media_2.ts -o 2.ts \
http://example.com/media_3.ts -o 3.ts \
http://example.com/media_4.ts -o 4.ts \
http://example.com/media_5.ts -o 5.ts
</code></pre>
<p>But you can see result:</p>
<pre><code> % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 687k 100 687k 0 0 75108 0 0:00:09 0:00:09 --:--:-- 74111
100 652k 100 652k 0 0 59404 0 0:00:11 0:00:11 --:--:-- 53400
100 673k 100 673k 0 0 48675 0 0:00:14 0:00:14 --:--:-- 55781
100 657k 100 657k 0 0 63573 0 0:00:10 0:00:10 --:--:-- 62494
100 671k 100 671k 0 0 39019 0 0:00:17 0:00:17 --:--:-- 40863
100 692k 100 692k 0 0 63480 0 0:00:11 0:00:11 --:--:-- 80049
</code></pre>
<p>See, total download time was 72 sec, while the total duration of all parts is 59 sec! that this time is very long!</p>
<p>So sorry, download all parts and then concat that, was not good solution.</p>
<h3>EDIT 2</h3>
<p>I try for another <code>.m3u8</code> file on the another server with difference URL:</p>
<p>Download and concat together:</p>
<pre><code>ffmpeg -i "concat:\
http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_0.ts|\
http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_1.ts|\
http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_2.ts|\
http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_3.ts|\
http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_4.ts|\
http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_5.ts\
" -c copy -y output.ts
</code></pre>
<p>Another command with <code>input.txt</code> URLs file.</p>
<pre><code>ffmpeg -f "concat" -i "input.txt" -c copy -y output.ts
</code></pre>
<p>input.txt file:</p>
<pre><code>file 'http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_0.ts'
file 'http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_1.ts'
file 'http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_2.ts'
file 'http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_3.ts'
file 'http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_4.ts'
file 'http://184.72.239.149/vod/smil:BigBuckBunny.smil/media_w442897525_b560000_5.ts'
</code></pre>
<p>Or this command some time if needed:</p>
<pre><code>ffmpeg -f "concat" -safe "0" -protocol_whitelist "file,http,https,tcp,tls" -i "input.txt" -c copy -y output.ts
</code></pre>
<p>Finally, for that download speed was good, <strong>MAYBE my server target has limited bandwidth. :-(</strong></p>
| 0 | 2,049 |
Get the current array key inside foreach
|
<p>Ok so, I am building something for my employer for them to input products, they have very specific requirements. I have a form with dynamically generated fields like so...
(obviously not the exact code to follow but the examples are identical conceptually)</p>
<pre><code><input type="text" name="attribute[20]"> inputted value = height
<input type="text" name="attribute[27]"> inputted value = width
</code></pre>
<p>the numbers are generated based on things in the database, so 20 would correlate to "width" 27 would correlate to "height" for example.</p>
<p>So once the user enters the values I need those values to go into a database...or in the test, echo out.</p>
<pre><code>foreach ($_POST['attribute'] as $attributes){
echo key($attributes).' '.$attributes.'<br>';
}
</code></pre>
<p>So that should output...</p>
<pre><code>20 height value<br>
27 width value
</code></pre>
<p>but instead it outputs</p>
<pre><code>&nbsp;height value<br>
&nbsp;width value
</code></pre>
<p>What is going on? I have something similar...but slightly different as the defined numbers can have more than one input....which works perfectly.</p>
<pre><code><input type="text" name="option[][20]"> inputted value = option 1
<input type="text" name="option[][20]"> inputted value = option 2
<input type="text" name="option[][27]"> inputted value = option 1
foreach ($_POST['option'] as $options){
echo key($options).' ';
foreach ($options as $option){
echo $option.'<br>';
}
</code></pre>
<p>which outputs perfectly...</p>
<pre><code>20 option 1<br>
20 option 2<br>
27 option 1
</code></pre>
<p>I don't understand why the more complex one works and the simpler one doesn't, am I missing something obvious? I am aware I have a somewhat unorthodox method of coding in comparison to some, but it is what it is lol. Any help would be greatly appreciated.</p>
<p>EDIT: Var dump as requested</p>
<p>array(22) { ["pID"]=> string(12) "test product" ["pPrice"]=> string(0) "" ["pName"]=> string(0) "" ["pRRP"]=> string(0) "" ["pPostSize"]=> string(0) "" ["pOurPrice"]=> string(0) "" ["pEstDelivery"]=> string(0) "" ["pWeight"]=> string(0) "" ["pEAN"]=> string(0) "" ["pOrder"]=> string(0) "" ["pStock"]=> string(0) "" ["pManufacturer"]=> string(0) "" ["pType"]=> string(13) "Shower Valves" ["pRange"]=> string(0) "" ["cat"]=> array(2) { [0]=> string(2) "72" [1]=> string(2) "23" } ["attribute"]=> array(2) { [<strong><em>0</em></strong>]=> string(5) "<strong><em>width</em></strong>" [1]=> string(6) "height" } ["option"]=> array(3) { [0]=> array(1) { [<strong>11</strong>]=> string(6) "<strong>works1</strong>" } [1]=> array(1) { [<strong>10</strong>]=> string(6) "<strong>works1</strong>" } [2]=> array(1) { [<strong>10</strong>]=> string(6) "<strong>works2</strong>" } } ["pLongdescription"]=> string(0) "" ["meta_description"]=> string(0) "" ["meta_keyword"]=> string(0) "" ["meta_title"]=> string(0) "" ["action"]=> string(6) "create" }</p>
<p>the bold parts, are the parts that successfully come out in my second example. but the bold italic as you can see, returns 0 instead of the 20 that is actually in the form name value.</p>
| 0 | 1,056 |
`TypeError` when calling create(). You may need to make the field read-only, or override the create() method
|
<p>Not sure what's going on here. I'm trying to perform create a new instance via Django-rest-framework. <strong>What am I doing wrong?</strong></p>
<p>There are a few read-only fields being submitted back.
I've tried marking them as read-only via <code>read_only_fields</code> in the serializer, as well as specifying them as <code>editable=False</code> within the model's fields.</p>
<p>Note: I would prefer to avoid specifying my own create method if possible. This should work via standard functionality as documented <a href="http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields" rel="noreferrer">here</a></p>
<p>when POSTing the following:</p>
<pre><code>{
"displayName": "New test",
"backgroundColour": "#4d3567",
"foregroundColour": "#FFFFFF",
"helpText": "test",
"description": "test",
"comment": "test."
}
</code></pre>
<p>i'm getting:</p>
<pre><code>TypeError at /api/v1/classifications/
Got a `TypeError` when calling `ClassificationLabel.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `ClassificationLabel.objects.create()`. You may need to make the field read-only, or override the ClassificationLabelListSerializer.create() method to handle this correctly.
</code></pre>
<p><strong>models.py</strong>:</p>
<pre><code>class ClassificationLabel(models.Model):
"""
this model is used to create all instances of classifications
labels that will be displayed to a user
"""
displayName = models.CharField('Classification label display name', max_length = 32)
helpText = models.TextField('Explanatory text about this label', max_length = 140, blank=True)
backgroundColour = models.CharField('Hex code for background colour including Alpha', max_length=8)
foregroundColour = models.CharField('Hex code for foreground colour include Alpha', max_length=8)
description = models.TextField('Description of this label', max_length = 256, blank=True)
comment = models.TextField('Internal comments for this label', max_length = 1024, blank=True)
lastChanged = models.DateTimeField('last changed timestamp', auto_now=True, editable=False)
identifier = models.CharField('Classification label ID', max_length = 128, blank=True, editable=False)
revision = models.PositiveIntegerField('Revision number for this label', default=1, editable=False)
#placeholder for lastChangedBy
def clean(self):
#the following code generates a unique identifier and checks it for collisions against existing identifiers
if not self.identifier:
stringCheck = False
while stringCheck is False:
newString = str(uuid.uuid4())
newString.replace('-', '')
doesStringExist = ClassificationLabel.objects.filter(identifier=newString).count()
if doesStringExist == 0:
stringCheck = True
self.identifier = newString
def __str__(self):
return self.displayName + " - " + self.identifier
def save(self, force_insert=False, force_update=False):
self.revision += 1
super(ClassificationLabel, self).save(force_insert, force_update) # Call the "real" save() method.
</code></pre>
<p><strong>serializer:</strong></p>
<pre><code>class ClassificationLabelListSerializer(serializers.ModelSerializer):
class Meta:
model = ClassificationLabel
fields = ('displayName', 'helpText', 'identifier', 'backgroundColour', 'foregroundColour', 'comment', 'description', 'lastChanged', 'revision')
#read_only_fields = ('identifier', 'lastChanged', 'revision',)
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>class ClassificationLabelList(mixins.ListModelMixin,generics.GenericAPIView, mixins.CreateModelMixin):
queryset = ClassificationLabel.objects.all()
serializer_class = ClassificationLabelListSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
</code></pre>
<p><strong>what seems to have fixed it</strong>
an updated save() method seems to have fixed this. updated code below:</p>
<pre><code> def save(self, *args, **kwargs):
self.revision += 1
super(ClassificationLabel, self).save() # Call the "real" save() method.
</code></pre>
| 0 | 1,482 |
Notice: Undefined index: ZZZZZZWTF?
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index">PHP: “Notice: Undefined variable” and “Notice: Undefined index”</a> </p>
</blockquote>
<p>All of a sudden my php code has come up with :</p>
<p>Notice: Undefined index: submit in C:\xampp\htdocs\globalautoparts\register.php on line 36</p>
<p>Notice: Undefined index: fullname in C:\xampp\htdocs\globalautoparts\register.php on line 40</p>
<p>Notice: Undefined index: username in C:\xampp\htdocs\globalautoparts\register.php on line 41</p>
<p>Notice: Undefined index: password in C:\xampp\htdocs\globalautoparts\register.php on line 42</p>
<p>Notice: Undefined index: repeatpassword in C:\xampp\htdocs\globalautoparts\register.php on line 43</p>
<p>Notice: Undefined index: email in C:\xampp\htdocs\globalautoparts\register.php on line 45</p>
<p>on the registration page. </p>
<p>How do i fix it?</p>
<p>This is my code:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="author" content="Luka Cvrk (solucija.com)" />
<meta name="keywords" content="conceptnova, concept, framework, web, content, corporate, business" />
<meta name="description" content="Conceptnova" />
<link rel="stylesheet" href="css/main.css" type="text/css" media="screen, projection" />
<title>Global Autoparts | Home</title>
</head>
<body>
<div id="wrap">
<div id="header_top">
<h1 id="logo"><a href="#" title="Conceptnova"><img src="images/logo.gif" align="left" /></a></h1>
<h1 id="logo"></h1>
<ul>
<li><a href="index.php">home</a></li>
<li><a href="aboutus.php">about us</a></li>
<li><a href="services.php">services</a></li>
<li><a href="portfolio.php">portfolio</a></li>
<li><a href="contact.php">contact</a></li>
</ul>
<div id="slogan">
<p></p>
</div>
</div>
<div id="header_bottom">
<h2>Think outside of the box!</h2>
<p>Registering with Global Auto Parts means you have access to super-fast online orders and total user customization, so you wont have to wait in a line again!</p>
</div>
<div id="maincontent">
<div id="left">
<h2><a href="#">Register to become apart of the global community!</a></h2>
<p><?php
echo "<h1>Registration Page.</h1>";
$submit = $_POST['submit'];
//form data
$fullname = strip_tags($_POST['fullname']);
$username = strtolower(strip_tags($_POST['username']));
$password = strip_tags($_POST['password']);
$repeatpassword = strip_tags($_POST['repeatpassword']);
$date = date("Y-m-d");
$email = $_POST['email'];
if ($submit)
{
//open database
$connect = mysql_connect("localhost","root","");
mysql_select_db("phplogin"); //select database
$namecheck = mysql_query("SELECT username FROM users WHERE username='$username'");
$count = mysql_num_rows($namecheck);
if ($count!=0)
{
die("Username already taken! Go <a href='register.php'>back</a> to try again?");
}
// check for existence
if($fullname&&$username&&$password&&$repeatpassword)
{
if ($password==$repeatpassword)
{
//check char length of username and fullname
if (strlen($username)>25||strlen($fullname)>25)
{
echo "Length of username or fullname is too long!";
}
else{
//check password length
if (strlen($password)>25||strlen($password)<6)
{
echo "Password must be between 6 and 25 characters";
}
else{
//register the user!
// encrypt password
$password = md5($password);
$repeatpassword = md5($repeatpassword);
//generate random number for activation process
$random = rand(23456789,98765432);
$queryreg = mysql_query("
INSERT INTO users VALUES ('','$fullname','$username','$password','$email','$date','$random','0')
");
$lastid = mysql_insert_id();
//send activation email
ini_set("SMTP",$server);
$to = $email;
$subject = "Activate your account!";
$headers = "From: Global Auto Parts";
$server = "localhost";
$body = "
Hello $fullname,\n\n
You need to activate your account with the link below:
http://localhost/globalautoparts/activate.php?=$lastid&code=$random \n\n
Thanks.
";
//function to send mail
mail($to, $subject, $body, $headers);
die("You have been registered! Check your email to activate your account!");
}
}
}
else
echo "Your passwords do not match!";
}
else
echo "Please fill in <b>all</a> fields!";
}
?>
<html>
<p>
<form action='register.php' method='POST'>
<table>
<tr>
<td>
Your full name:
</td>
<td>
<input type='text' name='fullname' value='<?php echo $fullname; ?>'>
</td>
</tr>
<tr>
<td>
Choose a username:
</td>
<td>
<input type='text' name='username' value='<?php echo $username; ?>'>
</td>
</tr>
<tr>
<td>
Choose a password:
</td>
<td>
<input type='password' name='password'>
</td>
</tr>
<tr>
<td>
Repeat your password:
</td>
<td>
<input type='password' name='repeatpassword'>
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<input type='text' name='email'>
</td>
</tr>
</table>
<br />
<p>
<input type='submit' name='submit' value='Register'>
</form>
</p>
</div>
<div id="right">
<div id="searchform">
<form method="post" action="#">
<p><input type="text" name="search" class="search" value="Search Keywords" /><input type="submit" value="GO" class="submit" /></p>
</form>
</div>
<p>
<html>
<form action='login.php' method='POST'>
Username: <input type='text' name='username'><br /><br />
Password: &nbsp;<input type='password' name='password'><br /><br />
Click <a href='register.php'>here</a> to register. <input type='Submit' value='Login' id="login">
</form> <p>
</p>
<br />
</div>
</div>
<div id="footer">
<p>&copy; Copyright 2011 <a href="#">Global Autoparts</a>&nbsp;&nbsp;Design: Victor Gatto </p>
</div>
</div>
</body>
</html>
<!--REGBOX-->
</code></pre>
| 0 | 4,724 |
rpmbuild failing error: Installed (but unpackaged) file(s) found:
|
<p>I looked around but none of the answers to this same error message worked in my simple package... I am building the rpm using rpmbuild on Redhat ES 6 and no matter what I have done in my spec file I get the same results. Thank you in advance for your help. </p>
<p>Here is my spec file:</p>
<pre><code>Name: package
Version: 3.2.5
Release: redhat
Summary: Company package gateway pos server
Group: Engineering
License: Company LLC - owned
URL: http://www.company.com
Source: %{name}.tar.gz
%description
The Company package gateway server provides a key component in the Company system architecture which passes information between the clients and the API.
%prep
%setup -n %{name}
%build
%define debug_package %{nil}
%install
mkdir -p $RPM_BUILD_ROOT/srv/package/gateways/config
mkdir -p $RPM_BUILD_ROOT/srv/package/gateways/logs
install -m 700 gateway $RPM_BUILD_ROOT/srv/package/
install -m 700 gatewayclient.conf $RPM_BUILD_ROOT/srv/package/
install -m 700 gateway.conf $RPM_BUILD_ROOT/srv/package/
install -m 700 rules.conf $RPM_BUILD_ROOT/srv/package/
install -m 700 gatewaytest.conf $RPM_BUILD_ROOT/srv/package/
install -m 700 gateways/bci.exe $RPM_BUILD_ROOT/srv/package/gateways/
install -m 700 gateways/config/bci_iso8583.conf $RPM_BUILD_ROOT/srv/package/gateways/config/
%post
%clean
rm -rf %{buildroot}
rm -rf $RPM_BUILD_ROOT
rm -rf %{_tmppath/%{name}
rm -rf %{_topdir}/BUILD%{name}
%files -f %{name}.lang
%defattr(-,root,root,-)
/srv/
/srv/package/
/srv/package/gateways/
/srv/package/gateways/logs/
/srv/package/gateways/config/
/srv/package/gateway
/srv/package/gatewayclient.conf
/srv/package/gateway.conf
/srv/package/gatewaytest.conf
/srv/package/rules.conf
/srv/package/gateways/bci.exe
/srv/package/gateways/config/bci_iso8583.conf
%changelog
* Thurs May 09 2013 Owner
- 1.0 r1 First release
</code></pre>
<p>The error message is here:</p>
<pre><code>Checking for unpackaged file(s): /usr/lib/rpm/check-files /home/rpmbuild/rpmbuild/BUILDROOT/package-3.2.5-redhat.x86_64
error: Installed (but unpackaged) file(s) found:
/srv/package/gateways/bci.exe
/srv/package/gateways/config/bci_iso8583.conf
/srv/package/gateway
/srv/package/gateway.conf
/srv/package/gatewayclient.conf
/srv/package/gatewaytest.conf
/srv/package/rules.conf
RPM build errors:
Installed (but unpackaged) file(s) found:
/srv/package/gateways/bci.exe
/srv/package/gateways/config/bci_iso8583.conf
/srv/package/gateway
/srv/package/gateway.conf
/srv/package/gatewayclient.conf
/srv/package/gatewaytest.conf
/srv/package/rules.conf
</code></pre>
<hr>
<p>Edition - Reran with suggestions below and got these results:</p>
<pre><code>Checking for unpackaged file(s): /usr/lib/rpm/check-files /home/rpmbuild/rpmbuild/BUILDROOT/package-3.2.5-redhat.x86_64
error: Installed (but unpackaged) file(s) found:
/srv/package/gateways/bci.exe
/srv/package/gateways/config/bci_iso8583.conf
/srv/package/gateway
/srv/package/gateway.conf
/srv/package/gatewayclient.conf
/srv/package/gatewaytest.conf
/srv/package/rules.conf
RPM build errors:
Installed (but unpackaged) file(s) found:
/srv/package/gateways/bci.exe
/srv/package/gateways/config/bci_iso8583.conf
/srv/package/gateway
/srv/package/gateway.conf
/srv/package/gatewayclient.conf
/srv/package/gatewaytest.conf
/srv/package/rules.conf
</code></pre>
| 0 | 1,388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.