title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
How to fix "Can't perform a React state update on an unmounted component." error in React Native
|
<p>I'm fetching data in my local database (sqlite) and updating the state, and this error is appearing: </p>
<blockquote>
<p>Can't perform a React state update on an unmounted component. This is a >no-op, but it indicates a memory leak in your application. To fix, >cancel all subscriptions and asynchronous tasks in the >componentWillUnmount method.</p>
</blockquote>
<p>no solution helped me.</p>
<pre><code>
_isMounted = false;
constructor(props) {
super(props);
this.state = {
slug: "",
value: "",
cod_year: "",
months: [],
years: [],
loadingData: true,
};
}
db = openDatabase({ name: 'test.db', createFromLocation : '~my_finances.db'});
getYears = () => {
if(this.state.loadingData){
this.db.transaction((txn)=>{
txn.executeSql(
"SELECT cod, slug FROM year",
[],
(tx, res) => {
if(res.rows.length > 0){
rows = [];
for(let i=0; i<res.rows.length;i++){
rows.push(res.rows.item(i));
}
this.setState({years: rows}, {loadingData: false});
}
}
)
})
}
}
componentDidMount(){
this._isMounted = true;
this.getYears();
}
render() {
const state = this.state;
if(!state.loadingData){
const pickerItens = state.years.map((record, index) => {
<Picker.Item label={record.slug} value={record.cod}/>
})
return (
<View style={{flex: 1}} >
<ScrollView style={styles.container}>
<View style={styles.form_add}>
<Text style={styles.form_slug} > Adicionar </Text>
<TextInput
placeholder="Digite o mês..."
onChangeText={(slug) => { this.setState({slug}) }}
value={this.state.slug}
style={styles.input_add}
/>
<TextInput
placeholder="Digite o valor..."
onChangeText={(value) => { this.setState({value}) }}
value={this.state.value}
style={styles.input_add}
/>
<Picker onValueChange = {(cod_year) => {this.setState({cod_year})}}>
{ pickerItens }
</Picker>
<Button color="#7159C1" title="Salvar" onPress={() => this.addYear()} />
</View>
</ScrollView>
<Footer navigate={this.props.navigation.navigate} />
</View>
);
}else{
<Text> Loading... </Text>
}
}
</code></pre>
| 0 | 1,464 |
SSIS using Script task - Convert XLS to CSV
|
<p>I am using C# script task component to convert XLS to CSV file , my entry point is set to ScriptMain</p>
<p>But I am constantly getting error "Error: Cannot execute script because the script entry point is invalid."</p>
<pre><code>/*
Microsoft SQL Server Integration Services Script Task
Write scripts using Microsoft Visual C# 2008.
The ScriptMain is the entry point class of the script.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Data.OleDb;
namespace ST_1feb807359714c80ae0bdd964110df59.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
/*
The execution engine calls this method when the task executes.
To access the object model, use the Dts property. Connections, variables, events,
and logging features are available as members of the Dts property as shown in the following examples.
To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
To post a log entry, call Dts.Log("This is my log text", 999, null);
To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);
To use the connections collection use something like the following:
ConnectionManager cm = Dts.Connections.Add("OLEDB");
cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";
Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
To open Help, press F1.
*/
static void Main(string[] args)
{
string sourceFile, worksheetName, targetFile;
sourceFile = "C:\\NewFolder\\Sample.xls"; worksheetName = "sheet1"; targetFile = "C:\\NewFolder\\target.csv";
convertExcelToCSV(sourceFile, worksheetName, targetFile);
}
static void convertExcelToCSV(string sourceFile, string worksheetName, string targetFile)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\" Excel.0;HDR=Yes;IMEX=1\"";
OleDbConnection conn = null;
StreamWriter wrtr = null;
OleDbCommand cmd = null;
OleDbDataAdapter da = null;
try
{
conn = new OleDbConnection(strConn);
conn.Open();
cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
cmd.CommandType = CommandType.Text;
wrtr = new StreamWriter(targetFile);
da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
string rowString = "";
for (int y = 0; y < dt.Columns.Count; y++)
{
rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
}
wrtr.WriteLine(rowString);
}
Console.WriteLine();
Console.WriteLine("Done! Your " + sourceFile + " has been converted into " + targetFile + ".");
Console.WriteLine();
}
catch (Exception exc)
{
Console.WriteLine(exc.ToString());
Console.ReadLine();
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
wrtr.Close();
wrtr.Dispose();
}
}
}
}
</code></pre>
| 0 | 1,907 |
How can I implement this POST request using HTTParty?
|
<p>I am having difficulty making a POST request to an API endpoint using Ruby's HTTParty library. The API I'm interacting with is the <a href="https://github.com/gittip/www.gittip.com#api">Gittip API</a> and their endpoint requires authentication. I have been able to successfully make an authenticated GET request using HTTParty.</p>
<p>You can see in the example code:</p>
<pre><code>user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"
# I have included real credentials since the above is merely a test account.
HTTParty.get("https://www.gittip.com/#{user}/tips.json",
{ :basic_auth => { :username => api_key } })
</code></pre>
<p>That request works and returns the following as expected:</p>
<pre><code>[
{
"amount" => "1.00",
"platform" => "gittip",
"username" => "whit537"
},
{
"amount" => "0.25",
"platform" => "gittip",
"username" => "JohnKellyFerguson"
}
]
</code></pre>
<p>However, I have been unable to make a successful POST request using HTTParty. The Gittip API describes making a POST request using curl as follows:</p>
<pre><code>curl https://www.gittip.com/foobar/tips.json \
-u API_KEY: \
-X POST \
-d'[{"username":"bazbuz", "platform":"gittip", "amount": "1.00"}]' \
-H"Content-Type: application/json"
</code></pre>
<p>I have tried (unsuccessfully) structuring my code using HTTParty as follows:</p>
<pre><code>user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"
HTTParty.post("https://www.gittip.com/#{user}/tips.json",
{
:body => [ { "amount" => "0.25", "platform" => "gittip", "username" => "whit537" } ],
:basic_auth => { :username => api_key },
:headers => { 'Content-Type' => 'application/json' }
})
</code></pre>
<p>The first argument is the url and the second argument is an options hash. When I run the code above, I get the following error:</p>
<pre><code>NoMethodError: undefined method `bytesize' for [{"amount"=>"0.25", "platform"=>"gittip", "username"=>"whit537"}]:Array
from /Users/John/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http/generic_request.rb:179:in `send_request_with_body'
</code></pre>
<p>I have tried various other combinations of structuring the API call, but can't figure out how to get it to work. Here's another such example, where I do not user an array as part of the body and convert the contents <code>to_json</code>.</p>
<pre><code>user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"
HTTParty.post("https://www.gittip.com/#{user}/tips.json",
{
:body => { "amount" => "0.25", "platform" => "gittip", "username" => "whit537" }.to_json,
:basic_auth => { :username => api_key },
:headers => { 'Content-Type' => 'application/json' }
})
</code></pre>
<p>Which returns the following (a 500 error):</p>
<pre><code><html>
<head>
<title>500 Internal Server Error</title>
</head>
<body>\n Internal server error, program!\n <pre></pre>
</body>
</html>
</code></pre>
<p>I'm not really familiar with curl, so I'm not sure if I am incorrectly translating things to HTTParty.</p>
<p>Any help would be appreciated. Thanks.</p>
| 0 | 1,428 |
No more post back after file download in sharepoint
|
<p>I tried to download a file from sharepoint.
But after I download this file, I can't click on other buttons.
What is wrong with my coding?</p>
<p><strong>This is my first way.</strong></p>
<blockquote>
<pre><code> Response.AppendHeader("content-disposition", "attachment; filename= " + fileName);
Response.ContentType = "text/plain";
Response.WriteFile(Server.MapPath("~/" + fileName));
Response.End();
</code></pre>
</blockquote>
<p><strong>This is my second way</strong></p>
<blockquote>
<pre><code> byte[] bytes = System.IO.File.ReadAllBytes("D:\\" + fileName);
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "application/octet-stream");
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename= " + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
</code></pre>
</blockquote>
<p>I even comment Response.End() but still the same result.</p>
<p>Is there any other way I should tried?</p>
<p>Any help would be really appreciated.
In fact, I posted this question a few days ago, but only one gave me my second way to try but it is still not working.</p>
<p>Thanks.</p>
<p><strong>UPDATE</strong></p>
<p>Here is my GridView under GridView.</p>
<pre><code> <asp:GridView ID="gvGiro" Width="100%" runat="server" GridLines="Both" AllowPaging="false" CssClass="form-table" ShowHeader="false"
AllowSorting="false" AutoGenerateColumns="false" OnRowDataBound="gvGiro_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-Width="20%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblValueDate" Text='<%# getDate(Eval("ValueDate")) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gvDetail" runat="server" AllowPaging="false" AllowSorting="false"
CssClass="list-table border" HeaderStyle-CssClass="header" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Sequence Number" ItemStyle-HorizontalAlign="Left"
ItemStyle-Width="30%" >
<ItemTemplate>
<%#((DataRowView)Container.DataItem)["MessageSeqNbr"] %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Number of Debit Transaction" ItemStyle-HorizontalAlign="Left"
HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<%#((DataRowView)Container.DataItem)["TotalDebitNbr"] %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="25%"
HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<%#((DataRowView)Container.DataItem)["CodeDesc"] %>
<asp:HiddenField ID="hidCode" runat="server" Value='<%#((DataRowView)Container.DataItem)["Code"] %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%"
HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="btnDownload" runat="server" CssClass="button submit" Text="Download"
CommandName="download" OnCommand="onCmd" CommandArgument='<%#Eval("Id") %>' Width="80px"/>
<asp:Button ID="btnUnbatch" runat="server" CssClass="button generic" Text="Un-Batch"
CommandName="unbatch" OnCommand="onCmd" CommandArgument='<%#Eval("Id") %>' Width="80px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</code></pre>
<p>Here is my cs file</p>
<pre><code> protected void gvGiro_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView gr;
if (e.Row.RowType == DataControlRowType.DataRow)
{
gr = (GridView) e.Row.FindControl("gvDetail");
using (class2 ct2= new Class2())
{
Label lblValueDate = (Label)e.Row.FindControl("lblValueDate");
DateTime dt= DateTime.MinValue;
DataSet ds= ct2.GetData(dt);
gr.DataSource = ds;
gr.DataBind();
}
}
}
protected void onCmd(object sender, CommandEventArgs e)
{
string id;
switch (e.CommandName)
{
case "unbatch":
id= e.CommandArgument.ToString();
Unbatch(id);
break;
case"download":
id= e.CommandArgument.ToString();
Download(id);
break;
default:
break;
}
}
protected void Download(string id)
{
// to do - substitute all hard-code guid
Guid batchId = new Guid(id);
string fileName = "";
Class1 ct = new Class1();
{
if (!ct.FileExists(batchId , ref fileName))
{
byte[] bytes = System.IO.File.ReadAllBytes("D:\\" + fileName);
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "application/octet-stream");
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename= " + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
</code></pre>
| 0 | 3,908 |
MVC 4 Bootstrap Modal Edit \ Detail
|
<p>Hoping someone might be able to help me with something I am experimenting with in MVC 4 using bootstrap.</p>
<p>I have a strongly-typed index view which displays items in a table along with edit and delete action icons in each line.</p>
<pre><code>@model IEnumerable<Models.EquipmentClass>
....
@foreach (var item in Model)
{
<tbody>
<tr>
<td>
@item.ClassId
</td>
<td>
@item.ClassName
</td>
<td>
<a href=@Url.Action("Edit", "EquipmentClass", new { id = item.ClassId })>
<i class="icon-edit"></i>
</a>
<a href=@Url.Action("Delete", "EquipmentClass", new { id = item.ClassId })>
<i class="icon-trash"></i>
</a>
</td>
</tr>
</tbody>
} <!-- foreach -->
</code></pre>
<p>The EquipmentClass controller returns the Edit view for the selected item based on the id. All great and as expected at this point</p>
<pre><code>public ViewResult Edit(int id)
{
return View(equipmentclassRepository.Find(id));
}
</code></pre>
<p>What I would like to know is how to open the edit form in a bootstrap modal dialog.</p>
<p>I could try and substitute the edit action in the table with the following and then have a modal div at the bottom of the view but how do I pass in the ID of the selected item and which html helper should I use in the modal section?</p>
<pre><code><!-- replaced table action -->
<a class="btn pull-right" data-toggle="modal" href="#myModal" >Details</a>
....
<!-- modal div -->
<div class="modal hide fade in" id="myModal" )>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
@Html.Partial("Edit")
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</code></pre>
<p>I'd greatly appreciate any advice, many thanks</p>
| 0 | 1,040 |
Get info by javascript in laravel
|
<p>I'm trying to get specific column from second table by javascript and return data of it to my view but i'm not sure how it can be done.</p>
<h1>Logic</h1>
<ol>
<li>Products table has <code>price</code> column</li>
<li>Discount table has <code>product_id</code>, <code>min</code>, <code>max</code> and <code>amount</code> columns</li>
<li>I input number as quantity, if have product id in my discount table
base on <code>min</code> and <code>max</code> return the <code>amount</code> as new price</li>
</ol>
<h1>Code</h1>
<p>so far this is my codes (I am aware that specially my controller method has identifying issue to find te right data)</p>
<p><code>JavaScript</code></p>
<pre><code><script>
$(document).ready(function() {
// if quantity is not selected (default 1)
$('#newprice').empty();
var quantity = parseInt(document.getElementById("quantity").value);
var shipingcost = parseFloat(quantity);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#newprice').append('Rp '+nf.format(shipingcostnumber)+'');
// if quantity is changed
$('#quantity').on('change', function() {
var quantity = parseInt(document.getElementById("quantity").value);
var qtyminmax = $(this).val();
if(qtyminmax) {
$.ajax({
url: '{{ url('admin/qtydisc') }}/'+encodeURI(qtyminmax),
type: "GET",
dataType: "json",
success:function(data) {
$('#totalPriceInTotal').empty();
var shipingcost = parseFloat(data)+parseFloat(quantity);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('Rp '+nf.format(shipingcostnumber)+'');
}
});
}else{
//when quantity backs to default (1)
$('#newprice').empty();
var quantity = parseInt(document.getElementById("quantity").value);
var shipingcost = parseFloat(quantity);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#newprice').append('Rp '+nf.format(shipingcostnumber)+'');
}
});
});
</script>
</code></pre>
<p><code>Route</code></p>
<pre><code>Route::get('qtydisc/{id}', 'ProductController@qtydisc');
</code></pre>
<p><code>Controller</code></p>
<pre><code>public function qtydisc($id){
return response()->json(QtyDiscount::where('min', '>=', $id)->orWhere('max', '<=', $id)->pluck('min'));
}
</code></pre>
<h1>Question</h1>
<ol>
<li>What should I change in my controller method to get the right data?</li>
<li>What should I change in my JavaScript code? should I add <code>product
ID</code> in my route as well or...?</li>
</ol>
<h1>UPDATE</h1>
<p>I'm trying some changes in my code but I can't get right <code>amount</code></p>
<p><code>controller</code></p>
<pre><code>public function qtydisc($id, $qty){
$price = DB::table('qty_discounts')
->where('product_id', $id)
->where([
['min', '>=', $qty],
['max', '<=', $qty],
])
// ->where('min', '>=', $qty)
// ->where('max', '<=', $qty)
->select('amount')
->first();
return response()->json($price);
}
</code></pre>
<p><code>route</code></p>
<pre><code>Route::get('qtydisc/{id}/{qty}', 'ProductController@qtydisc');
</code></pre>
<p><code>javascript</code></p>
<pre><code>//as before...
$('#quantity').on('change', function() {
var idofproduct = ["{{$product->id}}"]; //added
var quantity = parseInt(document.getElementById("quantity").value);
var qtyminmax = $(this).val();
if(qtyminmax) {
$.ajax({
url: '{{ url('admin/qtydisc') }}/'+idofproduct+'/'+encodeURI(qtyminmax), //changed
type: "GET",
dataType: "json",
success:function(data) {
$('#totalPriceInTotal').empty();
var shipingcost = parseFloat(data)+parseFloat(quantity);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('Rp '+nf.format(shipingcostnumber)+'');
}
});
}else{
//rest of it as before
</code></pre>
<h2>Screenshot</h2>
<p><a href="https://i.stack.imgur.com/qMaWL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qMaWL.png" alt="screenshotdb"></a></p>
<p>that's how my database look like and as results for quantity between <code>2</code> to <code>6</code> i get <code>7000</code> while i have to get <code>5000</code> from <code>2</code> to <code>5</code>.</p>
<p>From number <code>7</code> to <code>9</code> i get no results at all.</p>
<p>From number <code>10</code> to up all i get is <code>7000</code></p>
<p>Any idea?</p>
| 0 | 2,361 |
How to install weblogic maven plugin for weblogic v12.1.2 (12c)?
|
<p>To install weblogic application server I decompressed 2 files I got from or oracle using these links:</p>
<p><a href="http://download.oracle.com/otn/nt/middleware/12c/wls/1212/wls1212_dev.zip" rel="noreferrer">http://download.oracle.com/otn/nt/middleware/12c/wls/1212/wls1212_dev.zip</a>
<a href="http://download.oracle.com/otn/nt/middleware/12c/wls/1212/wls1212_dev_supplemental.zip" rel="noreferrer">http://download.oracle.com/otn/nt/middleware/12c/wls/1212/wls1212_dev_supplemental.zip</a></p>
<p>..found on <a href="http://www.oracle.com/technetwork/middleware/ias/downloads/wls-main-097127.html" rel="noreferrer">this page</a>.</p>
<p>I simply decompressed both files and they automatically decompress to the same folder. setting the <code>MW_HOME</code> and <code>JAVA_HOME</code> environment variables to point to the decompressed folder and Java 7 JDK locations respectively, I ran the <code>configure.cmd</code> file and it ended successfully.</p>
<p>The problem is that I can't reach the same result <a href="http://docs.oracle.com/middleware/1212/wls/WLPRG/maven.htm" rel="noreferrer">this page</a> shows if I follow the instructions on it. I summarized these instructions here:
(<code>ORACLE_HOME</code> is identical to <code>MW_HOME</code>, they both point to the installation folder.)</p>
<pre><code>%ORACLE_HOME%/wlserver/server/bin/setWLSEnv
cd %ORACLE_HOME%/oracle_common/plugins/maven/com/oracle/maven/oracle-maven-sync/12.1.2
mvn install:install-file -DpomFile=oracle-maven-sync.12.1.2.pom -Dfile=oracle-maven-sync.12.1.2.jar
mvn com.oracle.maven:oracle-maven-sync:push -Doracle-maven-sync.oracleHome=D:/oracle_home
mvn help:describe -DgroupId=com.oracle.weblogic -DartifactId=weblogic-maven-plugin -Dversion=12.1.2-0-0
</code></pre>
<p>Where <code>oracle-maven-sync.oracleHome</code> is <code>The path to the Oracle home that you wish to populate the Maven repository from.</code>. Its basically the Weblogic directory having <code>wlserver</code> directory in it.</p>
<p>The problem is that the last line (the line that asks the installed plugin for description), shows the following error message (Ignore the masked IPs, I masked them manually in this question):</p>
<pre><code>[INFO] Scanning for projects...
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-help-plugin:2.2:describe (default-cli) @ standalone-pom ---
[WARNING] The POM for com.oracle.weblogic:weblogic-maven-plugin:jar:12.1.2-0-0 is missing, no dependency information available
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.775 s
[INFO] Finished at: 2014-05-04T13:00:03+02:00
[INFO] Final Memory: 7M/152M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-help-plugin:2.2:describe (default-cli) on project standalone-pom: Plugin does not exist: Plugin could not be found, please check its coordinates fo
typos and ensure the required plugin repositories are defined in the POM
[ERROR] com.oracle.weblogic:weblogic-maven-plugin:maven-plugin:12.1.2-0-0
[ERROR]
[ERROR] from the specified remote repositories:
[ERROR] central (http://x.x.x.x:xxxx/artifactory/plugins-release, releases=true, snapshots=false),
[ERROR] snapshots (http://x.x.x.x:xxxx/artifactory/plugins-snapshot, releases=true, snapshots=true),
[ERROR] central-se (http://x.x.x.x:xxxx/artifactory/plugins-release, releases=true, snapshots=false),
[ERROR] snapshots-se (http://x.x.x.x:xxxx/artifactory/plugins-snapshot, releases=true, snapshots=true)
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code></pre>
<p>What makes me think that this is NOT a network problem, is that I've successfully installed this plugin before, but I can't remember how exactly so may be I'm missing some steps ?</p>
<p>How can I resolve this please ? My goal is to be able to refer to weblogic's libraries from maven as a <strong>dependency</strong> in the following way:</p>
<pre><code><dependency>
<groupId>com.oracle.weblogic</groupId>
<artifactId>weblogic-server-pom</artifactId>
<version>12.1.2-0-0</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
</code></pre>
| 0 | 1,683 |
VS Code Remote SSH Connection not working
|
<p>Im trying to setup vscode with the remote developement extensions on a second pc. While it works on my main one it doesnt on the second one. Tried reinstalling vscode, extensions and using older versions but nothing works.</p>
<p>When trying to connect it cancels after chosing the os. So I cant even type in the password.
I set it up in the exact same way as with the other pc.</p>
<p>Any ideas?</p>
<pre><code>[20:32:53.595] remote-ssh@0.55.0
[20:32:53.595] win32 x64
[20:32:53.596] SSH Resolver called for "ssh-remote+ssh.blabla", attempt 1
[20:32:53.597] SSH Resolver called for host: ssh.blabla
[20:32:53.597] Setting up SSH remote "ssh.blabla"
[20:32:53.610] Using commit id "58bb7b2331731bf72587010e943852e13e6fd3cf" and quality "stable" for server
[20:32:53.612] Install and start server if needed
[20:32:54.639] Checking ssh with "ssh -V"
[20:32:54.686] > OpenSSH_for_Windows_7.7p1, LibreSSL 2.6.5
[20:32:54.691] Running script with connection command: ssh -T -D 52819 ssh.blabla bash
[20:32:54.694] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[20:32:54.758] >
]0;C:\WINDOWS\System32\cmd.exe
[20:32:54.758] Got some output, clearing connection timeout
[20:32:54.785] >
[20:32:55.045] > root@blabla's password:
[20:32:55.045] Showing password prompt
[20:32:57.596] "install" terminal command done
[20:32:57.597] Install terminal quit with output: root@blabla's password:
[20:32:57.597] Received install output: root@blabla's password:
[20:32:57.598] Stopped parsing output early. Remaining text: root@blabla's password:
[20:32:57.598] Failed to parse remote port from server output
[20:32:57.603] Resolver error: Error:
at Function.Create (c:\Users\Manuel.vscode\extensions\ms-vscode-remote.remote-ssh-0.55.0\out\extension.js:1:130564)
at Object.t.handleInstallOutput (c:\Users\Manuel.vscode\extensions\ms-vscode-remote.remote-ssh-0.55.0\out\extension.js:1:127671)
at I (c:\Users\Manuel.vscode\extensions\ms-vscode-remote.remote-ssh-0.55.0\out\extension.js:127:106775)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
at async c:\Users\Manuel.vscode\extensions\ms-vscode-remote.remote-ssh-0.55.0\out\extension.js:127:104774
at async Object.t.withShowDetailsEvent (c:\Users\Manuel.vscode\extensions\ms-vscode-remote.remote-ssh-0.55.0\out\extension.js:127:109845)
at async Object.t.resolve (c:\Users\Manuel.vscode\extensions\ms-vscode-remote.remote-ssh-0.55.0\out\extension.js:127:107960)
at async c:\Users\Manuel.vscode\extensions\ms-vscode-remote.remote-ssh-0.55.0\out\extension.js:127:141955
[20:32:57.606] ------
[20:32:59.376] Password dialog canceled
[20:32:59.376] "install" terminal command canceled```
</code></pre>
| 0 | 1,114 |
Spring security oauth2 and form login configuration
|
<p>My project consists exposes two different parts, a JSF admin panel and a RESTfull service.
I am trying to setup spring security to use different authentication methods depending on the URL the user navigates.</p>
<p>The requirements are</p>
<ul>
<li>Users navigating to the JSF page get a login screen where they authentication using form authentication.</li>
<li>Users navigating to the REST service use OAuth2 implicit authentication with basic authentication for the token granting.</li>
</ul>
<p>The seperate configurations work by themselves, the problem is when I try to combine both of them in one configuration, in that case it seems like the REST provider gets in the way and authenticates each request even if the requests go to the admin url (this is documented from spring security ordering).</p>
<p>My sample configurations are as shown:</p>
<ul>
<li><p>For the form login (JSF)</p>
<pre><code>@Override
@Order(1)
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/templates/**").permitAll()
.antMatchers("/401.html").permitAll()
.antMatchers("/404.html").permitAll()
.antMatchers("/500.html").permitAll()
.antMatchers("/api/**").permitAll()
.antMatchers("/ui/admin.xhtml").hasAnyAuthority("admin", "ADMIN")
.antMatchers("/thymeleaf").hasAnyAuthority("admin", "ADMIN")
//.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/ui/index.xhtml")
.failureUrl("/login?error=1")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.rememberMe()
.and().exceptionHandling().accessDeniedPage("/error/403");
</code></pre></li>
<li><p>OAuth2 security config (REST)</p>
<pre><code>@EnableResourceServer
@Order(2)
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
@Inject
private UserRepository userRepository;
@Inject
private PasswordEncoder passwordEncoder;
@Bean
ApplicationListener<AbstractAuthorizationEvent> loggerBean() {
return new AuthenticationLoggerListener();
}
@Bean
AccessDeniedHandler accessDeniedHandler() {
return new AccessDeniedExceptionHandler();
}
@Bean
AuthenticationEntryPoint entryPointBean() {
return new UnauthorizedEntryPoint();
}
/*Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(
"/resources/**"
, "/templates/**"
, "/login"
, "/logout"
, "/ui/**"
, "/401.html"
, "/404.html"
, "/500.html"
);
}*/
@Override
protected void configure(HttpSecurity http) throws Exception {
ContentNegotiationStrategy contentNegotiationStrategy = http.getSharedObject(ContentNegotiationStrategy.class);
if (contentNegotiationStrategy == null) {
contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
}
MediaTypeRequestMatcher preferredMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy,
MediaType.APPLICATION_FORM_URLENCODED,
MediaType.APPLICATION_JSON,
MediaType.MULTIPART_FORM_DATA);
http.authorizeRequests()
.antMatchers("/ui/**").permitAll()
.and()
.anonymous().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().httpBasic()
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler()) // handle access denied in general (for example comming from @PreAuthorization
.authenticationEntryPoint(entryPointBean()) // handle authentication exceptions for unauthorized calls.
.defaultAuthenticationEntryPointFor(entryPointBean(), preferredMatcher)
.and()
.authorizeRequests()
.antMatchers("/api/**").fullyAuthenticated();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userRepository.findOneByUsername(s);
if (null == user) {
// leave that to be handled by log listener
throw new UsernameNotFoundException("The user with email " + s + " was not found");
}
return (UserDetails) user;
}
}).passwordEncoder(passwordEncoder);
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
return new JwtAccessTokenConverter();
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')").checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).accessTokenConverter(accessTokenConverter());
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("xxx")
.resourceIds(xxx)
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust", "update")
.accessTokenValiditySeconds(xxx)
.refreshTokenValiditySeconds(xxx)
.secret("xxx")
}
}
}
</code></pre></li>
</ul>
<p>These configurations exist on different classes and the ordering is set manually.</p>
<p>Has anyone any solutions to this issue?</p>
<p>Best,</p>
| 0 | 2,837 |
Show splash screen when page loads, but at least for x seconds
|
<p>I have a div with a splashscreen element. This element will be hidden on page load. However, I also want to make sure the splash screen is shown for at least x seconds.</p>
<p>I know this is not all supposed to be formatted as code but the auto formatter made me do it.</p>
<p>To use logic:
Show splash screen for at least x seconds.
If the page is loaded by that time hide this div.</p>
<p>This code is the part where it hides the div as soon as the page is loaded.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
$(document).on("pageload",function(){
$('#splashscreen').hide();
});
</script>
<title>Thomas Shera</title>
</head>
<body>
<div id="splashscreen">
</div>
</body>
</html>
</code></pre>
<p>This is the part where I show the splash screen for x seconds.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
$(function() {
$("#div2").show().delay(x).hide();
});
</script>
<title>Thomas Shera</title>
</head>
<body>
<div id="splashscreen">
</div>
</body>
</html>
</code></pre>
<p>So basically I am asking, how can I combine these two jquery codes?</p>
<p>EDIT: I am now trying this code but something still doesn't work.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
$(document).on("pageload",function(){
$('#splashscreen').hide();
});
$(function() {
$("splashscreen").show().delay(1000).hide();
});
</script>
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Cutive+Mono);
.skills
{
font-family: 'Cultive Mono', monospace;
font-size: 400pt;
}
</style>
<title>Thomas Shera</title>
</head>
<body>
<div id="splashscreen">
<p i="skills">
Javascript Technical writing VBA scripting with Microsoft Office Excel
Entrepreneur
</p>
</div>
</body>
</html>
</code></pre>
| 0 | 1,160 |
undefined reference to `boost::this_thread:
|
<p>I am trying to build to Doge coin headless wallet (similar to bitcoind) it seems to be Boost causing the error but I have no idea on how to fix it.</p>
<p>(Ubuntu 12.04)</p>
<p>When I execute "make -f makefile.unix USE_UPNP=-" I get this error:</p>
<pre><code>/bin/sh ../share/genbuild.sh obj/build.h
g++ -O2 -pthread -Wall -Wextra -Wformat -Wformat-security -Wno-unused-parameter -g -DUSE_IPV6 -DBOOST_SPIRIT_THREADSAFE -I/root/dogecoin/src -I/root/dogecoin/src/obj -DHAVE_BUILD_INFO -fno-stack-protector -fstack-protector-all -Wstack-protector -D_FORTIFY_SOURCE=2 -o dogecoind obj/version.o obj/checkpoints.o obj/netbase.o obj/addrman.o obj/crypter.o obj/key.o obj/db.o obj/init.o obj/irc.o obj/keystore.o obj/main.o obj/net.o obj/protocol.o obj/bitcoinrpc.o obj/rpcdump.o obj/rpcnet.o obj/rpcrawtransaction.o obj/script.o obj/scrypt.o obj/sync.o obj/util.o obj/wallet.o obj/walletdb.o obj/noui.o -Wl,-z,relro -Wl,-z,now -Wl,-Bdynamic -l boost_system -l boost_filesystem -l boost_program_options -l boost_thread -l db_cxx -l ssl -l crypto -Wl,-Bdynamic -l z -l dl -l pthread
obj/db.o: In function `CAddrDB::Write(CAddrMan const&)':
/root/dogecoin/src/db.cpp:764: undefined reference to `RenameOver(boost::filesystem3::path, boost::filesystem3::path)'
obj/init.o: In function `AppInit2()':
/root/dogecoin/src/init.cpp:450: undefined reference to `CreatePidFile(boost::filesystem3::path const&, int)'
obj/main.o: In function `operator/':
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
obj/main.o: In function `sleep':
/usr/local/include/boost/thread/pthread/thread_data.hpp:249: undefined reference to `boost::this_thread::hiden::sleep_until(timespec const&)'
obj/main.o: In function `space':
/usr/local/include/boost/filesystem/operations.hpp:520: undefined reference to `boost::filesystem::detail::space(boost::filesystem::path const&, boost::system::error_code*)'
obj/main.o: In function `sleep':
/usr/local/include/boost/thread/pthread/thread_data.hpp:249: undefined reference to `boost::this_thread::hiden::sleep_until(timespec const&)'
obj/main.o: In function `boost::thread::start_thread()':
/usr/local/include/boost/thread/detail/thread.hpp:180: undefined reference to `boost::thread::start_thread_noexcept()'
obj/bitcoinrpc.o: In function `sleep':
/usr/local/include/boost/thread/pthread/thread_data.hpp:249: undefined reference to `boost::this_thread::hiden::sleep_until(timespec const&)'
obj/bitcoinrpc.o: In function `boost::filesystem::path::has_root_directory() const':
/usr/local/include/boost/filesystem/path.hpp:444: undefined reference to `boost::filesystem::path::root_directory() const'
obj/bitcoinrpc.o: In function `operator/':
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
obj/bitcoinrpc.o: In function `exists':
/usr/local/include/boost/filesystem/operations.hpp:289: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)'
obj/bitcoinrpc.o: In function `boost::filesystem::path::has_root_directory() const':
/usr/local/include/boost/filesystem/path.hpp:444: undefined reference to `boost::filesystem::path::root_directory() const'
obj/bitcoinrpc.o: In function `operator/':
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
obj/bitcoinrpc.o: In function `exists':
/usr/local/include/boost/filesystem/operations.hpp:289: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)'
obj/bitcoinrpc.o: In function `call_once<void (*)()>':
/usr/local/include/boost/thread/pthread/once_atomic.hpp:145: undefined reference to `boost::thread_detail::enter_once_region(boost::once_flag&)'
/usr/local/include/boost/thread/pthread/once_atomic.hpp:157: undefined reference to `boost::thread_detail::commit_once_region(boost::once_flag&)'
/usr/local/include/boost/thread/pthread/once_atomic.hpp:153: undefined reference to `boost::thread_detail::rollback_once_region(boost::once_flag&)'
/usr/local/include/boost/thread/pthread/once_atomic.hpp:145: undefined reference to `boost::thread_detail::enter_once_region(boost::once_flag&)'
/usr/local/include/boost/thread/pthread/once_atomic.hpp:157: undefined reference to `boost::thread_detail::commit_once_region(boost::once_flag&)'
/usr/local/include/boost/thread/pthread/once_atomic.hpp:153: undefined reference to `boost::thread_detail::rollback_once_region(boost::once_flag&)'
obj/util.o: In function `operator/':
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
obj/util.o: In function `path<char*>':
/usr/local/include/boost/filesystem/path.hpp:139: undefined reference to `boost::filesystem::path::codecvt()'
obj/util.o: In function `system_complete':
/usr/local/include/boost/filesystem/operations.hpp:531: undefined reference to `boost::filesystem::detail::system_complete(boost::filesystem::path const&, boost::system::error_code*)'
obj/util.o: In function `is_directory':
/usr/local/include/boost/filesystem/operations.hpp:294: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)'
obj/util.o: In function `create_directory':
/usr/local/include/boost/filesystem/operations.hpp:405: undefined reference to `boost::filesystem::detail::create_directory(boost::filesystem::path const&, boost::system::error_code*)'
obj/util.o: In function `GetDataDir(bool)':
/root/dogecoin/src/util.cpp:1029: undefined reference to `boost::filesystem::path::operator/=(char const*)'
obj/util.o: In function `operator/':
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
obj/util.o: In function `boost::filesystem::path::has_root_directory() const':
/usr/local/include/boost/filesystem/path.hpp:444: undefined reference to `boost::filesystem::path::root_directory() const'
obj/util.o: In function `operator/':
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
obj/util.o: In function `boost::filesystem::path::has_root_directory() const':
/usr/local/include/boost/filesystem/path.hpp:444: undefined reference to `boost::filesystem::path::root_directory() const'
obj/util.o: In function `operator/':
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
obj/walletdb.o: In function `sleep':
/usr/local/include/boost/thread/pthread/thread_data.hpp:249: undefined reference to `boost::this_thread::hiden::sleep_until(timespec const&)'
obj/walletdb.o: In function `operator/':
/usr/local/include/boost/filesystem/path.hpp:648: undefined reference to `boost::filesystem::path::operator/=(boost::filesystem::path const&)'
obj/walletdb.o: In function `is_directory':
/usr/local/include/boost/filesystem/operations.hpp:294: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)'
obj/walletdb.o: In function `copy_file':
/usr/local/include/boost/filesystem/operations.hpp:381: undefined reference to `boost::filesystem::detail::copy_file(boost::filesystem::path const&, boost::filesystem::path const&, boost::filesystem::copy_option::enum_type, boost::system::error_code*)'
obj/walletdb.o: In function `sleep':
/usr/local/include/boost/thread/pthread/thread_data.hpp:249: undefined reference to `boost::this_thread::hiden::sleep_until(timespec const&)'
obj/walletdb.o: In function `operator/=<std::basic_string<char> >':
/usr/local/include/boost/filesystem/path.hpp:302: undefined reference to `boost::filesystem::path::codecvt()'
obj/walletdb.o: In function `boost::filesystem::path& boost::filesystem::path::append<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::codecvt<wchar_t, char, __mbstate_t> const&)':
/usr/local/include/boost/filesystem/path.hpp:707: undefined reference to `boost::filesystem::path::m_append_separator_if_needed()'
/usr/local/include/boost/filesystem/path.hpp:710: undefined reference to `boost::filesystem::path::m_erase_redundant_separator(unsigned long)'
collect2: ld returned 1 exit status
make: *** [dogecoind] Error 1
</code></pre>
| 0 | 3,097 |
Spring Security - Token based API auth & user/password authentication
|
<p>I am trying to create a webapp that will primarily provide a REST API using Spring, and am trying to configure the security side.</p>
<p>I am trying to implement this kind of pattern: <a href="https://developers.google.com/accounts/docs/MobileApps" rel="nofollow noreferrer">https://developers.google.com/accounts/docs/MobileApps</a> (Google have totally changed that page, so no longer makes sense - see the page I was referring to here: <a href="http://web.archive.org/web/20130822184827/https://developers.google.com/accounts/docs/MobileApps" rel="nofollow noreferrer">http://web.archive.org/web/20130822184827/https://developers.google.com/accounts/docs/MobileApps</a>)</p>
<p>Here is what I need to accompish:</p>
<ul>
<li>Web app has simple sign-in/sign-up forms that work with normal spring user/password authentication (have done this type of thing before with dao/authenticationmanager/userdetailsservice etc)</li>
<li>REST api endpoints that are stateless sessions and every request authenticated based ona token provided with the request</li>
</ul>
<p>(e.g. user logins/signs up using normal forms, webapp provides secure cookie with token that can then be used in following API requests)</p>
<p>I had a normal authentication setup as below:</p>
<pre><code>@Override protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/mobile/app/sign-up").permitAll()
.antMatchers("/v1/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/")
.loginProcessingUrl("/loginprocess")
.failureUrl("/?loginFailure=true")
.permitAll();
}
</code></pre>
<p>I was thinking of adding a pre-auth filter, that checks for the token in the request and then sets the security context (would that mean that the normal following authentication would be skipped?), however, beyond the normal user/password I have not done too much with token based security, but based on some other examples I came up with the following:</p>
<p>Security Config:</p>
<pre><code>@Override protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.addFilter(restAuthenticationFilter())
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()).and()
.antMatcher("/v1/**")
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/mobile/app/sign-up").permitAll()
.antMatchers("/v1/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/")
.loginProcessingUrl("/loginprocess")
.failureUrl("/?loginFailure=true")
.permitAll();
}
</code></pre>
<p>My custom rest filter:</p>
<pre><code>public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public RestAuthenticationFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
}
private final String HEADER_SECURITY_TOKEN = "X-Token";
private String token = "";
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
this.token = request.getHeader(HEADER_SECURITY_TOKEN);
//If we have already applied this filter - not sure how that would happen? - then just continue chain
if (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
}
//Now mark request as completing this filter
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
//Attempt to authenticate
Authentication authResult;
authResult = attemptAuthentication(request, response);
if (authResult == null) {
unsuccessfulAuthentication(request, response, new LockedException("Forbidden"));
} else {
successfulAuthentication(request, response, chain, authResult);
}
}
/**
* Attempt to authenticate request - basically just pass over to another method to authenticate request headers
*/
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
AbstractAuthenticationToken userAuthenticationToken = authUserByToken();
if(userAuthenticationToken == null) throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token"));
return userAuthenticationToken;
}
/**
* authenticate the user based on token, mobile app secret & user agent
* @return
*/
private AbstractAuthenticationToken authUserByToken() {
AbstractAuthenticationToken authToken = null;
try {
// TODO - just return null - always fail auth just to test spring setup ok
return null;
} catch (Exception e) {
logger.error("Authenticate user by token error: ", e);
}
return authToken;
}
</code></pre>
<p>The above actually results in an error on app startup saying: <code>authenticationManager must be specified</code>
Can anyone tell me how best to do this - is a pre_auth filter the best way to do this?</p>
<hr>
<p><strong>EDIT</strong></p>
<p>I wrote up what I found and how I did it with Spring-security (including the code) implementing a standard token implementation (not OAuth)</p>
<p><a href="https://automateddeveloper.blogspot.co.uk/2014/03/securing-your-api-for-mobile-access.html" rel="nofollow noreferrer">Overview of the problem and approach/solution</a></p>
<p><a href="https://automateddeveloper.blogspot.co.uk/2014/03/securing-your-mobile-api-spring-security.html" rel="nofollow noreferrer">Implementing the solution with Spring-security</a></p>
<p>Hope it helps some others..</p>
| 0 | 2,313 |
Can't change back button title but I can hide it
|
<p>I'm developing an <strong>iPhone</strong> application with <strong>latest SDK</strong> and <strong>XCode 4.2</strong></p>
<p>I use a UINavigationController, and to show a new ViewController I do this on AppDelegate.m:</p>
<pre><code> - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
}
else
{
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
}
self.viewController.title = NSLocalizedString(@"MAIN", nil);
navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
navController.navigationBar.tintColor = [UIColor darkGrayColor];
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];
return YES;
}
- (void) openDocumentation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
docViewController = [[DocumentationViewController alloc] initWithNibName:@"DocumentationViewController_iPhone" bundle:nil];
}
else
{
docViewController = [[DocumentationViewController alloc] initWithNibName:@"DocumentationViewControllerr_iPad" bundle:nil];
}
docViewController.title = NSLocalizedString(@"DOCUMENTATION", nil);
self.viewController.navigationItem.backBarButtonItem.title = @"Back";
[navController pushViewController:docViewController animated:YES];
}
</code></pre>
<p>On <code>DocumentationViewController.m</code> I do this:</p>
<pre><code>- (void) viewWillAppear:(BOOL)animated
{
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;
}
</code></pre>
<p>But it doesn't change back button title.</p>
<p>I move that code to viewDidLoad:</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;
}
- (void) viewWillAppear:(BOOL)animated
{
}
</code></pre>
<p>But still doesn't work.</p>
<p>And this doesn't work either:</p>
<pre><code>- (void) viewWillAppear:(BOOL)animated
{
self.navigationItem.backBarButtonItem.title = @"Back";
}
</code></pre>
<p>But if I do this, to test if I can't access back button:</p>
<pre><code>- (void) viewWillAppear:(BOOL)animated
{
self.navigationItem.hidesBackButton = YES;
}
</code></pre>
<p>It works!! And hides back button.</p>
<p>What am I doing wrong?</p>
| 0 | 1,330 |
Should FILTER be used inside or outside of SUMMARIZE?
|
<p>I have these two queries:</p>
<pre><code>EVALUATE
FILTER (
SUMMARIZE (
'Sales',
Products[ProductName],
'Calendar'[CalendarYear],
"Total Sales Amount", SUM ( Sales[SalesAmount] ),
"Total Cost", SUM ( 'Sales'[TotalProductCost] )
),
Products[ProductName] = "AWC Logo Cap"
)
ORDER BY
Products[ProductName],
'Calendar'[CalendarYear] ASC
</code></pre>
<p>and this:</p>
<pre><code>EVALUATE
SUMMARIZE (
FILTER ( 'Sales', RELATED ( Products[ProductName] ) = "AWC Logo Cap" ),
Products[ProductName],
'Calendar'[CalendarYear],
"Total Sales Amount", SUM ( Sales[SalesAmount] ),
"Total Cost", SUM ( 'Sales'[TotalProductCost] )
)
ORDER BY
Products[ProductName],
'Calendar'[CalendarYear] ASC
</code></pre>
<p>Both return the following:</p>
<p><a href="https://i.stack.imgur.com/3qrdO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3qrdO.png" alt="enter image description here"></a></p>
<p>The only difference between the two queries is the positioning of the FILTER function - which is better practice and why?</p>
<hr>
<p>note</p>
<p>So looking at the two sqlbi articles referenced by Alex we can do either of the following to potentially make things more performant but I'm still unsure if the FILTER function should happen inside or outside the other syntax:</p>
<pre><code>EVALUATE
FILTER (
ADDCOLUMNS (
SUMMARIZE ( 'Sales', Products[ProductName], 'Calendar'[CalendarYear] ),
"Total Sales Amount", CALCULATE ( SUM ( Sales[SalesAmount] ) ),
"Total Cost", CALCULATE ( SUM ( 'Sales'[TotalProductCost] ) )
),
Products[ProductName] = "AWC Logo Cap"
)
ORDER BY
Products[ProductName],
'Calendar'[CalendarYear] ASC
</code></pre>
<p>And using the 'SUMMARIZECOLUMNS' function:</p>
<pre><code>EVALUATE
FILTER (
SUMMARIZECOLUMNS (
Products[ProductName],
'Calendar'[CalendarYear],
"Total Sales Amount", SUM ( Sales[SalesAmount] ),
"Total Cost", SUM ( 'Sales'[TotalProductCost] )
),
Products[ProductName] = "AWC Logo Cap"
)
ORDER BY
Products[ProductName],
'Calendar'[CalendarYear] ASC
</code></pre>
<hr>
<p>note2 </p>
<p>Looks like SUMMARIZECOLUMNS has a built in FILTER parameter so I'd guess that this is the best way to go to guard against performance issues:</p>
<pre><code>EVALUATE
SUMMARIZECOLUMNS (
Products[ProductName],
'Calendar'[CalendarYear],
FILTER ( 'Products', Products[ProductName] = "AWC Logo Cap" ),
"Total Sales Amount", SUM ( Sales[SalesAmount] ),
"Total Cost", SUM ( 'Sales'[TotalProductCost] )
)
ORDER BY
Products[ProductName],
'Calendar'[CalendarYear] ASC
</code></pre>
| 0 | 1,052 |
WEBPACK_IMPORTED_MODULE_13___default(...) is not a function
|
<p>Context : I am building a small library (let's call it myLibrary here) using TypeScript and Webpack. I built it, imported it in a react application but the react application crash.</p>
<p><strong>Library side</strong></p>
<p>My main entry point (index.ts) has a default export as such :</p>
<pre><code>import wrapper from "./wrapper";
export default wrapper;
</code></pre>
<p>And my wrapper file exposes a default export which is a function (wrapper.ts) :</p>
<pre><code>const create = () => {
// Some functions
return {
init,
close,
getBase,
setBase
}
}
export default create;
</code></pre>
<p>The library pass all the unit tests easily.</p>
<p><strong>React application side</strong></p>
<p>After building and when importing my library in a React application, I have no Typescript error but my React app crashes with the following message :</p>
<pre><code>TypeError: myLibrary__WEBPACK_IMPORTED_MODULE_13___default(...) is not a function
</code></pre>
<p>After calling my library like that :</p>
<pre><code>import createAPI from "myLibrary";
const api = createAPI(); // Crash here even though I should have a nice object containing my functions
</code></pre>
<p>It's really strange as TS really compiled nicely to JS without any warnings.</p>
<p>My library wepback config (4.43.0) which I use to build with command <code>webpack --config webpack.config.js</code>:</p>
<pre><code>const path = require('path');
module.exports = {
mode: "production",
entry: "./src/index.ts",
output: {
filename: "index.js",
path: path.resolve(__dirname, 'dist'),
},
resolve: {
extensions: [".ts", ".js"]
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "ts-loader" }
]
}
}
</code></pre>
<p>My library TS config (3.7.3) :</p>
<pre><code>{
"compilerOptions": {
"outDir": "dist",
"target": "es5",
"module": "CommonJS",
"lib": ["dom", "dom.iterable", "esnext"],
"sourceMap": true,
"allowJs": true,
"jsx": "preserve",
"declaration": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true
},
"include": ["src"]
}
</code></pre>
<p>Any help would be greatly appreciated :)</p>
<p>EDIT :
After updating default export to named export :</p>
<pre><code>import { createAPI } from "myLibrary";
const api = createAPI();
</code></pre>
<p>I got a new error</p>
<pre><code>TypeError: Object(...) is not a function
</code></pre>
<p>And when I try to <code>console.log(typeof createAPI);</code> I got an undefined, which should not be possible as my tests are passing and TS doesn't complain.</p>
| 0 | 1,175 |
Email composure iOS 8
|
<p>I'm trying to open email composure in iOS 8 from Xcode 6, but getting an error. The same code is working fine if I'm trying from Xcode 5. Later I downloaded a sample code from apple developer portal: </p>
<p><a href="https://developer.apple.com/library/content/samplecode/MessageComposer/Introduction/Intro.html" rel="nofollow noreferrer">https://developer.apple.com/library/content/samplecode/MessageComposer/Introduction/Intro.html</a></p>
<p>But the result is same. Is there something, or some setting, I'm missing to optimise the code for Xcode 6</p>
<p>Here is the code:
in my button action</p>
<pre><code>MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@"Hello from California!"];
// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"];
NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"];
[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];
// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];
// Fill out the email body text
NSString *emailBody = @"It is raining in sunny California!";
[picker setMessageBody:emailBody isHTML:NO];
[self presentViewController:picker animated:YES completion:NULL];
</code></pre>
<p>email delegate</p>
<pre><code>self.feedbackMsg.hidden = NO;
// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
self.feedbackMsg.text = @"Result: Mail sending canceled";
break;
case MFMailComposeResultSaved:
self.feedbackMsg.text = @"Result: Mail saved";
break;
case MFMailComposeResultSent:
self.feedbackMsg.text = @"Result: Mail sent";
break;
case MFMailComposeResultFailed:
self.feedbackMsg.text = @"Result: Mail sending failed";
break;
default:
self.feedbackMsg.text = @"Result: Mail not sent";
break;
}
[self dismissViewControllerAnimated:YES completion:NULL];
</code></pre>
<p>result:</p>
<blockquote>
<p>email composure delegate disappearing automatically with result 0,
i.e., MFMailComposeResultCancelled</p>
<p>with error codes : MessageComposer[10993:196902]
viewServiceDidTerminateWithError: Error
Domain=_UIViewServiceInterfaceErrorDomain Code=3 "The operation
couldn’t be completed. (_UIViewServiceInterfaceErrorDomain error 3.)"
UserInfo=0x7b93f7e0 {Message=Service Connection Interrupted}</p>
</blockquote>
<p>and </p>
<blockquote>
<p>2014-09-17 22:04:22.538 MessageComposer[10993:205761]
timed out waiting for
fence barrier from com.apple.MailCompositionService</p>
</blockquote>
| 0 | 1,065 |
How to show Spinner-List when we tapped on button in android?
|
<p>Hi I recently came to the android technology and in my app I have two buttons(one for showing movies-list and another one for showing countrieslist)</p>
<p>When I tap on the second button I want to display movies-list in spinner-list as in the first image bellow.</p>
<p>But according to my code, when I tap on the button first spinner is appearing and I selected any one item and set that to my button title but after selection spinner still visible B/w two button as like my second screen how can remove it. </p>
<p>How can I resolve this problem?</p>
<p>Please help me. </p>
<p>I want to show directly spinner-list when I tap on button. </p>
<h2>xml:-</h2>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button1Action"
android:text="CountiesList"/>
<Spinner
android:visibility="gone"
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/mainLayout"
android:layout_alignParentRight="true"
android:paddingRight="0dp"
android:layout_marginTop="5dp"
/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button2Action"
android:text="MoviesList"/>
<Spinner
android:visibility="gone"
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/mainLayout"
android:layout_alignParentRight="true"
android:paddingRight="0dp"
android:layout_marginTop="5dp"
/>
</LinearLayout>
</code></pre>
<h2>activity:-</h2>
<pre><code>public class spinnerListProgramatically extends AppCompatActivity{
String [] countriesList = {"india","usa","england"
};
String [] moviesList = {"fury","300 rise of an empire","troy"
};
Spinner spinner1,spinner2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnerlist_runtime);
}
public void Button1Action(View view){
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setVisibility(View.VISIBLE);
}
public void Button2Action(View view){
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, moviesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
spinner2.setVisibility(View.VISIBLE);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/8iqgp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8iqgp.png" alt="enter image description here"></a></p>
<p>---<a href="https://i.stack.imgur.com/iRhWZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iRhWZ.png" alt="enter image description here"></a></p>
| 0 | 1,518 |
Submit a php form and display its result on div without reloading page
|
<p>First of all, thank you for your kind help. </p>
<p>I have tried almost everything I found on stackoverflow but I cannot get this to work.</p>
<p>I created a form to send a text to the webmaster (instead of an email). So I have my index.php file </p>
<pre><code> <style>
.result{
padding: 20px;
font-size: 16px;
background-color: #ccc;
color: #fff;
}
</style>
<form id="contact-form" method="post">
<div>
<input type="text" id="fullname" name="fullname" value="" placeholder="Name" required="required" autofocus="autofocus" autocomplete="off" />
</div>
<div>
<input type="email" id="email" name="email" value="" placeholder="example@yourdomain.com" required="required" autocomplete="off" />
</div>
<div>
<textarea id="message" name="message" value="" placeholder="20 characters max." required="required" maxlength="50" autocomplete="off" ></textarea>
</div>
<div>
<input type="submit" value="Submit" id="submit-button" name="submit" />
*indicates a required field
</div>
</form>
<div class="result"></div>
</code></pre>
<p>And this is my jquery</p>
<pre><code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#contact-form').submit(function() {
$.ajax({
type:"POST",
url:"sendtext.php",
data: $("#contact-form").serialize(),
success: function(response){$(".result").appendTo(response)}
});
//return false;
});
});
</script>
</code></pre>
<p>The script does not work. If I put <code>action = sendtext.php</code> in the <code><form></code> it will work perfectly but it will take me to sendtext.php and <code>echo</code> the message.</p>
<p>What I want is to show the <code>echo</code> in the <code><div class="result"></div></code>.</p>
<p>Again thank you for your help.</p>
<hr>
<p><strong>UPDATE # 1</strong>
After a few comments...</p>
<p>this is what I have so far...</p>
<pre><code><script>
$(document).ready(function(){
$('#contact-form').submit(function(e) {
e.preventDefault();
$.ajax({
type:"POST",
url:"sendtext.php",
data: $("#contact-form").serialize(),
success: function(response){$(".result").append(response)}
});
//return false;
});
});
</script>
</code></pre>
<hr>
<p><strong>Update 2</strong></p>
<p>After reading all the comments and try different options, no success just yet! I did what @guy suggested, and it worked but I want to use <code>form</code> and <code>submit</code>.</p>
<p>Again, I appreciate all your time you put to help me out. Thank you!</p>
| 0 | 1,359 |
how to install node js canvas on windows
|
<p>I'm trying to get working canvas on node js. I'm using Windows Vista. After basic approach <code>npm install canvas</code> failed (see error below), I have looked up some tutorials, here is what I have tried:</p>
<p>sources:<br>
<a href="https://github.com/benjamind/delarre.docpad/blob/master/src/documents/posts/installing-node-canvas-for-windows.html.md" rel="noreferrer">installing-node-canvas-for-windows</a><br>
<a href="https://github.com/LearnBoost/node-canvas/wiki/Installation---Windows" rel="noreferrer">LearnBoost/node-canvas/wiki/Installation---Windows</a></p>
<ul>
<li>I have installed older Python (2.7.5) and add it to PATH (and remove Python 3.2. from PATH) </li>
<li>I have checked that I do have Microsoft Visual Studio 2010 Professional installed</li>
<li>I have downloaded the 'all in one' GTK package from <a href="http://ftp.gnome.org/pub/gnome/binaries/win32/gtk+/2.24/gtk+-bundle_2.24.10-20120208_win32.zip" rel="noreferrer">http://ftp.gnome.org/pub/gnome/binaries/win32/gtk+/2.24/gtk+-bundle_2.24.10-20120208_win32.zip</a>, unziped it in C:\GTK\ and add 'C:\GTK\bin' to PATH</li>
</ul>
<p>log in console (after running <code>npm install canvas</code> in cmd):<br>
log contains several warnings, I don't thing these are the problem - it is mostly something like 'conversion from double to float', and one error marked in red color:</p>
<pre><code>init.cc
d:\pathToApp\node_modules\canvas\src\PNG.h(5): fatal error C1083: Cannot
open include file: 'cairo.h': No such file or directory [d:\pathToApp\n
ode_modules\canvas\build\canvas.vcxproj]
</code></pre>
<p>And at the very end of log there is:</p>
<pre><code>gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\
npm\node_modules\node-gyp\lib\build.js:267:23)
gyp ERR! stack at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:789:
12)
gyp ERR! System Windows_NT 6.0.6002
gyp ERR! command "node" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modu
les\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd d:\pathToApp\node_modules\canvas
gyp ERR! node -v v0.10.16
gyp ERR! node-gyp -v v0.10.9
gyp ERR! not ok
npm ERR! weird error 1
npm ERR! not ok code 0
</code></pre>
<p>After that, nothing appeared in node-module folder (no canvas subdirectory, npm after unsuccessful installation removed the subdirectory).</p>
<p>So I have also tried to download canvas module manually from github, unzip it in node-modules and then run <code>node-gyp configure</code> in node-modules/canvas with success, and <code>node-gyp build</code>, which unfortunatelly gave me the same error <code>Cannot open include file: 'cairo.h'</code>.</p>
<p>I have read everything that I found on this carefully. If you can suggest any help, please do it.</p>
| 0 | 1,071 |
Java io.jsonwebtoken.MalformedJwtException: Unable to read JSON value:
|
<p>I have following function written to parse claims:</p>
<pre><code> public Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(config.getJwtSecret()).parseClaimsJws(token).getBody();
}
</code></pre>
<p>And when I try to call the function with the following string:</p>
<pre><code>yJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJicGF3YW4iLCJyb2xlIjpudWxsLCJlbmFibGUiOm51bGwsImV4cCI6MTUzNDgyMzUyNSwiaWF0IjoxNTM0Nzk0NzI1fQ.65PPknMebR53ykLm-EBIunjFJvlV-vL-pfTOtbBLtnQ
</code></pre>
<p>I get the following error:</p>
<pre><code>io.jsonwebtoken.MalformedJwtException: Unable to read JSON value: Ș[Ȏ��̍M��
at io.jsonwebtoken.impl.DefaultJwtParser.readValue(DefaultJwtParser.java:554) ~[jjwt-0.9.1.jar:0.9.1]
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:252) ~[jjwt-0.9.1.jar:0.9.1]
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:481) ~[jjwt-0.9.1.jar:0.9.1]
at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:541) ~[jjwt-0.9.1.jar:0.9.1]
at com.saralpasal.api.security.JWTUtil.getAllClaimsFromToken(JWTUtil.java:33) ~[classes/:na]
at com.saralpasal.api.security.JWTUtil.getUsernameFromToken(JWTUtil.java:29) ~[classes/:na]
at com.saralpasal.api.security.AuthenticationManager.getUserNameFromToken(AuthenticationManager.java:51) ~[classes/:na]
at com.saralpasal.api.security.AuthenticationManager.authenticate(AuthenticationManager.java:37) ~[classes/:na]
at com.saralpasal.api.security.SecurityContextRepository.load(SecurityContextRepository.java:34) [classes/:na]
at org.springframework.security.web.server.context.ReactorContextWebFilter.withSecurityContext(ReactorContextWebFilter.java:51) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.security.web.server.context.ReactorContextWebFilter.lambda$filter$0(ReactorContextWebFilter.java:46) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at reactor.core.publisher.MonoSubscriberContext.subscribe(MonoSubscriberContext.java:40) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:53) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:53) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:53) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:150) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:115) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:115) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1083) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoFlatMap$FlatMapInner.onNext(MonoFlatMap.java:241) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1083) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoCollectList$MonoBufferAllSubscriber.onComplete(MonoCollectList.java:117) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxIterable$IterableSubscription.fastPath(FluxIterable.java:334) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:199) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoCollectList$MonoBufferAllSubscriber.onSubscribe(MonoCollectList.java:90) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:140) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:64) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoCollectList.subscribe(MonoCollectList.java:59) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:150) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:67) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:76) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxFilterWhen$FluxFilterWhenSubscriber.drain(FluxFilterWhen.java:287) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxFilterWhen$FluxFilterWhenSubscriber.onNext(FluxFilterWhen.java:131) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxIterable$IterableSubscription.slowPath(FluxIterable.java:244) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:202) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxFilterWhen$FluxFilterWhenSubscriber.onSubscribe(FluxFilterWhen.java:190) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:140) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:64) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.FluxFilterWhen.subscribe(FluxFilterWhen.java:68) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoNext.subscribe(MonoNext.java:40) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoSwitchIfEmpty.subscribe(MonoSwitchIfEmpty.java:44) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoFlatMap.subscribe(MonoFlatMap.java:60) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoMapFuseable.subscribe(MonoMapFuseable.java:59) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoMapFuseable.subscribe(MonoMapFuseable.java:59) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoFlatMap.subscribe(MonoFlatMap.java:60) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:53) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoOnErrorResume.subscribe(MonoOnErrorResume.java:44) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoOnErrorResume.subscribe(MonoOnErrorResume.java:44) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoOnErrorResume.subscribe(MonoOnErrorResume.java:44) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.Mono.subscribe(Mono.java:3080) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:172) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoPeekFuseable.subscribe(MonoPeekFuseable.java:70) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.core.publisher.MonoPeekTerminal.subscribe(MonoPeekTerminal.java:61) ~[reactor-core-3.1.8.RELEASE.jar:3.1.8.RELEASE]
at reactor.ipc.netty.channel.ChannelOperations.applyHandler(ChannelOperations.java:380) ~[reactor-netty-0.7.8.RELEASE.jar:0.7.8.RELEASE]
at reactor.ipc.netty.http.server.HttpServerOperations.onHandlerStart(HttpServerOperations.java:398) ~[reactor-netty-0.7.8.RELEASE.jar:0.7.8.RELEASE]
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) ~[netty-common-4.1.27.Final.jar:4.1.27.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404) ~[netty-common-4.1.27.Final.jar:4.1.27.Final]
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:322) ~[netty-transport-native-epoll-4.1.27.Final-linux-x86_64.jar:4.1.27.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884) ~[netty-common-4.1.27.Final.jar:4.1.27.Final]
at java.base/java.lang.Thread.run(Thread.java:844) ~[na:na]
</code></pre>
<p>Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Ș': was expecting ('true', 'false' or 'null')
at [Source: (String)"Ș[Ȏ��̍M��"; line: 1, column: 2]</p>
<p>no matter what I try I could not find the cause of the error.
Anybody have experienced the same error. Any help would be greatly appreciated.</p>
<p>Thank you very much</p>
| 0 | 3,768 |
Download a image from server to android and show in imageview
|
<p>I have an server (i use GlassFish). I am able to send Json or XML etc. with http to my android device. I saw an example to upload a picture from my android device to the server. That converts my picked image to byte, converts to String and back at my server. So i can put it on my PC (server).
Now i just want the opposite: get a picture from my PC and with the URL get the image (bitmap here) to imageview. but with debugging bmp seems to be "null". google says its because my image is not a valid bitmap (so maybe something is wrong at my server encoding?).
What does i need to change to this code to get it working?</p>
<p>Server code:</p>
<pre><code>public class getImage{
String imageDataString = null;
@GET
@Path("imageid/{id}")
public String findImageById(@PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64URLSafeString(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
</code></pre>
<p>and this is the android side (android studio):</p>
<pre><code>public class XMLTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
</code></pre>
| 0 | 1,504 |
How to Calculate Centroid
|
<p>I am working with geospatial shapes and looking at the centroid algorithm here,</p>
<p><a href="http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon" rel="noreferrer">http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon</a></p>
<p>I have implemented the code in C# like this (which is just this adapted),</p>
<p><a href="https://stackoverflow.com/questions/2792443/finding-the-centroid-of-a-polygon">Finding the centroid of a polygon?</a></p>
<pre><code>class Program
{
static void Main(string[] args)
{
List<Point> vertices = new List<Point>();
vertices.Add(new Point() { X = 1, Y = 1 });
vertices.Add(new Point() { X = 1, Y = 10 });
vertices.Add(new Point() { X = 2, Y = 10 });
vertices.Add(new Point() { X = 2, Y = 2 });
vertices.Add(new Point() { X = 10, Y = 2 });
vertices.Add(new Point() { X = 10, Y = 1 });
vertices.Add(new Point() { X = 1, Y = 1 });
Point centroid = Compute2DPolygonCentroid(vertices);
}
static Point Compute2DPolygonCentroid(List<Point> vertices)
{
Point centroid = new Point() { X = 0.0, Y = 0.0 };
double signedArea = 0.0;
double x0 = 0.0; // Current vertex X
double y0 = 0.0; // Current vertex Y
double x1 = 0.0; // Next vertex X
double y1 = 0.0; // Next vertex Y
double a = 0.0; // Partial signed area
// For all vertices except last
int i=0;
for (i = 0; i < vertices.Count - 1; ++i)
{
x0 = vertices[i].X;
y0 = vertices[i].Y;
x1 = vertices[i+1].X;
y1 = vertices[i+1].Y;
a = x0*y1 - x1*y0;
signedArea += a;
centroid.X += (x0 + x1)*a;
centroid.Y += (y0 + y1)*a;
}
// Do last vertex
x0 = vertices[i].X;
y0 = vertices[i].Y;
x1 = vertices[0].X;
y1 = vertices[0].Y;
a = x0*y1 - x1*y0;
signedArea += a;
centroid.X += (x0 + x1)*a;
centroid.Y += (y0 + y1)*a;
signedArea *= 0.5;
centroid.X /= (6*signedArea);
centroid.Y /= (6*signedArea);
return centroid;
}
}
public class Point
{
public double X { get; set; }
public double Y { get; set; }
}
</code></pre>
<p>The problem is that this algorithm when I have this shape (which is an L shape),</p>
<p>(1,1) (1,10) (2,10) (2,2) (10,2) (10,1) (1,1)</p>
<p>It gives me the result (3.62, 3.62). Which is OK, except that point is outside the shape. Is there another algorithm around that takes this into account?</p>
<p>Basically a person is going to be drawing a shape on a map. This shape might span multiple roads (so could be an L shape) and I want to work out the centre of the shape. This is so I can work out the road name at that point. It doesn't make sense to me for it to be outside the shape if they have drawn a long skinny L shape.</p>
| 0 | 1,339 |
Can't deploy app to ios 8 device
|
<p>Just updated an iPad Mini to iOS 8 and suddenly can't debug my app on it with XCode 6.0.1.
The error in Xcode is <code>App installation failed</code> with <code>An unknown error has occurred.</code>. On the device the app remains greyed out.</p>
<p>Tried to :</p>
<ul>
<li>delete the app from ipad ( was working before )</li>
<li>Soft reset and reboot the device </li>
<li>Delete derived data and clean</li>
<li>Reboot the mac </li>
<li>reinstall xcode</li>
<li>change the bundle id and product name</li>
<li>Recreate the dev certificates and provisioning profiles</li>
</ul>
<p>With iOS 6 and iOS 7 devices works fine, also, can debug other projects too, but not this one, so I'm getting desperate. </p>
<p>Any idea ? </p>
<p>Console log:</p>
<pre><code>23/09/14 18:24:16,617 Xcode[421]: createShadowPath (thread 0x12a2f6000): returning: /var/folders/lq/1z47wljj77gbhhrhc9z_yylw0000gn/C/com.apple.DeveloperTools/6.0.1/Xcode/942f46185227b6e098ea41a4548a0649/e269ac837383a4b805c1e212d18ffe36483ab24a/TDev.app
23/09/14 18:24:16,617 Xcode[421]: createSiblingInPath (thread 0x12a2f6000): returning: /var/folders/lq/1z47wljj77gbhhrhc9z_yylw0000gn/C/com.apple.DeveloperTools/6.0.1/Xcode/942f46185227b6e098ea41a4548a0649/e269ac837383a4b805c1e212d18ffe36483ab24a/ManifestCache.plist
23/09/14 18:24:16,690 Xcode[421]: _AMDeviceCopyInstalledAppInfo (thread 0x12a2f6000): no app info
23/09/14 18:24:16,693 Xcode[421]: AMDeviceSecureInstallApplicationBundle (thread 0x12a2f6000): unable to get installed app info, falling back to old skool install
23/09/14 18:24:16,693 Xcode[421]: AMDeviceSecureInstallApplicationBundle (thread 0x12a2f6000): Blasting the bundle over to the device in an old skool way
23/09/14 18:24:27,005 Xcode[421]: AMDErrorForMobileInstallationCallbackDict (thread 0x114564000): GOT AN ERROR 0xe800003a
23/09/14 18:24:27,032 Xcode[421]: SZConduit: _MonitorResultDispatchFunction:140 (0x0x114564000): Got error from service: InstallationFailed
23/09/14 18:24:27,033 Xcode[421]: _AMDeviceTransferAndInstall (thread 0x12a2f6000): SZConduitSendPathWithPreflight failed: 0xe8008001
23/09/14 18:24:27,051 Xcode[421]: writeDictToFile:1258 ==== Successfully wrote Manifest cache to /var/folders/lq/1z47wljj77gbhhrhc9z_yylw0000gn/C/com.apple.DeveloperTools/6.0.1/Xcode/942f46185227b6e098ea41a4548a0649/e269ac837383a4b805c1e212d18ffe36483ab24a/ManifestCache.plist
23/09/14 18:24:27,053 Xcode[421]: AMDeviceSecureInstallApplicationBundle (thread 0x12a2f6000): returning 0xe8008001
</code></pre>
<p><strong>Edit:</strong> </p>
<p>It seems that the regeneration of the certificates was the solution but after Clean there was necessary a Clean Build Folder too, which solved the issue (for now at least).</p>
| 0 | 1,038 |
Generate the JPA metamodel files using maven-processor-plugin - What is a convenient way for re-generation?
|
<p>I am trying to use maven-processor-plugin for generating JPA metamodel java files and I set up my pom.xml as belows. </p>
<pre><code><plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<!-- source output directory -->
<outputDirectory>${basedir}/src/main/java</outputDirectory>
<processors>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
</processors>
<overwrite>true</overwrite>
</configuration>
</execution>
</executions>
</plugin>
</code></pre>
<p>Actually, I want to generate metamodel files (Entity_.java) to the same packages of their corresponding entities (Entity.java). Hence, I set up outputDirectory in the plugin as </p>
<pre><code><outputDirectory>${basedir}/src/main/java</outputDirectory>
</code></pre>
<p>The first time of running is ok, but from later times when performing the metamodel java files re-generation, the plugin always turns out an error about file duplication.</p>
<p>My Question is
- Is there any way to config the plugin so that it could overwrite the existing files during re-generation?</p>
<p>In fact, to work around</p>
<ol>
<li>I must delete all generated files before any re-generation.</li>
<li>I could point the outputDirectory to a different folder in /target, this location will be clean everytime Maven run, but this
leads to manually copy generated metamodel files to source folder
for update after re-generation.</li>
</ol>
<p>Both of these are very inconvenient and I hope you guys could show me a proper solution.</p>
| 0 | 1,148 |
What's the net::ERR_HTTP2_PROTOCOL_ERROR about?
|
<p>I'm currently working on a website, which triggers a <code>net::ERR_HTTP2_PROTOCOL_ERROR 200</code> error on Google Chrome. I'm not sure exactly what can provoke this error, I just noticed it pops out only when accessing the website in HTTPS. I can't be 100% sure it is related, but it looks like it prevents JavaScript to be executed properly.</p>
<p>For instance, the following scenario happens :</p>
<ol>
<li><p>I'm accessing the website in HTTPS</p>
</li>
<li><p>My Twitter feed integrated via <a href="https://publish.twitter.com" rel="noreferrer">https://publish.twitter.com</a> isn't loaded at all</p>
</li>
<li><p>I can notice in the console the ERR_HTTP2_PROTOCOL_ERROR</p>
</li>
<li><p>If I remove the code to load the Twitter feed, the error remains</p>
</li>
<li><p>If I access the website in HTTP, the Twitter feed appears and the error disappears</p>
</li>
</ol>
<p>Google Chrome is the only web browser triggering the error: it works well on both Edge and Firefox.
(NB: I tried with Safari, and I have a similar <code>kcferrordomaincfnetwork 303</code> error)</p>
<p>I was wondering if it could be related to the header returned by the server since there is this '200' mention in the error, and a 404 / 500 page isn't triggering anything.</p>
<p>Thing is the error isn't documented at all. Google search gives me very few results. Moreover, I noticed it appears on very recent Google Chrome releases; the error doesn't pop on v.64.X, but it does on v.75+ (regardless of the OS; I'm working on Mac tho).</p>
<hr />
<p>Might be related to <a href="https://stackoverflow.com/questions/49927327/website-ok-on-firefox-but-not-on-safari-kcferrordomaincfnetwork-error-303-neit">Website OK on Firefox but not on Safari (kCFErrorDomainCFNetwork error 303) neither Chrome (net::ERR_SPDY_PROTOCOL_ERROR)</a></p>
<hr />
<p>Findings from further investigations are the following:</p>
<ul>
<li><strong>error doesn't pop on the exact same page if server returns 404 instead of 2XX</strong></li>
<li>error doesn't pop on local with a HTTPS certificate</li>
<li>error pops on a different server (both are OVH's), which uses a different certificate</li>
<li>error pops no matter what PHP version is used, from 5.6 to 7.3 (framework used : Cakephp 2.10)</li>
</ul>
<p>As requested, below is the returned header for the failing ressource, which is the whole web page. Even if the error is triggering on each page having a HTTP header 200, those pages are always loading on client's browser, but sometimes an element is missing (in my exemple, the external Twitter feed). Every other asset on the Network tab has a success return, except the whole document itself.
<a href="https://i.stack.imgur.com/ZkdHo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZkdHo.png" alt="line that failed in console" /></a></p>
<p>Google Chrome header (with error):</p>
<p><a href="https://i.stack.imgur.com/0wCrD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0wCrD.png" alt="Chrome header" /></a></p>
<p>Firefox header (without error):</p>
<p><a href="https://i.stack.imgur.com/AAtn8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AAtn8.png" alt="Firefox header" /></a></p>
<p>A <code>curl --head --http2</code> request in console returns the following success:</p>
<pre><code>HTTP/2 200
date: Fri, 04 Oct 2019 08:04:51 GMT
content-type: text/html; charset=UTF-8
content-length: 127089
set-cookie: SERVERID31396=2341116; path=/; max-age=900
server: Apache
x-powered-by: PHP/7.2
set-cookie: xxxxx=0919c5563fc87d601ab99e2f85d4217d; expires=Fri, 04-Oct-2019 12:04:51 GMT; Max-Age=14400; path=/; secure; HttpOnly
vary: Accept-Encoding
</code></pre>
<hr />
<p>Trying to go deeper with the chrome://net-export/ and <a href="https://netlog-viewer.appspot.com" rel="noreferrer">https://netlog-viewer.appspot.com</a> tools is telling me the request ends with a RST_STREAM :</p>
<pre><code>t=123354 [st=5170] HTTP2_SESSION_RECV_RST_STREAM
--> error_code = "2 (INTERNAL_ERROR)"
--> stream_id = 1
</code></pre>
<p>For what I read in <a href="https://stackoverflow.com/questions/28736463/rst-stream-frame-in-http2">this other post</a>, "<em>In HTTP/2, if the client wants to abort the request, it sends a RST_STREAM. When the server receives a RST_STREAM, it will stop sending DATA frames to the client, thereby stopping the response (or the download). The connection is still usable for other requests, and requests/responses that were concurrent with the one that has been aborted may continue to progress.
[...]
It is possible that by the time the RST_STREAM travels from the client to the server, the whole content of the request is in transit and will arrive to the client, which will discard it. However, for large response contents, sending a RST_STREAM may have a good chance to arrive to the server before the whole response content is sent, and therefore will save bandwidth.</em>"</p>
<p>The described behavior is the same as the one I can observe. But that would mean the browser is the culprit, and then I wouldn't understand why it happens on two identical pages with one having a 200 header and the other a 404 (same goes if I disable JS).</p>
| 0 | 1,691 |
Spring Boot Integration test throwing error and not able to pick up an existing bean in another maven module
|
<p>I have the following maven-based project structure</p>
<pre><code>product-app
product-web
product-service
product-integration-tests
</code></pre>
<p>There is an <code>MailClientService</code> service written in <code>product-service</code> module that I would like to do an integration test on. The integration test is obviously written in <code>product-integration-tests</code> module. </p>
<p>The <code>product-web module</code> has been already added as a dependency in the pom of <code>product-integration-tests</code> module.</p>
<p>However the problem is that during runtime of the integration test it is not able to construct the <code>MailClientService</code> bean and is throwing a runtime exception.</p>
<p><strong>Exception</strong></p>
<pre><code>13:53:01.161 [main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener@20b2475a] to prepare test instance [com.radial.hostedpayments.service.MailClientServiceIntegrationTest@7857fe2]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.radial.hostedpayments.service.MailClientServiceIntegrationTest': Unsatisfied dependency expressed through field 'mailClientService': No qualifying bean of type [com.radial.hostedpayments.service.MailClientService] found for dependency [com.radial.hostedpayments.service.MailClientService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.radial.hostedpayments.service.MailClientService] found for dependency [com.radial.hostedpayments.service.MailClientService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener.prepareTestInstance(AutoConfigureReportTestExecutionListener.java:46) ~[spring-boot-test-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367) [surefire-junit4-2.19.1.jar:2.19.1]
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) [surefire-junit4-2.19.1.jar:2.19.1]
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) [surefire-junit4-2.19.1.jar:2.19.1]
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) [surefire-junit4-2.19.1.jar:2.19.1]
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290) [surefire-booter-2.19.1.jar:2.19.1]
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242) [surefire-booter-2.19.1.jar:2.19.1]
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121) [surefire-booter-2.19.1.jar:2.19.1]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.radial.hostedpayments.service.MailClientService] found for dependency [com.radial.hostedpayments.service.MailClientService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 30 more
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.318 sec <<< FAILURE! - in com.radial.hostedpayments.service.MailClientServiceIntegrationTest
shouldSendMail(com.radial.hostedpayments.service.MailClientServiceIntegrationTest) Time elapsed: 0.002 sec <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.radial.hostedpayments.service.MailClientServiceIntegrationTest': Unsatisfied dependency expressed through field 'mailClientService': No qualifying bean of type [com.radial.hostedpayments.service.MailClientService] found for dependency [com.radial.hostedpayments.service.MailClientService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.radial.hostedpayments.service.MailClientService] found for dependency [com.radial.hostedpayments.service.MailClientService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.radial.hostedpayments.service.MailClientService] found for dependency [com.radial.hostedpayments.service.MailClientService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Results :
Tests in error:
MailClientServiceIntegrationTest.shouldSendMail » UnsatisfiedDependency Error ...
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
</code></pre>
<p><strong>MailClientServiceIntegrationTest.java (product-integration-tests maven module)</strong></p>
<pre><code>@RunWith(SpringRunner.class)
public class MailClientServiceIntegrationTest {
@Autowired
private MailClientService mailClientService;
private GreenMail smtpServer;
@Before
public void setUp() throws Exception {
smtpServer = new GreenMail(new ServerSetup(25, null, "smtp"));
smtpServer.start();
}
@Test
public void shouldSendMail() throws Exception {
//given
String recipient = "name@dolszewski.com";
String message = "Test message content";
//when
mailClientService.prepareAndSend(recipient, message);
//then
assertReceivedMessageContains(message);
}
private void assertReceivedMessageContains(String expected) throws IOException, MessagingException {
MimeMessage[] receivedMessages = smtpServer.getReceivedMessages();
assertEquals(1, receivedMessages.length);
String content = (String) receivedMessages[0].getContent();
assertTrue(content.contains(expected));
}
@After
public void tearDown() throws Exception {
smtpServer.stop();
}
}
</code></pre>
<p><strong>MailClientService.java (product-service maven module)</strong> </p>
<pre><code>@Service
public class MailClientService {
@Autowired
private JavaMailSender mailSender;
private MailContentBuilder mailContentBuilder;
@Value("${error.email.from.address}")
private String emailAddressFrom;
@Value("${error.email.to.address}")
private String emailRecipientAddress;
private String[] emailRecipientAddresses;
private static final boolean HTML_FLAG = true;
private static final String ERROR_ALERT_EMAIL_SUBJECT = "Hosted Payment Service - Error Alert on ";
private static final Logger LOGGER = LoggerFactory.getLogger(MailClientServiceImpl.class);
public MailClientServiceImpl(final JavaMailSender javaMailSender, final MailContentBuilder emailContentBuilder) {
this.mailSender = javaMailSender;
this.mailContentBuilder = emailContentBuilder;
}
@Override
public void prepareAndSend(final String message, final String emailSubject) {
emailRecipientAddresses = StringUtils.split(emailRecipientAddress, ',');
MimeMessagePreparator messagePreparator = mimeMessage -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setFrom(emailAddressFrom);
messageHelper.setTo(emailRecipientAddresses);
if (StringUtils.isNotBlank(emailSubject)) {
messageHelper.setSubject(emailSubject);
} else {
messageHelper.setSubject(ERROR_ALERT_EMAIL_SUBJECT + CommonUtils.getHostName());
}
// Create the HTML body using Thymeleaf
String htmlContent = mailContentBuilder.buildHtmlTemplating(message);
messageHelper.setText(htmlContent, HTML_FLAG);
};
try {
// Send email
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sending email '{}' to: {} ", ERROR_ALERT_EMAIL_SUBJECT, emailRecipientAddress);
}
mailSender.send(messagePreparator);
} catch (MailException e) {
e.printStackTrace();
LOGGER.error("Problem with sending alert email to: {}, error message: {}", emailRecipientAddress, e.getMessage());
}
}
@Override
public void prepareAndSend(final String message) {
prepareAndSend(message, null);
}
}
</code></pre>
<p><strong>product-web/pom.xml</strong></p>
<pre><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<attachClasses>true</attachClasses>
</configuration>
</plugin>
</code></pre>
<p><strong>product-integration-tests/pom.xml</strong></p>
<pre><code><dependency>
<groupId>${project.groupId}</groupId>
<artifactId>hosted-payments</artifactId>
<version>${project.version}</version>
<classifier>classes</classifier>
</dependency>
</code></pre>
| 0 | 5,234 |
Reactjs Bootstrap Overriding CSS
|
<p>I am learning react and nextjs, and am faced with a problem where the bootstrap css is overriding my own css. Basically I have a navbar component with a style of backgroundColor red but unfortunately the bootstrap css then overrides the style. I need help to find a better way to achieve this result.</p>
<p>Here is my code</p>
<p>/page/index.js</p>
<pre><code>import Head from "next/head";
import Navbar from "../components/navbar";
export default () => (
<div>
<Head>
<title>Testing</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous"
/>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"
/>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"
/>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin="anonymous"
/>
</Head>
<Navbar name="Test" />
</div>
);
</code></pre>
<p>/components/navbar.js</p>
<pre><code>class NavBar extends React.Component {
state = {
collapseID: "navbarNav"
};
style = {
backgroundColor: "red"
};
render(props) {
return (
<React.Fragment>
<nav className="navbar navbar-expand-lg navbar-light bg-light" style={this.style}>
<Brand name={this.props.name} target={this.state.collapseID} />
<div className="collapse navbar-collapse" id={this.state.collapseID}>
<PageList />
</div>
</nav>
</React.Fragment>
);
}
}
export default NavBar;
</code></pre>
<p>The red style keeps getting overrided by bootstrap
If there is someway to improve this code please let me know. I appreciate all the help. Thank you.</p>
| 0 | 1,187 |
Why does Celery work in Python shell, but not in my Django views? (import problem)
|
<p>I installed Celery (latest stable version.)
I have a directory called <code>/home/myuser/fable/jobs</code>. Inside this directory, I have a file called tasks.py:</p>
<pre><code>from celery.decorators import task
from celery.task import Task
class Submitter(Task):
def run(self, post, **kwargs):
return "Yes, it works!!!!!!"
</code></pre>
<p>Inside this directory, I also have a file called celeryconfig.py:</p>
<pre><code>BROKER_HOST = "localhost"
BROKER_PORT = 5672
BROKER_USER = "abc"
BROKER_PASSWORD = "xyz"
BROKER_VHOST = "fablemq"
CELERY_RESULT_BACKEND = "amqp"
CELERY_IMPORTS = ("tasks", )
</code></pre>
<p>In my <code>/etc/profile</code>, I have these set as my PYTHONPATH:</p>
<ul>
<li><code>PYTHONPATH=/home/myuser/fable:/home/myuser/fable/jobs</code></li>
</ul>
<p>So I run my Celery worker using the console (<code>$ celeryd --loglevel=INFO</code>), and I try it out.
I open the Python console and import the tasks. Then, I run the Submitter.</p>
<pre><code>>>> import fable.jobs.tasks as tasks
>>> s = tasks.Submitter()
>>> s.delay("abc")
<AsyncResult: d70d9732-fb07-4cca-82be-d7912124a987>
</code></pre>
<p>Everything works, as you can see in my console</p>
<pre><code>[2011-01-09 17:30:05,766: INFO/MainProcess] Task tasks.Submitter[d70d9732-fb07-4cca-82be-d7912124a987] succeeded in 0.0398268699646s:
</code></pre>
<p>But when I go into my Django's views.py and run the exact 3 lines of code as above, I get this:</p>
<pre><code>[2011-01-09 17:25:20,298: ERROR/MainProcess] Unknown task ignored: "Task of kind 'fable.jobs.tasks.Submitter' is not registered, please make sure it's imported.": {'retries': 0, 'task': 'fable.jobs.tasks.Submitter', 'args': ('abc',), 'expires': None, 'eta': None, 'kwargs': {}, 'id': 'eb5c65b4-f352-45c6-96f1-05d3a5329d53'}
Traceback (most recent call last):
File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/listener.py", line 321, in receive_message
eventer=self.event_dispatcher)
File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/job.py", line 299, in from_message
eta=eta, expires=expires)
File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/job.py", line 243, in __init__
self.task = tasks[self.task_name]
File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/registry.py", line 63, in __getitem__
raise self.NotRegistered(str(exc))
NotRegistered: "Task of kind 'fable.jobs.tasks.Submitter' is not registered, please make sure it's imported."
</code></pre>
<p>It's weird, because the celeryd client does show that it's registered, when I launch it.</p>
<pre><code>[2011-01-09 17:38:27,446: WARNING/MainProcess]
Configuration ->
. broker -> amqp://GOGOme@localhost:5672/fablemq
. queues ->
. celery -> exchange:celery (direct) binding:celery
. concurrency -> 1
. loader -> celery.loaders.default.Loader
. logfile -> [stderr]@INFO
. events -> OFF
. beat -> OFF
. tasks ->
. tasks.Decayer
. tasks.Submitter
</code></pre>
<p>Can someone help?</p>
| 0 | 1,277 |
ASP.Net: How to maintain TextBox State after postback
|
<p>I would like to know how to maintain the control state that has been modified in Javascript.<br />
I have two TextBoxes, one DropDownList and a button (all Runat=Server) in C# ASP.net 2010 Express.<br /><br />
First textbox is just accept whatever data user input. <br />Second textbox enable state will change based on DDL selected value. <br />If ddl selected value is "-", second textbox will become Enabled = False. <br />
If not "-", it will become Enabled = True. This enable is done through Javascript.</p>
<p><br />
In my Page Load event, I have below code.</p>
<pre><code>if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
</code></pre>
<p><br />And in my aspx page, I have some javascript which will clear the textbox data and disable the textbox.</p>
<p>Here is for Second Textbox.</p>
<pre><code><asp:TextBox ID="txtKey2" runat="server" Width="425px" EnableViewState="False"></asp:TextBox>
</code></pre>
<p><br />
And here is for DDL.</p>
<pre><code><asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
</code></pre>
<p>Here is the code for my Javascript. (I have a plan to implement other textbox and ddl so in my code I have Else if condition).</p>
<pre><code>function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
</code></pre>
<p>I have nothing in button click event.</p>
<p>By using above all code, when I run the project, the page loads Ok.
The second textbox enabled state is set to False (through Page_Load event). So far Ok.</p>
<p>Then from my browser, I choose ddl value to other instead of "-", the textbox become enable because of javascript. This is Ok.</p>
<p>I input the value and click on the button. Page PostBack happens here. Textbox is still enabled (because of EnableViewState = False for my textbox).</p>
<p>I choose ddl value to "-", second textbox became disabled.
<br />Click on the button, page postback happen, but this time the textbox is still enabled. << This is the issue I'm trying to solve. I change EnableViewState, ViewStateMode in different values but still the same.</p>
<p>Is there any solution for this one?</p>
<p>Here is my test image URL.
<a href="http://postimg.org/image/atrtkip49/" rel="nofollow">State 1</a> ,
<a href="http://postimg.org/image/3pa0bhhux/" rel="nofollow">State 2</a> ,
<a href="http://postimg.org/image/hy9mtjwdl/" rel="nofollow">State 3</a> <br /></p>
<p>Sorry for the long post.</p>
| 0 | 1,239 |
OnCheckedChanged event not firing
|
<p>I have a GridView with a column of checkboxes (the rest of the GridView is being populated from a database). I'm using AJAX to perform different functions, and I'm wondering if i'm just not calling the OnCheckedChanged event in the right place. Should it be wrapped in some sort of UpdatePanel? I'm still really new to how all of this works...basically what I'm aiming for is to change a bit value in my database when a checkbox is checked. I know the logic of how to do that, I just don't know if I'm addressing my OnCheckedChanged event the right way.</p>
<p>.CS</p>
<pre><code> protected void CheckBoxProcess_OnCheckedChanged(Object sender, EventArgs args)
{
CheckBox checkbox = (CheckBox)sender;
GridViewRow row = (GridViewRow)checkbox.NamingContainer;
OrderBrowser.Text += "CHANGED";
}
}
</code></pre>
<p>.aspx</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
</code></pre>
<p>
</p>
<pre><code> <asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
<asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
<asp:ListItem Value="lName">Last Name</asp:ListItem>
<asp:ListItem Value="state">State</asp:ListItem>
<asp:ListItem Value="zip">Zip Code</asp:ListItem>
<asp:ListItem Value="cwaSource">Source</asp:ListItem>
<asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label runat="server" ID="searchLabel" Text="Search For: " />
<asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
<asp:Button ID="searchButton" runat="server" Text="Search" />
</div>
<div>
<asp:UpdatePanel ID = "up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "orderByList"
EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlId="searchButton" EventName="Click" />
</Triggers>
<ContentTemplate>
<div align="center">
<asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "fName"
onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
autogenerateselectbutton = "true"
selectedindex="0">
<SelectedRowStyle BackColor="Azure"
forecolor="Black"
font-bold="true" />
<Columns>
<asp:TemplateField HeaderText="Processed">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" runat="server" Enabled="true" OnCheckedChanged = "CheckBoxProcess_OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:TextBox ID="OrderBrowser" columns="100" Rows="14" runat="server" Wrap="false" TextMode="MultiLine" ReadOnly = "true">
</asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</code></pre>
<p>
</p>
| 0 | 1,390 |
Why is ASP.NET throwing so many exceptions?
|
<p>By coincidence I watched the debug output of Visual Studio a bit. I can see hundreds and hundreds of various exceptions being thrown. I checked another ASP.NET based solution and it is showing same behavior. Why are all those exceptions thrown? I cannot believe it is good for the overall performance, is it?
Look at the excerpt below. It is the output of appr. 30 seconds surfing. Most are HttpExceptions but there are also FormatExceptions and ArgumentOutOfRangeExceptions. None of these is really affecting the usage. Nothing crashes. Does anybody have an explanation, as it seems to be "normal"?</p>
<pre><code>A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
'w3wp.exe' (Managed): Loaded 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\a402e511\e6aaa0de\App_Web_vdj_eurz.dll', Symbols loaded.
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.InvalidCastException' occurred in mscorlib.dll
A first chance exception of type 'System.InvalidCastException' occurred in mscorlib.dll
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
</code></pre>
| 0 | 1,372 |
Radio box, get the checked value [iCheck]
|
<p>Basic radio box</p>
<pre><code><div class="adv_filter">
<li>
<input type="radio" name="letter_type" data-custom="Text" value="0"> Text</li>
</li>
<li>
<input type="radio" name="letter_type" data-custom="Text" value="0"> Text</li>
</li>
</div>
</code></pre>
<p>iCheck transformation</p>
<pre><code><!-- iCheck output format
<div class="adv_filter">
<li>
<div class="iradio_square-orange checked" aria-checked="true" aria-disabled="false" style="position: relative;"><input type="radio" name="letter_type" data-custom="Text" value="0" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; border: 0px; opacity: 0; background: rgb(255, 255, 255);"><ins class="iCheck-helper" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; border: 0px; opacity: 0; background: rgb(255, 255, 255);"></ins></div> Text</li>
<li>
<div class="iradio_square-orange" aria-checked="false" aria-disabled="false" style="position: relative;"><input type="radio" name="letter_type" data-custom="Text" value="0" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; border: 0px; opacity: 0; background: rgb(255, 255, 255);"><ins class="iCheck-helper" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; border: 0px; opacity: 0; background: rgb(255, 255, 255);"></ins></div> Text</li>
</div> -->
</code></pre>
<p><strong><em>As you see the checked is attached to the div..</em></strong></p>
<pre><code> $(document).ready(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-orange',
radioClass: 'iradio_square-orange',
increaseArea: '20%' // optional
});
$("li").on("click", "input", function () {
var val = $(this).val();
//updateDataGrid(val);
alert(val);
});
});
</code></pre>
<p><strong>Question and description</strong> </p>
<p>Provided javascript code worked properly before adding the icheck plugin,
<em>I am wondering how to get the same result in the icheck plugin. Its simple, on radio click it stores the value in variable later its passed further to functions.</em> </p>
<p>Live example : <a href="http://jsfiddle.net/9ypwjvt4/">http://jsfiddle.net/9ypwjvt4/</a></p>
<p>iCheck : <a href="http://fronteed.com/iCheck/">http://fronteed.com/iCheck/</a></p>
| 0 | 1,150 |
How get <body> element from the html which one have as a string
|
<p>I have a stupid problem. An <code>jQuery.ajax</code> request return me a <strong>full HTML text</strong> as a string. I receive such response in an case of error on the server. The server give me an error description which I want to place inside of the corresponding place of my current page.</p>
<p>So now the question: I have a string contains full HTML document (which is not an XML!!! see <code><hr></code> element inside). I need to have for example only BODY part as a jQuery object. Then I could append it to the corresponding part of my page.</p>
<p>Here is an example of the string which I need to parse:</p>
<pre><code><html>
<head>
<title>The resource cannot be found.</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
// ...
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>The resource cannot be found.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>HTTP 404. The resource you are looking for ...bla bla....
<br><br>
<b> Requested URL: </b>/ImportBPImagesInfos/Repository.svc/GetFullProfilimageSw<br><br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
</font>
</body>
</html>
<!--
[HttpException]: A public action method &#39;....
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
</code></pre>
| 0 | 1,190 |
Chip Group OnCheckedChangeListener() not triggered
|
<p>I'm trying to make a recyclerview filter based ChipGroup & Chip</p>
<p><a href="https://i.stack.imgur.com/DltSi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DltSi.png" alt="enter image description here"></a></p>
<p>I'm use fragment on my app, so, the fragment who contain the RecyclerView contain a frameLayout who inflate the ChipGroup filter fragment </p>
<p>I'm trying to trigger a listener when the user unselect all chip inside ChipGroup (I've already put listener on chip for trigger when chip are checked by user)</p>
<p>I've already put some listener on chipgroup but no one are trigered </p>
<p>FilterFragment.java </p>
<pre><code>public class FilterFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public ChipGroup chipGroup;
// TODO: Rename and change types of parameters
public View.OnClickListener chipClickListener;
private OnFragmentInteractionListener mListener;
public FilterFragment() {
// Required empty public constructor
}
public static FilterFragment newInstance(View.OnClickListener
param1) {
CoachFilterFragment fragment = new CoachFilterFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_filter,
container, false);
this.chipGroup = view.findViewById(R.id.chipGroup);
for(Skill skill : ((MainActivity)getContext()).api.skills){
Chip chip = new Chip(getContext());
chip.setId(skill.getId());
chip.setText(skill.getName());
chip.setOnClickListener(chipClickListener);
chip.setCheckable(true);
chipGroup.addView(chip);
}
chipGroup.setOnCheckedChangeListener((chipGroup, id) -> {
Log.d("test","ok");
});
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
</code></pre>
<p>FilterFragment.xml </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Fragment.FilterFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.chip.ChipGroup
android:id="@+id/chipGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</com.google.android.material.chip.ChipGroup>
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
</code></pre>
<p>Someone have any idea why any listener are not triggered by my ChipGroup?Maybe I'm missing some parameter or something?</p>
| 0 | 1,488 |
Ios Xcode Message from debugger: Terminated due to memory issue
|
<p>I have an app with collection view and a cell within this collection view that redirects to external link. </p>
<p>Whenever that link opens the app crashs in the background and gives on the debugger: </p>
<blockquote>
<p>"Terminated due to memory issue". </p>
</blockquote>
<p>If I just press home button the app continues working just fine.</p>
<pre><code>if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) Portrait = NO;
else if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)) Portrait = YES;
else Portrait = [self getStatusBarOrientations];
if(indexPath.row == 4 && indexPath.section == 0)
{
NewsListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell4" forIndexPath:indexPath];
if ([languageID isEqualToString:@"1025"])
{
cell.title.text =[NSString stringWithFormat:@"جريدة اليوم %@", [self.pdfCoverDict valueForKey:@"PdfDate"]];
[cell.contentView setTransform:CGAffineTransformMakeScale(-1, 1)];
} else {
cell.title.text =[NSString stringWithFormat:@"Today's Edition %@", [self.pdfCoverDict valueForKey:@"PdfDate"]];
}
NSURL *imageUrl = [NSURL URLWithString:[self.pdfCoverDict valueForKey:@"CoverImage"]];
[cell.imageView sd_setImageWithURL:imageUrl];
cell.imageViewWidth.constant = Portrait ? 246 : 331;
cell.imageViewHeight.constant = Portrait ? 350 : 471;
return cell;
} else if(indexPath.row == 0) {
NewsListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
cell.title.text = [self.channelKeys objectAtIndex:indexPath.section];
cell.backView.hidden = [channelID isEqualToString:@"1"] ? (indexPath.section == 0 ? YES : NO) : YES;
if([languageID isEqualToString:@"1025"]) {
[cell.contentView setTransform:CGAffineTransformMakeScale(-1, 1)];
} else {
[cell.contentView setTransform:CGAffineTransformMakeScale(-1, 1)];
[cell.title setTransform:CGAffineTransformMakeScale(-1, 1)];
}
return cell;
} else {
NSInteger row;
if(indexPath.row != 1 && indexPath.row != 2 && indexPath.row != 3) {
row = indexPath.row - 2;
} else {
row = indexPath.row - 1;
}
NSMutableArray * articles = [self.channelArticles valueForKey:[self.channelKeys objectAtIndex:indexPath.section]];
// if(row < articles.count) {
NSString *articleImage = [[articles objectAtIndex:row] valueForKey:@"ArticleMedia"];
NSString *cellIdentifier;
NSString *articleLangID = [NSString stringWithFormat:@"%@", [[articles objectAtIndex:row] valueForKey:@"LanguageID"]];
if(indexPath.section == 0) {
switch (indexPath.row)
{
case 1:
if(![articleImage isEqualToString:@""]) cellIdentifier = @"Cell1";
else cellIdentifier = @"CellNoImg";
break;
case 2:
if(![articleImage isEqualToString:@""]) cellIdentifier = @"Cell2";
else cellIdentifier = @"CellNoImg";
break;
case 3:
if(![articleImage isEqualToString:@""]) cellIdentifier = @"Cell3";
else cellIdentifier = @"CellNoImg";
break;
case 5:
if(![articleImage isEqualToString:@""]) cellIdentifier = @"Cell5";
else cellIdentifier = @"CellNoImg";
break;
case 6:
if(![articleImage isEqualToString:@""]) cellIdentifier = @"Cell5";
else cellIdentifier = @"CellNoImg";
break;
default:
if(![articleImage isEqualToString:@""]) {
if([channelID isEqualToString:@"1"]) cellIdentifier = @"Cell6";
else cellIdentifier = @"Cell5";
} else {
cellIdentifier = @"CellNoImg";
}
break;
}
} else {
if(![articleImage isEqualToString:@""]) cellIdentifier = @"Cell5";
else cellIdentifier = @"CellNoImg";
}
NewsListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
if([[[articles objectAtIndex:row] valueForKey:@"LabelName"] isEqualToString:@""]) {
cell.labelNameHeight.constant = 0;
} else {
cell.labelNameHeight.constant = 21;
}
cell.labelName.text = [[articles objectAtIndex:row] valueForKey:@"LabelName"];
cell.title.text = [[articles objectAtIndex:row] valueForKey:@"MainHeadline"];
if(indexPath.row == 3 && indexPath.section == 0) {
if(![articleImage isEqualToString:@""]) cell.titleHeight.constant = [self lineCountForLabel:cell.title labelWidth:cell.frame.size.width - Portrait ? 254 : 337] * 35;
else cell.titleHeight.constant = [self lineCountForLabel:cell.title labelWidth:cell.frame.size.width - 10] * 35;
} else {
cell.titleHeight.constant = [self lineCountForLabel:cell.title labelWidth:cell.frame.size.width - 10] * 35;
}
NSString *authorTime = [self getAuthorTime:[articles objectAtIndex:row]];
if([authorTime isEqualToString:@""]) {
cell.authorTimeHeight.constant = 0;
} else {
cell.authorTimeHeight.constant = 21;
}
cell.authorTime.text = authorTime;
NSString *details = [[articles objectAtIndex:row] valueForKey:@"Introduction"];
cell.details.attributedText = [self getAttributedString: details language: articleLangID];
if([cellIdentifier isEqualToString:@"CellNoImg"]) {
defaultLines = 5;
if([cell.authorTime.text isEqualToString:@""]) defaultLines++;
if([cell.labelName.text isEqualToString:@""]) defaultLines++;
if(cell.titleHeight.constant / 35 == 1) defaultLines++;
cell.details.numberOfLines = defaultLines;
}
if(indexPath.section == 0) {
switch (indexPath.row)
{
case 2:
cell.imageViewWidth.constant = Portrait ? 240 : 323;
cell.imageViewHeight.constant = Portrait ? 151 : 199;
break;
case 3:
cell.imageViewWidth.constant = Portrait ? 240 : 323;
cell.imageViewHeight.constant = Portrait ? 151 : 199;
case 5:
cell.imageViewWidth.constant = Portrait ? 240 : 323;
cell.imageViewHeight.constant = Portrait ? 151 : 199;
break;
case 6:
cell.imageViewWidth.constant = Portrait ? 240 : 323;
cell.imageViewHeight.constant = Portrait ? 151 : 199;
break;
default:
cell.imageViewWidth.constant = Portrait ? 240 : 323;
cell.imageViewHeight.constant = Portrait ? 151 : 199;
break;
}
} else {
cell.imageViewWidth.constant = Portrait ? 240 : 323;
cell.imageViewHeight.constant = Portrait ? 151 : 199;
}
if (![articleImage isEqualToString:@""]) {
NSURL *imageUrl = [NSURL URLWithString:articleImage];
[cell.imageView sd_setImageWithURL:imageUrl];
} else {
[cell.imageView sd_setImageWithURL:nil];
}
if([articleLangID isEqualToString:@"1025"]) {
[cell.contentView setTransform:CGAffineTransformMakeScale(-1, 1)];
cell.labelName.textAlignment = NSTextAlignmentRight;
cell.title.textAlignment = NSTextAlignmentRight;
cell.authorTime.textAlignment = NSTextAlignmentRight;
cell.details.textAlignment = NSTextAlignmentRight;
} else {
if (indexPath.row == 3) {
[cell.contentView setTransform:CGAffineTransformMakeScale(-1, 1)];
[cell.labelName setTransform:CGAffineTransformMakeScale(-1, 1)];
[cell.title setTransform:CGAffineTransformMakeScale(-1, 1)];
[cell.authorTime setTransform:CGAffineTransformMakeScale(-1, 1)];
[cell.details setTransform:CGAffineTransformMakeScale(-1, 1)];
[cell.imageView setTransform:CGAffineTransformMakeScale(-1, 1)];
}
cell.labelName.textAlignment = NSTextAlignmentLeft;
cell.title.textAlignment = NSTextAlignmentLeft;
cell.authorTime.textAlignment = NSTextAlignmentLeft;
cell.details.textAlignment = NSTextAlignmentLeft;
}
return cell;
}
</code></pre>
<p>}</p>
| 0 | 3,668 |
Setting Classpath using command prompt in Windows 7
|
<p>I am compiling my code through Windows 7 using command prompt -- here are details :</p>
<p>I set the class path like this :</p>
<pre><code>set classpath= %classpath%;C:\java-programes\Servlet-Programing-new1\TotalUsersOnline\lib\servlet-api\*.jar;C:\java-programes\Servlet-Programing-new1\TotalUsersOnline\lib\servlet\*.jar;
</code></pre>
<p>and then I tried to compile my file like :</p>
<pre><code>javac -d ..\classe com\java\controller\LoginServlet.java
</code></pre>
<p>output:</p>
<pre><code>com\java\controller\LoginServlet.java:7: package javax.servlet does not exist
import javax.servlet.RequestDispatcher;
^
com\java\controller\LoginServlet.java:8: package javax.servlet does not exist
import javax.servlet.ServletException;
^
com\java\controller\LoginServlet.java:9: package javax.servlet.http does not exist
import javax.servlet.http.HttpServlet;
^
com\java\controller\LoginServlet.java:10: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletRequest;
^
com\java\controller\LoginServlet.java:11: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletResponse;
^
com\java\controller\LoginServlet.java:13: cannot find symbol
symbol: class HttpServlet
public class LoginServlet extends HttpServlet{
^
com\java\controller\LoginServlet.java:21: cannot find symbol
symbol : class HttpServletRequest
location: class com.java.controller.LoginServlet
public void service(HttpServletRequest request, HttpServletResponse response)
^
com\java\controller\LoginServlet.java:21: cannot find symbol
symbol : class HttpServletResponse
location: class com.java.controller.LoginServlet
public void service(HttpServletRequest request, HttpServletResponse response)
^
com\java\controller\LoginServlet.java:22: cannot find symbol
symbol : class ServletException
location: class com.java.controller.LoginServlet
throws ServletException, IOException {
^
com\java\controller\LoginServlet.java:46: cannot find symbol
symbol : class RequestDispatcher
location: class com.java.controller.LoginServlet
RequestDispatcher dispatcher = request.getRequestDispatcher("/home.jsp");
^
com\java\controller\LoginServlet.java:20: method does not override or implement a method from a supertype
@Override
</code></pre>
<p><strong>after that I tried like :</strong> </p>
<pre><code>javac -classpath C:\java-programes\Servlet-Programing-new1\TotalUsersOnline\lib\servlet-api\*.jar com\java\controller\LoginServlet.java
</code></pre>
<p><strong>then the output I got is :</strong> </p>
<pre><code>javac: invalid flag: C:\java-programes\Servlet-Programing-new1\TotalUsersOnline\lib\servlet-api\servlet-api-2.5.jar
Usage: javac <options> <source files>
use -help for a list of possible options
</code></pre>
<p>Please Help on this As I am stuck on this point and I am not getting anything..how to go forward.I need help badly :(</p>
<p>Thanks in Advance </p>
| 0 | 1,297 |
Bcrypt installation fails in Docker
|
<p>I've created a Node-application with MongoDB that runs in Docker. It worked fine until I included <a href="https://github.com/ncb000gt/node.bcrypt.js" rel="nofollow">node.bcrypt.js</a>. This makes Node crash with <code>node-gyp</code> and <code>bcrypt</code>.</p>
<p>The app runs fine locally and on Heroku.</p>
<p>I tried to install a few suggested packages that I found online, that were known to be needed based on error messages. This is why I've added a few extra dependencies, see the <code>node-gyp</code>-related line in the dockerfile below. </p>
<p>Now it's gotten where I cannot find any more suggestions, but it still doens't work. I feel it's weird that it works both locally and on Heorku, but not on Docker, and therefore that it's something I'm missing.</p>
<p>Thanks in advance.</p>
<p>Error:</p>
<pre><code>> crowdshelf-server@1.0.0 start /server
> node index.js
COPY Release/bcrypt_lib.node
make: Leaving directory `/server/node_modules/bcrypt/build'
module.js:338
throw err;
^
Error: Cannot find module './lib/topologies/server'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/server/node_modules/mongodb/node_modules/mongodb-core/index.js:3:13)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
npm ERR! Linux 3.13.0-58-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "start"
npm ERR! node v0.12.7
npm ERR! npm v2.11.3
npm ERR! code ELIFECYCLE
npm ERR! crowdshelf-server@1.0.0 start: `node index.js`
npm ERR! Exit status 1
</code></pre>
<p>This is after I added a few installations to my Dockerfile, see the line after <code>node-gyp</code>. Dockerfile:</p>
<pre><code># Base Docker-image on Ubuntu
FROM ubuntu:latest
#install mongodb
#install git, curl, python and mongo
# node-gyp
RUN apt-get install -y build-essential make automake gcc g++ cpp libkrb5-dev libc6-dev man-db autoconf pkg-config
# Create the MongoDB data directory
RUN mkdir -p /data/db
# mongodb setup
# Install NodeJS
RUN curl --silent --location https://deb.nodesource.com/setup_0.12 | sudo bash -
RUN apt-get update && apt-get install -y nodejs
RUN npm install -g node-gyp
# Git-clone project
# expose ports
# Install dependencies and start server and database
CMD cd /server && sh start.sh
</code></pre>
<p>The <code>starth.sh</code>-script simply installs dependencies and starts both MongoDB and server.</p>
<p><strong>EDIT:</strong>
The <a href="https://github.com/ncb000gt/node.bcrypt.js" rel="nofollow">repo</a> tells me to check out the <a href="https://github.com/nodejs/node-gyp" rel="nofollow">node-gyp dependencies</a>, but I feel that's been covered by the Dockerfile shown above.</p>
| 0 | 1,098 |
Error: StaticInjectorError(DynamicTestModule)[RouterLinkWithHref -> Router]: (NullInjectorError: No provider for Router!)
|
<p>I am preparing unit test case for AppComponent which have router as a injected dependency and have included RouterTestingModule in my test bed. But still getting a weird error. Please find the error log shown below:</p>
<pre><code>Error: StaticInjectorError(DynamicTestModule)[RouterLinkWithHref -> Router]:
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]:
NullInjectorError: No provider for Router!
</code></pre>
<blockquote>
<p>error properties: Object({ ngTempTokenPath: null, ngTokenPath: [
'RouterLinkWithHref', Function ], ngDebugContext: DebugContext_({
view: Object({ def: Object({ factory: Function, nodeFlags: 671753,
rootNodeFlags: 1, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({
nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0,
outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 671753,
directChildFlags: 1, childMatchedQueries: 0, matchedQueries: Object({
}), matchedQueryIds: 0, references: Object({ }), ngContentIndex:
null, childCount: 10, bindings: [ Object({ flags: 8, ns: '', name:
'className', nonMinifiedName: 'className', securityContext: 0, suffix:
undefined }) ], bindingFlags: 8, outputs: [ ], element: Object({ ns:
'', name: 'nav', attrs: [ Array ], template: null, componentProvider:
null, componentView: null, componentRendererType: null,
publicProviders: null({ }), allProviders: null({ }), handleEvent:
Function }), provider: null, text: null, query: null, ngContent: null
}), Object({ ... Error:
StaticInjectorError(DynamicTestModule)[RouterLinkWithHref -> Router]:
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]:
NullInjectorError: No provider for Router!
at NullInjector.get (webpack:///./node_modules/@angular/core/fesm5/core.js?:1360:19)
at resolveToken (webpack:///./node_modules/@angular/core/fesm5/core.js?:1598:24)
at tryResolveToken (webpack:///./node_modules/@angular/core/fesm5/core.js?:1542:16)
at StaticInjector.get (webpack:///./node_modules/@angular/core/fesm5/core.js?:1439:20)
at resolveToken (webpack:///./node_modules/@angular/core/fesm5/core.js?:1598:24)
at tryResolveToken (webpack:///./node_modules/@angular/core/fesm5/core.js?:1542:16)
at StaticInjector.get (webpack:///./node_modules/@angular/core/fesm5/core.js?:1439:20)
at resolveNgModuleDep (webpack:///./node_modules/@angular/core/fesm5/core.js?:8667:29)
at NgModuleRef_.get (webpack:///./node_modules/@angular/core/fesm5/core.js?:9355:16)
at resolveDep (webpack:///./node_modules/@angular/core/fesm5/core.js?:9720:45)</p>
</blockquote>
<p>Please help. I have already tried removing router links from my template.</p>
<pre><code>TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [
CoreModule.forRoot(),
RouterTestingModule.withRoutes(routes),
],
providers: [
{provide: APP_BASE_HREF, useValue: '/'},
]
}
</code></pre>
| 0 | 1,105 |
Silverlight Listbox Item Style
|
<p>How would one go about styling a listbox such that the selection has a different text color than the default view? I've looked at this in several ways and because the ContentPresenter lacks a Foreground property. </p>
<p>The default control template of the listbox provides several rectangles which one can use to adjust the highlight color. For example, with the default style a rectangle called BGColor3 has its opacity adjusted to get a highlight effect.</p>
<p>Here is the bulk of my control template: </p>
<pre><code><Grid>
<Rectangle x:Name="BGColor2" Fill="{StaticResource HoverBrush}" Stroke="Black" StrokeThickness="1" Opacity="0"/>
<Rectangle x:Name="BGColor3" Fill="{StaticResource ListboxHighlightBrush}" StrokeThickness="0" Opacity="0"/>
<Rectangle x:Name="BGColor" Stroke="Black" StrokeThickness="0" Opacity="0.2" Fill="{TemplateBinding Background}"/>
<Border Height="20">
<ContentPresenter HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" x:Name="contentPresenter" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
</Border>
<Rectangle Fill="Blue" Opacity="0.4" x:Name="FocusVisual" Stroke="#BF313131" Margin="1" StrokeThickness="1" StrokeDashArray="1 2" StrokeDashCap="Square" Visibility="Collapsed" />
<Rectangle x:Name="BorderRect" Stroke="Black" StrokeThickness="1" Opacity="0.3" />
</Grid>
</code></pre>
<p>In the selection Visual State, here is the gist:</p>
<pre><code><VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected"/>
<VisualState x:Name="Selected">
<Storyboard>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="BGColor2" Storyboard.TargetProperty="(UIElement.Opacity)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0.8"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</code></pre>
<p>What is evident is that BGColor2 the rectangle is being modified (opacity) so that the selected item has a background. Fair enough. Within this portion of the Storyboard, is there anyway to access either the ContentPresenter or something else similar and toggling the text foreground color?</p>
<p>Footnote: wouldn't it be much cleaner to simply have different templates versus visual state transitions?</p>
<p>---- added after first answer given ----</p>
<p>Using a TextBlock <em>almost</em> does the trick but what's interesting is that the transition for SelectedUnfocused does not appear to be enforced which is to say that implementing your solution works perfectly until a person mouses over a previously selected item then the text once again goes to black. </p>
<p>Here is my template:</p>
<pre><code><!-- ItemStyle brushes -->
<SolidColorBrush x:Key="BaseColorBrush" Color="White"/>
<SolidColorBrush x:Key="BaseColorBrushFaint" Color="#265B0000"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="#FFFFFFFF"/>
<SolidColorBrush x:Key="HoverBrush2" Color="#FF808000"/>
<LinearGradientBrush x:Key="HoverBrush" EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF406DC7" Offset="1"/>
<GradientStop Color="#FF002C83"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="ListboxHighlightBrush" EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF7CA8FF" Offset="1"/>
<GradientStop Color="#FF376FDC"/>
</LinearGradientBrush>
<SolidColorBrush x:Key="HyperlinkBrush" Color="#FFC8A1A1"/>
<!-- Search Listbox ItemStyle -->
<Style x:Key="ItemStyle" TargetType="ListBoxItem">
<Setter Property="Padding" Value="4"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Top"/>
<Setter Property="Background" Value="{StaticResource BaseColorBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource HoverBrush}"/>
<Setter Property="Foreground" Value="#FF333333"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="TabNavigation" Value="Local"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="BGColor3" Storyboard.TargetProperty="Opacity" Duration="0" To="1"/>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="BGColor" Storyboard.TargetProperty="(UIElement.Opacity)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0.3"/>
</DoubleAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)">
<EasingColorKeyFrame KeyTime="00:00:00" Value="White"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="(UIElement.Opacity)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0.55"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected"/>
<VisualState x:Name="Selected">
<Storyboard>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="BGColor2" Storyboard.TargetProperty="(UIElement.Opacity)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0.9"/>
</DoubleAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)">
<EasingColorKeyFrame KeyTime="00:00:00" Value="White"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="SelectedUnfocused">
<Storyboard>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="BGColor2" Storyboard.TargetProperty="(UIElement.Opacity)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0.9"/>
</DoubleAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)">
<EasingColorKeyFrame KeyTime="00:00:00" Value="#FFFFFFFF"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="FocusVisual" Storyboard.TargetProperty="Visibility" Duration="0">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<Visibility>Visible</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)">
<EasingColorKeyFrame KeyTime="00:00:00" Value="White"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Unfocused">
<Storyboard/>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle x:Name="BGColor2" Fill="{StaticResource HoverBrush}" Stroke="Black" StrokeThickness="0" Opacity="0"/>
<Rectangle x:Name="BGColor3" Fill="{StaticResource ListboxHighlightBrush}" StrokeThickness="0" Opacity="0"/>
<Rectangle x:Name="BGColor" Stroke="Black" StrokeThickness="0" Opacity="0.3" Fill="{TemplateBinding Background}"/>
<Border Height="20">
<TextBlock Canvas.ZIndex="22" x:Name="contentPresenter" Foreground="{TemplateBinding Foreground}"
Text="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding
HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" />
</Border>
<Rectangle Opacity="0.4" x:Name="FocusVisual" Stroke="#BF313131" Margin="1" StrokeThickness="1" StrokeDashArray="1 2" StrokeDashCap="Square" Visibility="Collapsed" />
<Rectangle x:Name="BorderRect" Stroke="Black" StrokeThickness="0" Opacity="0.3" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>And my consumption of the template:</p>
<pre><code> <ListBox ItemContainerStyle="{StaticResource ItemStyle}" x:Name="testListBox" />
</code></pre>
<p>And finally some code to populate the listbox:</p>
<pre><code> List<string> data = new List<string>();
for (int i = 0; i < 30; i++) {
data.Add(DateTime.Now.AddDays(i).ToString("MMMM dd yyyy"));
}
testListBox.ItemsSource = data;
</code></pre>
| 0 | 5,979 |
Having a div/0 error in excel 2007 return a 0 with in a large formula
|
<p>I apologize if this is not considered real programming since it is in Excel but I need help and this is the most helpful place I know!</p>
<p>Alright so I have a very large if formula in excel:</p>
<pre><code>=IF(AND(($EZ16+LF$1139)>$B$1145,($EZ16+LF$1139)<$B$1146),IF(OR(AND($FB16<LF$1141,$FB16>LF$1142),AND($FE16<LF$1141,$FE16>LF$1142),AND($FH16<LF$1141,$FH16>LF$1142),AND($FK16<LF$1141,$FK16>LF$1142),AND($FN16<LF$1141,$FN16>LF$1142),AND($FQ16<LF$1141,$FQ16>LF$1142),AND($FT16<LF$1141,$FT16>LF$1142),AND($FW16<LF$1141,$FW16>LF$1142),AND($FZ16<LF$1141,$FZ16>LF$1142),AND($GC16<LF$1141,$GC16>LF$1142),AND($GF16<LF$1141,$GF16>LF$1142)),FALSE,(EU16/EI16-1)),FALSE)
</code></pre>
<p>What can I do to it so that if it returns a div/0 error it will pass a value of 0 instead of the <code>#DIV/0!</code> error?</p>
<p>Would it be something like:</p>
<pre><code>=IF(ISERROR(A1/B1),0,A1/B1)
</code></pre>
<p>If so how can I add that to my current formula and not break it? Would it be:</p>
<pre><code>=IF(ISERROR(IF(AND(($EZ16+LF$1139)>$B$1145,($EZ16+LF$1139)<$B$1146),IF(OR(AND($FB16<LF$1141,$FB16>LF$1142),AND($FE16<LF$1141,$FE16>LF$1142),AND($FH16<LF$1141,$FH16>LF$1142),AND($FK16<LF$1141,$FK16>LF$1142),AND($FN16<LF$1141,$FN16>LF$1142),AND($FQ16<LF$1141,$FQ16>LF$1142),AND($FT16<LF$1141,$FT16>LF$1142),AND($FW16<LF$1141,$FW16>LF$1142),AND($FZ16<LF$1141,$FZ16>LF$1142),AND($GC16<LF$1141,$GC16>LF$1142),AND($GF16<LF$1141,$GF16>LF$1142)),FALSE,(EU16/EI16-1)),FALSE))**),0,IF**(AND(($EZ16+LF$1139)>$B$1145,($EZ16+LF$1139)<$B$1146),IF(OR(AND($FB16<LF$1141,$FB16>LF$1142),AND($FE16<LF$1141,$FE16>LF$1142),AND($FH16<LF$1141,$FH16>LF$1142),AND($FK16<LF$1141,$FK16>LF$1142),AND($FN16<LF$1141,$FN16>LF$1142),AND($FQ16<LF$1141,$FQ16>LF$1142),AND($FT16<LF$1141,$FT16>LF$1142),AND($FW16<LF$1141,$FW16>LF$1142),AND($FZ16<LF$1141,$FZ16>LF$1142),AND($GC16<LF$1141,$GC16>LF$1142),AND($GF16<LF$1141,$GF16>LF$1142)),FALSE,(EU16/EI16-1)),FALSE))
</code></pre>
<p>Thank you for the help!</p>
<p>EDIT:
Tim a tried your suggestion:</p>
<pre><code>=IF(AND(($EZ16+LF$1139)>$B$1145,($EZ16+LF$1139)<$B$1146),IF(OR(AND($FB16<LF$1141,$FB16>LF$1142),AND($FE16<LF$1141,$FE16>LF$1142),AND($FH16<LF$1141,$FH16>LF$1142),AND($FK16<LF$1141,$FK16>LF$1142),AND($FN16<LF$1141,$FN16>LF$1142),AND($FQ16<LF$1141,$FQ16>LF$1142),AND($FT16<LF$1141,$FT16>LF$1142),AND($FW16<LF$1141,$FW16>LF$1142),AND($FZ16<LF$1141,$FZ16>LF$1142),AND($GC16<LF$1141,$GC16>LF$1142),AND($GF16<LF$1141,$GF16>LF$1142)),FALSE,IF(EI16=1,0,EU16/EI16-1)),FALSE)
</code></pre>
<p>Still getting a <code>#DIV/0</code> error, any idea why?</p>
| 0 | 1,685 |
ValueError: failed to parse CPython sys.version after using conda command
|
<p>I'm running into an error that I can't solve despite others having reported the same error.</p>
<p>I am connecting remotely to a Linux machine. I have installed the latest version of anaconda:</p>
<pre><code>$ bash Anaconda2-2.4.0-Linux-x86_64.sh
// A lot of python libraries get installed
installing: _cache-0.0-py27_x0 ...
Python 2.7.10 :: Continuum Analytics, Inc.
creating default environment...
installation finished.
</code></pre>
<p>I updated the corresponding paths and it seems like it works:</p>
<pre><code>$ python
Python 2.7.10 |Anaconda 2.4.0 (64-bit)| (default, Oct 19 2015, 18:04:42)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
</code></pre>
<p>Great, so now I want to use <code>conda</code>, which is pre-installed with Anaconda. It looks like Anaconda gave me 3.18.3:</p>
<pre><code>$ conda --version
conda 3.18.3
</code></pre>
<p>Following the <a href="http://conda.pydata.org/docs/test-drive.html" rel="noreferrer">test drive instructions</a>, I update conda:</p>
<pre><code>$ conda update conda
Fetching package metadata: An unexpected error has occurred, please consider sending the
following traceback to the conda GitHub issue tracker at:
https://github.com/conda/conda/issues
Include the output of the command 'conda info' in your report.
Traceback (most recent call last):
File "/code/anaconda2-4-0/bin/conda", line 5, in <module>
sys.exit(main())
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/cli/main.py", line 195, in main
args_func(args, p)
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/cli/main.py", line 202, in args_func
args.func(args, p)
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/cli/main_update.py", line 48, in execute
install.install(args, parser, 'update')
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/cli/install.py", line 239, in install
offline=args.offline)
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/cli/common.py", line 598, in get_index_trap
return get_index(*args, **kwargs)
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/api.py", line 42, in get_index
unknown=unknown)
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/utils.py", line 119, in __call__
value = self.func(*args, **kw)
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/fetch.py", line 237, in fetch_index
session = CondaSession()
File "/code/anaconda2-4-0/lib/python2.7/site-packages/conda/connection.py", line 61, in __init__
super(CondaSession, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 272, in __init__
self.headers = default_headers()
File "/usr/lib/python2.7/dist-packages/requests/utils.py", line 555, in default_headers
'User-Agent': default_user_agent(),
File "/usr/lib/python2.7/dist-packages/requests/utils.py", line 524, in default_user_agent
_implementation = platform.python_implementation()
File "/usr/lib/python2.7/platform.py", line 1521, in python_implementation
return _sys_version()[0]
File "/usr/lib/python2.7/platform.py", line 1486, in _sys_version
repr(sys_version))
ValueError: failed to parse CPython sys.version: '2.7.10 |Anaconda 2.4.0 (64-bit)| (default, Oct 19 2015, 18:04:42) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]'
</code></pre>
<p>Unfortunately, I can't figure out how to avoid this error.</p>
<p>I found a few other StackOverflow posts. <a href="https://stackoverflow.com/questions/30448687/pycharm-valueerror-failed-to-parse-cpython-sys-version">This one</a> suggests reinstalling python and pycharm from scratch (but I just installed Anaconda and I don't use pycharm). <a href="https://stackoverflow.com/questions/31304636/installing-modules-with-pip-failed-to-parse-cpython-sys-version">Another suggests</a> reinstalling canopy, but I'm not using that here. Finally, <a href="https://stackoverflow.com/questions/19105255/praw-failed-to-parse-cpython-sys-version-when-creating-reddit-object">a third suggests</a> that it's actually a bug, and proposes a fix. Unfortunately, re-naming <code>sys.version</code> fails to resolve the error. This isn't even my computer so I don't want to get deep into the code and risk messing something up.</p>
<p>I would appreciate some thoughts or advice.</p>
| 0 | 1,637 |
android.content.Context.getContentResolver()' on a null object reference
|
<p>I can't seem work out why I am getting a null pointer on this?</p>
<p>This is my AsyncTask that I call to grab the data. It passes it to a JSON Parser and an array of Objects is returned. This is then passed to my DBHelper where it was passing to my database through a ContentResolver.... </p>
<pre><code>public class getFilms extends AsyncTask<String, Void, Void> {
public int LIMIT_FILMS = 10;
String KEY = "apikey";
String LIMIT = "limit";
private static final String URL = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?";
private static final String API_KEY = "******************";
ArrayList<HashMap<String, String>> filmArrayList = new ArrayList<HashMap<String, String>>();
Context mContext;
@Override
protected Void doInBackground(String... params) {
Uri RottenUrl = Uri.parse(URL).buildUpon()
.appendQueryParameter(KEY, API_KEY)
.appendQueryParameter(LIMIT, Integer.toString(LIMIT_FILMS))
.build();
JSONParser jParser = new JSONParser();
Film[] json = jParser.getJSONFromUrl(RottenUrl.toString());
sortData(json);
return null;
}
public void sortData(Film[] jsonlist) {
DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);
dbHelper.deleteAll();
for (int i = 0; i < jsonlist.length; i++) {
dbHelper.contentAddFilm(jsonlist[i]);
}
}
}
</code></pre>
<p>This is my Database Helper</p>
<pre><code>public class DatabaseHelper extends SQLiteOpenHelper {
private ContentResolver myCR;
public DatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, FilmDataContract.DATABASE_NAME, factory, FilmDataContract.DATABASE_VERSION);
myCR = context.getContentResolver();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(FilmDataContract.FilmEntry.SQL_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(FilmDataContract.FilmEntry.DELETE_TABLE);
onCreate(db);
}
public void addFilm(Film film) {
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(FilmDataContract.TABLE_NAME,
null,
values);
db.close();
}
public Film getFilm(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(FilmDataContract.TABLE_NAME,
FilmDataContract.FilmEntry.COLUMNS,
"_id = ?",
new String[]{String.valueOf(id)},
null,
null,
null,
null);
if (cursor != null)
cursor.moveToFirst();
Film film = new Film();
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
return film;
}
public List<Film> getAllFilms() {
List<Film> films = new LinkedList<Film>();
String query = "SELECT * FROM " + FilmDataContract.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Film film = null;
if (cursor.moveToFirst()) {
do {
film = new Film();
film.setId(Integer.parseInt(cursor.getString(0)));
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
films.add(film);
} while (cursor.moveToNext());
}
return films;
}
public int updateFilm(Film film) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
int i = db.update(FilmDataContract.FilmEntry.TABLE_NAME,
values,
"_id+ = ?",
new String[]{String.valueOf(film.getId())});
db.close();
return i;
}
public int getFilmsCount() {
String countQuery = "SELECT * FROM " + FilmDataContract.FilmEntry.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public void deleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(FilmDataContract.FilmEntry.TABLE_NAME, null, null);
}
public boolean contentDelete(String filmName) {
boolean result = false;
String selection = "title = \"" + filmName + "\"";
int rowsDeleted = myCR.delete(FilmProvider.CONTENT_URI,
selection, null);
if (rowsDeleted > 0)
result = true;
return result;
}
public Film contentFindFilm(String filmName) {
String[] projection = FilmDataContract.FilmEntry.COLUMNS;
String selection = "title = \"" + filmName + "\"";
Cursor cursor = myCR.query(FilmProvider.CONTENT_URI,
projection, selection, null,
null);
Film film = new Film();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
film.setId(Integer.parseInt(cursor.getString(0)));
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
cursor.close();
} else {
film = null;
}
return film;
}
public void contentAddFilm(Film film) {
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
myCR.insert(FilmProvider.CONTENT_URI, values);
}
</code></pre>
<p>This is my stack trace... Seems to be happening when I am passing the context.</p>
<pre><code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
at com.purewowstudio.topmovies.data.DatabaseHelper.<init>(DatabaseHelper.java:25)
at com.purewowstudio.topmovies.util.getFilms.sortData(getFilms.java:48)
at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:43)
at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:16)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
</code></pre>
<p> at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
</p>
| 0 | 3,442 |
ASP.NET Validation not working
|
<p>I made a registration form , add to it some validation but they not being targeted/fired , am not sure what's wrong , also it seems to work fine on Internet Explore but not on firefox:</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
width: 143px;
text-align: right;
}
.auto-style3 {
width: 280px;
}
.auto-style4 {
font-size: x-large;
text-align: left;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="auto-style4">
Registeration</div>
<table class="auto-style1">
<tr>
<td class="auto-style2">Username:</td>
<td class="auto-style3">
<asp:TextBox ID="tbUserName" runat="server" Width="277px" MaxLength="16"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="tbUserName" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="tbUserName" ErrorMessage="4 - 16 Characters!" ForeColor="Red" MaximumValue="16" MinimumValue="4" Type="Integer"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Password:</td>
<td class="auto-style3">
<asp:TextBox ID="tbPassword" runat="server" Width="277px" MaxLength="16"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="tbPassword" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="tbPassword" ErrorMessage="4 - 16 Characters!" ForeColor="Red" MaximumValue="16" MinimumValue="4" Type="Integer"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Confirm Password:</td>
<td class="auto-style3">
<asp:TextBox ID="tbConfPassword" runat="server" Width="277px" MaxLength="16"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="tbConfPassword" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator3" runat="server" ControlToValidate="tbConfPassword" ErrorMessage="4 - 16 Characters!" ForeColor="Red" MaximumValue="16" MinimumValue="4" Type="Integer"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Email:</td>
<td class="auto-style3">
<asp:TextBox ID="tbEmail" runat="server" Width="277px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="tbEmail" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">First Name:</td>
<td class="auto-style3">
<asp:TextBox ID="tb1stName" runat="server" Width="277px" MaxLength="16"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="tb1stName" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator4" runat="server" ControlToValidate="tb1stName" ErrorMessage="4 - 16 Characters!" ForeColor="Red" MaximumValue="16" MinimumValue="4" Type="Integer"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Second Name:</td>
<td class="auto-style3">
<asp:TextBox ID="tb2ndName" runat="server" Width="277px" MaxLength="16"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="tb2ndName" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator5" runat="server" ControlToValidate="tb2ndName" ErrorMessage="4 - 16 Characters!" ForeColor="Red" MaximumValue="16" MinimumValue="4" Type="Integer"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Age:</td>
<td class="auto-style3">
<asp:TextBox ID="tbAge" runat="server" Width="277px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="tbAge" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Gender:</td>
<td class="auto-style3">
<asp:DropDownList ID="dlGender" runat="server" Width="277px">
<asp:ListItem Selected="True">Select Gender</asp:ListItem>
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ControlToValidate="dlGender" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Secret Question1:</td>
<td class="auto-style3">
<asp:DropDownList ID="dl1stQ" runat="server" Height="24px" Width="277px">
<asp:ListItem Selected="True">Select Question</asp:ListItem>
<asp:ListItem>What is your Favourite Car Manufacturer?</asp:ListItem>
<asp:ListItem>What is your Favourite Food?</asp:ListItem>
<asp:ListItem>What is your Favourite Video Game?</asp:ListItem>
<asp:ListItem>What is your Favourite Drink?</asp:ListItem>
<asp:ListItem>What is your Favourite Brand?</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ControlToValidate="dl1stQ" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Answer:</td>
<td class="auto-style3">
<asp:TextBox ID="tbAnswer" runat="server" Width="277px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server" ControlToValidate="tbAnswer" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Secret Question2:</td>
<td class="auto-style3">
<asp:DropDownList ID="dlQ2" runat="server" Height="16px" Width="277px">
<asp:ListItem Selected="True">Select Question</asp:ListItem>
<asp:ListItem>What is your Favourite Sports Team?</asp:ListItem>
<asp:ListItem>Who is your Favourite Singer?</asp:ListItem>
<asp:ListItem>Who is your Favourite Actor?</asp:ListItem>
<asp:ListItem>Who is your Favourite Actress?</asp:ListItem>
<asp:ListItem>Who is your favourite Sports Player?</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="dlQ2" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Answer:</td>
<td class="auto-style3">
<asp:TextBox ID="tbAnswer2" runat="server" Width="277px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" ControlToValidate="tbAnswer2" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Secret Question3:</td>
<td class="auto-style3">
<asp:DropDownList ID="dlQ3" runat="server" Width="277px">
<asp:ListItem Selected="True">Select Question</asp:ListItem>
<asp:ListItem>What is your mother Maiden Name?</asp:ListItem>
<asp:ListItem>Where were you born?</asp:ListItem>
<asp:ListItem>What was your first best friends Name?</asp:ListItem>
<asp:ListItem>Who was your first kiss?</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator13" runat="server" ControlToValidate="dlQ3" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Answer:</td>
<td class="auto-style3">
<asp:TextBox ID="tbAnswer3" runat="server" Width="277px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator14" runat="server" ControlToValidate="tbAnswer3" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
</form>
</body>
</html>
</code></pre>
| 0 | 6,587 |
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count
|
<p>I am getting this exception about commits and rollbacks but am not sure what exactly is wrong with my Stored Procedure. I have read the answers in other such questions and am unable to find where exactly the commit count is getting messed up.</p>
<p>So, this is the Stored Procedure I use:</p>
<pre><code>-- this is a procedure used for the purge utility. This procedure uses the parameters of a date and lets user select
-- if the leads that should be purge must be closed either before, on or since that date.
-- operator: 0-->less 1-->equal 2-->greater
-- @closed: closing date
-- leadscount: returns the count of leads deleted
IF OBJECT_ID ('LEAD_PURGE', 'P') IS NOT NULL
DROP PROCEDURE LEAD_PURGE
go
CREATE PROCEDURE LEAD_PURGE
@purgextns INT,
@leadscount INT OUTPUT
AS
BEGIN
BEGIN TRANSACTION
CREATE TABLE #ASSIGNMENTS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #MAPRESULTS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #COMMAND_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #PROGRESS_STATUS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #DETAILS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #NEEDS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
insert into #ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD);
SELECT @leadscount = (SELECT COUNT(*) FROM PURGE_LEAD);
INSERT INTO #MAPRESULTS_DELETED
SELECT ID FROM MAPRESULT WHERE ASSIGNMENTSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
INSERT INTO #COMMAND_DELETED
SELECT ID FROM EXECUTERULECOMMAND WHERE MAPRESULTID IN (SELECT ID FROM #MAPRESULTS_DELETED)
INSERT INTO #PROGRESS_STATUS_DELETED
SELECT PROGRESS_STATUS_ID FROM COMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
INSERT INTO #DETAILS_DELETED
SELECT DETAILID FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
INSERT INTO #NEEDS_DELETED
SELECT NEEDSID FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM PROGRESS_STATUS WHERE ID IN (SELECT ID FROM #PROGRESS_STATUS_DELETED)
DELETE FROM EXECUTERULECOMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
DELETE FROM COMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
DELETE FROM SIMPLECONDITIONAL WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM MAPPREDICATE WHERE ROWBP IN (SELECT ID FROM MAPROW WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED))
DELETE FROM MAPROW WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM MAPRESULT WHERE ID IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM ASSIGNMENTATTACHMENTS WHERE ASSIGNMENTSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM LEADOBSERVER WHERE ASSIGNSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM MAPDESTINATIONS WHERE SUGGESTEDASSIGNID IN
(SELECT ID FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM #ASSIGNMENTS_DELETED))
DELETE FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM PRODUCTINTEREST WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD)
CREATE TABLE #SALE_DELETED_EX
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
INSERT into #SALE_DELETED_EX SELECT SALEEXSEQ FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD))
DELETE FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD))
DELETE FROM SALEEXTENSIONS WHERE
SEQID IN (SELECT ID FROM #SALE_DELETED_EX)
DELETE FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM NOTES WHERE OBJECTID IN (SELECT ID FROM #NEEDS_DELETED) OR OBJECTID IN (SELECT ID FROM #DETAILS_DELETED)
DELETE FROM HISTORYRECORD WHERE OBJECTID IN (SELECT ID FROM #DETAILS_DELETED)
DELETE FROM DETAIL WHERE SEQID IN (SELECT ID FROM #NEEDS_DELETED UNION SELECT ID FROM #DETAILS_DELETED)
DELETE FROM MESSAGES WHERE PROVIDERID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
CREATE TABLE #PURGE_LEAD_E
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
INSERT into #PURGE_LEAD_E Select SEQID FROM LEADEXTENSIONS WHERE
SEQID NOT IN (SELECT LEADEXSEQ FROM LEAD)
if @purgextns = 1 begin
DELETE FROM LEADEXTENSIONS WHERE
SEQID IN (SELECT ID FROM PURGE_LEAD_E)
end
DELETE FROM PURGE_LEAD;
DROP TABLE #ASSIGNMENTS_DELETED
DROP TABLE #MAPRESULTS_DELETED
DROP TABLE #COMMAND_DELETED
DROP TABLE #PROGRESS_STATUS_DELETED
DROP TABLE #DETAILS_DELETED
DROP TABLE #NEEDS_DELETED
DROP TABLE #PURGE_LEAD_E
DROP TABLE #SALE_DELETED_EX
COMMIT
END
go
</code></pre>
<p>now I call this procedure in the following code:</p>
<pre><code> try {
c = new ConnectionHelper().getConnection();
String sql = "";
if (shouldPurgeExtns) {
progressModel.makeProgress("progress.deleting.dependents");
purgeMultiselect(c, LEAD, isMSSQL);
}
sql = "{CALL " + TOPLinkManager.getSchemaPrefix()
+ "LEAD_PURGE (?,?)}";
cs = c.prepareCall(sql);
cs.setInt(1, shouldPurgeExtns ? 0 : 1);
cs.registerOutParameter(2, java.sql.Types.INTEGER);
cs.executeUpdate();
int rowcount = cs.getInt(2);
cs.close();
progressModel.makeProgress("progress.recording.history");
recordHistory(c, isMSSQL, LEAD, DateTypeDecorator.CLOSED, date,
rowcount);
done(progressModel);
c.close();
return true;
} catch (Exception e) {
Logs.main.error("Error Purging Leads", e);
throw new Exception(e.getMessage());
}
</code></pre>
<p>And I get an exception on the line which say <code>int rowcount = cs.getInt(2);</code></p>
<p>The Exception is:</p>
<pre><code>com.microsoft.sqlserver.jdbc.SQLServerException: Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.processResults(SQLServerStatement.java:1083)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getOutParameter(SQLServerCallableStatement.java:112)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getterGetParam(SQLServerCallableStatement.java:387)
</code></pre>
<p>Please help me out.
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getValue(SQLServerCallableStatement.java:393)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getInt(SQLServerCallableStatement.java:437)
at marketsoft.tools.purge.PurgeUtils.PurgeLeads(PurgeUtils.java:283)</p>
<p><strong>EDIT:</strong></p>
<p>as I have answered this question myself... I would like to change the question a bit now.</p>
<p><strong>Why was no exception thrown in the execute method???</strong></p>
| 0 | 2,774 |
Yii and .htaccess file on production server
|
<p>I am new to yii and have some problem in configuring .htaccess file on production server.</p>
<p><strong>On localhost :</strong> </p>
<p><strong>Location of Application :</strong> /www/connect_donors/</p>
<p><strong>Default URL that yii provides is</strong>,</p>
<pre><code>http://localhost/connect_donors/index.php?r=controllerId/functionName
</code></pre>
<p>We used the urlManager in /connect_donors/protected/config/main.php to configure the SEO friendly url's..</p>
<pre><code>'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>'
</code></pre>
<p>Now the URL that was working was</p>
<pre><code>http://localhost/connect_donors/index.php/controllerId/functionName
</code></pre>
<p>Then I used the .htaccess file to remove index.php from the above URL.</p>
<p>Location of .htaccess is : /connect_donors/.htaccess</p>
<p>Following is .htaccess file,</p>
<pre><code>RewriteEngine On
RewriteBase /connect_donors
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php/$1 [L,QSA]
</code></pre>
<p><strong>URL Chenged to :</strong> </p>
<pre><code>http://localhost/connect_donors/controllerId/functionName
</code></pre>
<p>Everything working fine and awesome.</p>
<p>But yesterday I uploaded the application on production server.</p>
<p><strong>On Production Server</strong></p>
<p>Everything remained same only I had to change the .htaccess file.</p>
<p>The .htaccess file on server is,</p>
<pre><code>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php/$1 [L,QSA]
</code></pre>
<p>Now the following url:</p>
<pre><code>http://donorsconnect.com/
</code></pre>
<p>loads the home page of server properly.</p>
<p>But,
<a href="http://donorsconnect.com/profile" rel="nofollow">http://donorsconnect.com/profile</a> </p>
<p>redirects again to home page.</p>
<p>NOTE : There is no session set on the "profile" controller.</p>
<pre><code>class ProfileController extends CController
{
public function actionIndex()
{
$this->render('index');
}
}
</code></pre>
<p>I tried lot of things, changing the .htaccess file to different codes. but none helped me.</p>
<p>Any help is appreciable.</p>
<p><strong>Solution</strong></p>
<p>I finally got the solution and the mistake I had done.</p>
<p>My Components had a request array containing baseUrl.</p>
<pre><code>'components'=>array(
...
'request' => array(
'baseUrl' => 'http://donorsconnect.com',
...),
</code></pre>
<p>Due to this it was not loading. I did not find the real reason for that.</p>
<p>But after removing that 'request' array, its loading fine.</p>
<p>Check link,
<a href="http://donorsconnect.com/profile" rel="nofollow">http://donorsconnect.com/profile</a></p>
| 0 | 1,168 |
Copy Sqlite database for android application
|
<p>I am trying to use my own created database in my android application using this tutorial <a href="http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/" rel="nofollow noreferrer">http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/</a></p>
<p>I have my database in my assets folder have been working for 5 hours to get the work around but in vain.. i always keep getting</p>
<pre><code>01-17 04:09:07.111: E/Database(1060): sqlite3_open_v2("/data/data/com.rahul.besttracker/databases/route", &handle, 1, NULL) failed
</code></pre>
<p>and</p>
<pre><code>01-17 04:09:07.271: E/AndroidRuntime(1060): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rahul.besttracker/com.rahul.besttracker.Busdisplay}: android.database.sqlite.SQLiteException: unable to open database file
</code></pre>
<p>my code</p>
<pre class="lang-java prettyprint-override"><code>public class Busdisplay extends ListActivity {
TextView source, destination;
String src, dest;
ArrayList<String> mArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
init();
Bundle caught = getIntent().getExtras();
src = caught.getString("source");
dest = caught.getString("dest");
DataBaseHelper entry = null;
entry = new DataBaseHelper(Busdisplay.this);
entry.openDataBase();
mArrayList = entry.readEntry(src, dest);
entry.close();
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mArrayList));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
void init() {
source = (TextView) findViewById(R.id.textView1);
destination = (TextView) findViewById(R.id.textView2);
}
}
</code></pre>
<p>My DBhelper class</p>
<pre class="lang-java prettyprint-override"><code>public class DataBaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static final String DB_PATH = "/data/data/com.rahul.besttracker/databases/";
private static final String DB_NAME = "route.db";
private static final String DB_TABLE1 = "route1";
private static final String DB_TABLE2 = "route2";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
System.out.print("ERROR");
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE1);
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE2);
onCreate(db);
}
public ArrayList<String> readEntry(String src, String dest) {
// TODO Auto-generated method stub
Cursor c = myDataBase.rawQuery("SELECT route_no from " + DB_TABLE1
+ " WHERE stops LIKE '%" + src + "%,%" + dest + "%';", null);
ArrayList<String> mArrayList = new ArrayList<String>();
int index = c.getColumnIndex("route_no");
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
// The Cursor is now set to the right position
mArrayList.add(c.getString(index));
}
return mArrayList;
}
// Add your public helper methods to access and get content from the
// database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd
// be easy
// to you to create adapters for your views.
}
</code></pre>
| 0 | 2,895 |
How can I disable code signing for debug builds in Visual Studio 2013?
|
<p>We recently upgraded Visual Studio from 2010 to 2013 and everything seems to be working the same as before except for one thing. In 2010 code signing was only performed when publishing the project, but in 2013 it wants to sign the output assembly every time we build the project.</p>
<p>I'm having issues trying to find any results online about this, everything only points to how to setup signing in the first place, not how to prevent it signing during normal debug builds.</p>
<hr>
<p>I created a new project and started playing with the settings to determine what single setting may be triggering the signing requirement during normal builds. In the project properties page under the Security tab, if the "Enable ClickOnce security settings" check box is checked then 2013 requires the signing step but 2010 doesn't seem to have that requirement.</p>
<p>I still need to confirm whether or not this is the single decision point for this behavior.</p>
<hr>
<p>Confirmed.</p>
<p>I created two solutions each with a single empty WinForms application. One solution was created in Visual Studio 2010 and the other was created in Visual Studio 2013. I went into the project properties on each and enabled signing via the signing tab and then checked the "Enable ClickOnce security settings" in the security tab with "This is a full trust application". Note that the projects are being signed with a certificate on a smart-card which is PIN enabled.</p>
<p>VS 2013 prompts for the smart card PIN during a normal build in debug mode, 2010 does not. Now the question is basically why there is a difference between the two versions and how to fix this in 2013 to behave like 2010.</p>
<hr>
<p>I'm including the project files for the test solutions I created below. Comparing the differences doesn't point to anything obviously different. I also attempted to change the VS 2013 project to target the same framework as the VS 2010 project to minimize the differences between the projects - this doesn't change the behavior difference.</p>
<p>Visual Studio 2010 Project File</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{E31DA60C-E444-4E34-AF6D-5B4588CC1F8E}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SigningTest1</RootNamespace>
<AssemblyName>SigningTest1</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignManifests>true</SignManifests>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>22E252B5076264F4F2CD88983A9053D554CCD185</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<TargetZone>LocalIntranet</TargetZone>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>true</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\app.manifest" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
</code></pre>
<p>Visual Studio 2013 Project File</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{732A657C-452D-4942-8832-89A14314739C}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SigningTest2013</RootNamespace>
<AssemblyName>SigningTest2013</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignManifests>true</SignManifests>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>22E252B5076264F4F2CD88983A9053D554CCD185</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<TargetZone>LocalIntranet</TargetZone>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>true</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="Properties\app.manifest" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
</code></pre>
<p>I'll attempt to upload a full solution for each when I can. I'm unable to do it from my current computer due to most file sharing websites being blocked.</p>
| 0 | 4,874 |
JUNIT test case for connection with database
|
<p><strong>This is the code which im testing for JDBC connection</strong></p>
<pre><code>package com.sybase;
public class SybaseDBConnection {
public static Properties prop = null;
public static Connection getConnection(String databaseType) {
Connection conn = null;
// Properties prop = null;
String database = null;
String driver = null;
String url = null;
String user = null;
String password = null;
try {
// prop = new Properties();
// prop.load(SybaseDBConnection.class.getClassLoader()
// .getResourceAsStream("com/properties/sybase.properties"));
database = prop.getProperty("sybase." + databaseType
+ ".databaseName");
driver = prop.getProperty("sybase." + databaseType
+ ".driverClassName");
url = prop.getProperty("sybase." + databaseType + ".url");
user = prop.getProperty("sybase." + databaseType + ".username");
password = prop.getProperty("sybase." + databaseType + ".password");
// String dbConUrl =
// "jdbc:datadirect:sqlserver://nt64sl2003a.americas.progress.comsql2008;Port=1433;DatabaseName=test;User=test;Password=test;EnableBulkLoad=true;BulkLoadBatchSize="
// + JDBC_BATCH_SIZE;
String dbConUrl = url + SEMI_COLLAN + "DatabaseName=" + database
+ SEMI_COLLAN + "User=" + user + SEMI_COLLAN + "Password="
+ password + SEMI_COLLAN + "EnableBulkLoad=true"
+ SEMI_COLLAN + "BulkLoadBatchSize=" + JDBC_BATCH_SIZE;
System.out.println("The URL is : " + dbConUrl);
SybDriver sybDriver = (SybDriver) Class.forName(driver)
.newInstance();
sybDriver.setVersion(com.sybase.jdbcx.SybDriver.VERSION_6);
DriverManager.registerDriver(sybDriver);
conn = DriverManager.getConnection(dbConUrl);
} catch (SQLException e) {
System.err.println("Exception occured : SQLException : "
+ e.getMessage());
e.printStackTrace();
} catch (InstantiationException e) {
System.err.println("Exception occured : InstantiationException : "
+ e.getMessage());
e.printStackTrace();
} catch (IllegalAccessException e) {
System.err.println("Exception occured : IllegalAccessException : "
+ e.getMessage());
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.err.println("Exception occured : ClassNotFoundException : "
+ e.getMessage());
e.printStackTrace();
}
return conn;
}
public static void closeConnection(Connection conn) {
try {
if (null != conn) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeResultset(ResultSet rs) {
try {
if (null != rs) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closePreparedStatement(PreparedStatement pstmt) {
try {
if (null != pstmt) {
pstmt.close();
pstmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeStatement(Statement stmt) {
try {
if (null != stmt) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static String getProperty(String property) {
return prop.getProperty(property);
}
public static void main(String args[]) {
SybaseDBConnection.getConnection("ase");
}
}
</code></pre>
<p><strong>I have written this test Case</strong></p>
<pre><code>public class SybaseStatementTest {
Connection conn;
Statement stmt;
// Setup methods
@BeforeClass
public void beforeClass() {
conn = null;
stmt = null;
}
// clean up method
@AfterClass
public void releaseResource() {
if (stmt != null) {
SybaseDBConnection.closeStatement(stmt);
}
if (conn != null) {
SybaseDBConnection.closeConnection(conn);
}
}
// Test case to check close statement using ASE database
@Before
public void openConnBeforerStmtTestASE() throws SQLException {
conn = SybaseDBConnection.getConnection("ase");
stmt = conn.createStatement();
}
@After
public void closeConnAfterStmtTestASE() {
if (conn != null) {
SybaseDBConnection.closeConnection(conn);
}
}
@Test
public void testCloseStatementASE() {
SybaseDBConnection.closeStatement(stmt);
Assert.assertNull("Error occured", stmt);
}
}
</code></pre>
<p><strong>I am getting an Initialization error(@BeforeClass should be static) when I run this Junit test case.
Please can you help?</strong> </p>
| 0 | 2,478 |
How to handle child click event in Expandablelistview in Android?
|
<p>I'm creating expandable list view in Android. I have add three textview in relative layout and two buttons in horizontal linear layout means this two buttons are added in one row, so how can I fire click event on those two buttons?</p>
<p>And I want to call another activity on button click in expandable list view. But I did not find any idea how to click on child in <code>ExpandableListView</code>.</p>
<p>Here is my XML file.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:padding="2dp" >
<TextView
android:id="@+id/TextView_Projectdetails"
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="@drawable/button_shape"
android:paddingLeft="10sp"
android:textColor="@android:color/black" />
<TextView
android:id="@+id/textOne"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_below="@+id/TextView_Projectdetails"
android:layout_marginTop="2dp"
android:background="@drawable/button_shape"
android:paddingLeft="10sp"
android:textColor="@android:color/black" >
</TextView>
<TextView
android:id="@+id/textTwo"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_below="@+id/textOne"
android:layout_marginTop="2dp"
android:background="@drawable/button_shape"
android:paddingLeft="10sp"
android:textColor="@android:color/black" >
</TextView>
<LinearLayout
android:id="@+id/linearlAYOUT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textTwo"
android:layout_marginTop="5dp"
android:orientation="horizontal" >
<Button
android:id="@+id/button_EditedTask"
android:layout_width="0dp"
android:layout_height="27dp"
android:layout_gravity="center"
android:layout_weight="1"
android:background="@drawable/button_shape_two"
android:gravity="center"
android:paddingBottom="3sp"
android:paddingTop="3sp"
android:text="ASSIGN TASK"
android:focusable="false"
android:textColor="@android:color/white"
android:textSize="12sp"
android:textStyle="normal" />
<Button
android:id="@+id/buttonViewTask"
android:layout_width="0dp"
android:layout_height="27dp"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginLeft="3dp"
android:layout_weight="1"
android:background="@drawable/button_shape_one"
android:gravity="center"
android:paddingBottom="3sp"
android:paddingTop="3sp"
android:text="VIEW TASK"
android:focusable="false"
android:textColor="@android:color/white"
android:textSize="12sp"
android:textStyle="normal" />
</LinearLayout>
</RelativeLayout>
</code></pre>
<p>List_Group xml file -</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:background="#000000">
<TextView
android:id="@+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="17dp"
android:textColor="#f9f93d" />
</LinearLayout>
</code></pre>
<p>here is my <code>ExpandableListAdapter</code> class -</p>
<pre><code>public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
Context context;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
public ExpandableListAdapter
(My_Project my_Project, List createGroupList,
int listGroup, String[] strings, int[] is, List createChildList,
int childItem, String[] strings2, int[] is2)
{
// TODO Auto-generated constructor stub
}
@Override
public Object getChild(int groupPosition, int childPosition)
{
//this.get(groupPosition).getChildren().get(childPosition);
String strchildPosition = this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition);
System.out.println("Child Position =" + strchildPosition);
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.TextView_Projectdetails);
TextView txtOneListChild = (TextView)convertView.findViewById(R.id.textOne);
TextView txtTwoListChild = (TextView)convertView.findViewById(R.id.textTwo);
txtListChild.setText(childText);
txtOneListChild.setText(childText);
txtTwoListChild.setText(childText);
Button btnAssgnTask = (Button)convertView.findViewById(R.id.button_EditedTask);
btnAssgnTask.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent i=new Intent(context,Assign_Task.class);
//StartElementListener()
}
});
Button btnViewTask = (Button)convertView.findViewById(R.id.buttonViewTask);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
@Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
@Override
public int getGroupCount() {
return this._listDataHeader.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
</code></pre>
<p>Here is my Activity code -</p>
<pre><code>public class My_Project extends ExpandableListActivity
{
expListView = (ExpandableListView) findViewById(android.R.id.list);
expListView.setOnGroupClickListener(new OnGroupClickListener()
{
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id)
{
return false;
}
});
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
dtrProjectNAmeSize.length + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
dtrProjectNAmeSize.length + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
expListView.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
int cp = (int) mAdapter.getChildId(groupPosition, childPosition);
if(cp == 3)
{
switch (cp)
{
case 3:
break;
}
}
return false;
}
});
mAdapter = new SimpleExpandableListAdapter(
this,
groupData,
R.layout.list_group,
new String[] { Project_Name },
new int[] {R.id.lblListHeader },
childData,
R.layout.child_item,
new String[] { Project_Date_Created , Project_End_Date , Project_Is_Active},
new int[] { R.id.TextView_Projectdetails , R.id.textOne , R.id.textTwo }
);
expListView.setAdapter(mAdapter);
}
}
</code></pre>
| 0 | 5,134 |
Scikit-learn - ValueError: Input contains NaN, infinity or a value too large for dtype('float32') with Random Forest
|
<p>First, I have checked the different posts concerning this error and none of them can solve my issue.</p>
<p>So I am using RandomForest and I am able to generate the forest and to do a prediction but sometimes during the generation of the forest, I get the following error.</p>
<blockquote>
<p>ValueError: Input contains NaN, infinity or a value too large for dtype('float32').</p>
</blockquote>
<p>This error occurs with the same dataset. Sometimes the dataset creates an error during the training and most of the time not. The error sometimes occurs at the start and sometimes in the middle of the training.</p>
<p>Here's my code :</p>
<pre><code>import pandas as pd
from sklearn import ensemble
import numpy as np
def azureml_main(dataframe1 = None, dataframe2 = None):
# Execution logic goes here
Input = dataframe1.values[:,:]
InputData = Input[:,:15]
InputTarget = Input[:,16:]
limitTrain = 2175
clf = ensemble.RandomForestClassifier(n_estimators = 10000, n_jobs = 4 );
features=np.empty([len(InputData),10])
j=0
for i in range (0,14):
if (i == 1 or i == 4 or i == 5 or i == 6 or i == 8 or i == 9 or i == 10 or i == 11 or i == 13 or i == 14):
features[:,j] = (InputData[:, i])
j += 1
clf.fit(features[:limitTrain,:],np.asarray(InputTarget[:limitTrain,1],dtype = np.float32))
res = clf.predict_proba(features[limitTrain+1:,:])
listreu = np.empty([len(res),5])
for i in range(len(res)):
if(res[i,0] > 0.5):
listreu[i,4] = 0;
elif(res[i,1] > 0.5):
listreu[i,4] = 1;
elif(res[i,2] > 0.5):
listreu[i,4] = 2;
else:
listreu[i,4] = 3;
listreu[:,0] = features[limitTrain+1:,0]
listreu[:,1] = InputData[limitTrain+1:,2]
listreu[:,2] = InputData[limitTrain+1:,3]
listreu[:,3] = features[limitTrain+1:,1]
# Return value must be of a sequence of pandas.DataFrame
return pd.DataFrame(listreu),
</code></pre>
<p>I ran my code locally and on <code>Azure ML</code> Studio and the error occurs in both cases.</p>
<p>I am sure that it is not due to my dataset since most of the time I don't get the error and I am generating the dataset myself from different input.</p>
<p>This is a <a href="http://%20https://pastebin.com/mC76uq8P" rel="nofollow noreferrer">part of the dataset I use</a></p>
<p><strong>EDIT:</strong> I probably found out that I had 0 value which were not real 0 value. The values were like</p>
<blockquote>
<p>3.0x10^-314</p>
</blockquote>
| 0 | 1,042 |
Selecting a subset of a Pandas DataFrame indexed by DatetimeIndex with a list of TimeStamps
|
<p>I have a large Pandas <code>DataFrame</code></p>
<pre><code><class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 3425100 entries, 2011-12-01 00:00:00 to 2011-12-31 23:59:59
Data columns:
sig_qual 3425100 non-null values
heave 3425100 non-null values
north 3425099 non-null values
west 3425097 non-null values
dtypes: float64(4)
</code></pre>
<p>I select a subset of that <code>DataFrame</code> using <code>.ix[start_datetime:end_datetime]</code> and I pass this to a <a href="https://gist.github.com/1178136" rel="nofollow noreferrer">peakdetect function</a> which returns the index and value of the local maxima and minima in two seperate lists. I extract the index position of the maxima and using <code>DataFrame.index</code> I get a list of pandas TimeStamps.</p>
<p>I then attempt to extract the relevant subset of the large DataFrame by passing the list of TimeStamps to <code>.ix[]</code> but it always seems to return an empty <code>DataFrame</code>. I can loop over the list of TimeStamps and get the relevant rows from the <code>DataFrame</code> but this is a lengthy process and I thought that <code>ix[]</code> should accept a list of values according to <a href="http://pandas.sourceforge.net/indexing.html" rel="nofollow noreferrer">the docs</a>?
<em>(Although I see that the example for Pandas 0.7 uses a <code>numpy.ndarray</code> of <code>numpy.datetime64</code>)</em></p>
<p><strong>Update:</strong>
A small 8 second subset of the DataFrame is selected below, # lines show some of the values:</p>
<pre><code>y = raw_disp['heave'].ix[datetime(2011,12,30,0,0,0):datetime(2011,12,30,0,0,8)]
#csv representation of y time-series
2011-12-30 00:00:00,-310.0
2011-12-30 00:00:01,-238.0
2011-12-30 00:00:01.500000,-114.0
2011-12-30 00:00:02.500000,60.0
2011-12-30 00:00:03,185.0
2011-12-30 00:00:04,259.0
2011-12-30 00:00:04.500000,231.0
2011-12-30 00:00:05.500000,139.0
2011-12-30 00:00:06.500000,55.0
2011-12-30 00:00:07,-49.0
2011-12-30 00:00:08,-144.0
index = y.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-12-30 00:00:00, ..., 2011-12-30 00:00:08]
Length: 11, Freq: None, Timezone: None
#_max returned from the peakdetect function, one local maxima for this 8 seconds period
_max = [[5, 259.0]]
indexes = [x[0] for x in _max]
#[5]
timestamps = [index[z] for z in indexes]
#[<Timestamp: 2011-12-30 00:00:04>]
print raw_disp.ix[timestamps]
#Empty DataFrame
#Columns: array([sig_qual, heave, north, west, extrema], dtype=object)
#Index: <class 'pandas.tseries.index.DatetimeIndex'>
#Length: 0, Freq: None, Timezone: None
for timestamp in timestamps:
print raw_disp.ix[timestamp]
#sig_qual 0
#heave 259
#north 27
#west 132
#extrema 0
#Name: 2011-12-30 00:00:04
</code></pre>
<p><strong>Update 2:</strong>
I <a href="https://gist.github.com/3377772" rel="nofollow noreferrer">created a gist</a>, which actually works because when the data is loaded in from csv the index columns of timestamps are stored as numpy array of objects which appear to be strings. Unlike in my own code where the index is of type <code><class 'pandas.tseries.index.DatetimeIndex'></code> and each element is of type <code><class 'pandas.lib.Timestamp'></code>, I thought passing a list of <code>pandas.lib.Timestamp</code> would work the same as passing individual timestamps, would this be considered a bug?</p>
<p>If I create the original <code>DataFrame</code> with the index as a list of strings, querying with a list of strings works fine. It does increase the byte size of the DataFrame significantly though.</p>
<p><strong>Update 3:</strong>
The error only appears to occur with very large DataFrames, I reran the code on varying sizes of DataFrame ( some detail in a comment below ) and it appears to occur on a DataFrame above 2.7 million records. Using strings as opposed to TimeStamps resolves the issue but increases memory usage.</p>
<p><strong>Fixed</strong>
In latest github master (18/09/2012), see comment from Wes at bottom of page.</p>
| 0 | 1,483 |
How to Add Columns to Jquery DataTable Dynamically
|
<p>I have a student Fee module, and I want to Generate Fee Class wise. Means Generate Fee for a whole Class, not for a Specific Student. <code>DataTable</code> will look like below..</p>
<pre><code>|RegistrationNo | Name | AdmissionFee | TutionFee | SportsFee | Exam Fee| Discount |
------------------------------------------------------------------------------------
| 50020 | A | 1000 | 800 | 500 | 400 | 300 |
| 50021 | B | 1000 | 800 | 500 | 400 | 100 |
</code></pre>
<p>so on, whole class...</p>
<p>The problem is that the <code>Fees</code> are defined by school, so i have not a fix number of fees, e.g <code>Transport Fee</code> can be defined, <code>Library Fee</code> can be defined and any other fee that school wants can define. so these Fee Names come from a <code>FeeDefination</code> Table. Now how i should add these Fees to <code>aoColumns</code> as attribute.
I have try the below code...</p>
<pre><code> var html = '[';
var oTable = $('#GenerateFeeDataTable').dataTable({
"bJQueryUI": true,
"bServerSide": true,
"bPaginate": false,
"bFilter": false,
"bInfo": false,
"sAjaxSource": "/forms/StudentFee/studentfee.aspx/GenerateStudentFee?CampusId=" + campusId + "&ClassId= " + classId + '&Session=' + JSON.stringify(session) + "&FeeModeId=" + feeModeId,
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"type": "GET",
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"url": sSource,
"data": aoData,
"success": function (data) {
var data = data.d;
html += '{"sTitle":"Registration No","mDataProp":"RegistrationNo","bSearchable":false,"bSortable":false},';
html += '{"sTitle":"Student Name","mDataProp":"StudentName","bSearchable":false,"bSortable":false},';
html = html.substring(0, html.length - 1);
html += ']';
fnCallback(data);
}
});
},
"aoColumns": html
});
</code></pre>
<p>How ever i have taken <code>aoColumns</code> attributes static in <code>fnServerData</code>, but these will not be fixed, i am just trying that i will work or not, but its not working..</p>
<pre><code>My Questions are :
1) How to handle this situation, means how to add aoColumns dynamically.
2) How to get Header/Variables Name from JSON aaData, below is the Image to understand.
</code></pre>
<p><img src="https://i.stack.imgur.com/pEdQl.png" alt="enter image description here"></p>
<p>Is there any way to do such task, Any Help..</p>
| 0 | 1,374 |
beautifulSoup html csv
|
<p>Good evening, I have used BeautifulSoup to extract some data from a website as follows:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
soup = BeautifulSoup(urlopen('http://www.fsa.gov.uk/about/media/facts/fines/2002'))
table = soup.findAll('table', attrs={ "class" : "table-horizontal-line"})
print table
</code></pre>
<p>This gives the following output:</p>
<pre><code>[<table width="70%" class="table-horizontal-line">
<tr>
<th>Amount</th>
<th>Company or person fined</th>
<th>Date</th>
<th>What was the fine for?</th>
<th>Compensation</th>
</tr>
<tr>
<td><a name="_Hlk74714257" id="_Hlk74714257">&#160;</a>£4,000,000</td>
<td><a href="/pages/library/communication/pr/2002/124.shtml">Credit Suisse First Boston International </a></td>
<td>19/12/02</td>
<td>Attempting to mislead the Japanese regulatory and tax authorities</td>
<td>&#160;</td>
</tr>
<tr>
<td>£750,000</td>
<td><a href="/pages/library/communication/pr/2002/123.shtml">Royal Bank of Scotland plc</a></td>
<td>17/12/02</td>
<td>Breaches of money laundering rules</td>
<td>&#160;</td>
</tr>
<tr>
<td>£1,000,000</td>
<td><a href="/pages/library/communication/pr/2002/118.shtml">Abbey Life Assurance Company ltd</a></td>
<td>04/12/02</td>
<td>Mortgage endowment mis-selling and other failings</td>
<td>Compensation estimated to be between £120 and £160 million</td>
</tr>
<tr>
<td>£1,350,000</td>
<td><a href="/pages/library/communication/pr/2002/087.shtml">Royal &#38; Sun Alliance Group</a></td>
<td>27/08/02</td>
<td>Pension review failings</td>
<td>Redress exceeding £32 million</td>
</tr>
<tr>
<td>£4,000</td>
<td><a href="/pubs/final/ft-inv-ins_7aug02.pdf" target="_blank">F T Investment &#38; Insurance Consultants</a></td>
<td>07/08/02</td>
<td>Pensions review failings</td>
<td>&#160;</td>
</tr>
<tr>
<td>£75,000</td>
<td><a href="/pubs/final/spe_18jun02.pdf" target="_blank">Seymour Pierce Ellis ltd</a></td>
<td>18/06/02</td>
<td>Breaches of FSA Principles ("skill, care and diligence" and "internal organization")</td>
<td>&#160;</td>
</tr>
<tr>
<td>£120,000</td>
<td><a href="/pages/library/communication/pr/2002/051.shtml">Ward Consultancy plc</a></td>
<td>14/05/02</td>
<td>Pension review failings</td>
<td>&#160;</td>
</tr>
<tr>
<td>£140,000</td>
<td><a href="/pages/library/communication/pr/2002/036.shtml">Shawlands Financial Services ltd</a> - formerly Frizzell Life &#38; Financial Planning ltd)</td>
<td>11/04/02</td>
<td>Record keeping and associated compliance breaches</td>
<td>&#160;</td>
</tr>
<tr>
<td>£5,000</td>
<td><a href="/pubs/final/woodwards_4apr02.pdf" target="_blank">Woodward's Independent Financial Advisers</a></td>
<td>04/04/02</td>
<td>Pensions review failings</td>
<td>&#160;</td>
</tr>
</table>]
</code></pre>
<p>I would like to export this into CSV whilst keeping the table structure as displayed on the website, is this possible and if so how?</p>
<p>Thanks in advance for the help.</p>
| 0 | 1,863 |
Windows Python2.7 mysqldb installation error
|
<p>I'm trying to install mysqldb for Python.
I'm running "pip install mysql-python"
and I keep getting this error:</p>
<p>running build_ext<br>
building '_mysql' extension<br>
creating build\temp.win32-2.7<br>
creating build\temp.win32-2.7\Release<br>
C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,2,5,'fi
nal',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\python27\include -Ic:\python27\PC /Tc_mysql.c /Fobui
ld\temp.win32-2.7\Release_mysql.obj /Zl
_mysql.c<br>
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory<br>
error: command 'C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe' failed with exit status 2</p>
<p>----------------------------------------<br>
Failed building wheel for mysql-python<br>
Failed to build mysql-python<br>
Installing collected packages: mysql-python<br>
Running setup.py install for mysql-python<br>
Complete output from command c:\python27\python.exe -c "import setuptools, tokenize;<strong>file</strong>='c:\users\scott~1.sco\appdata\local\temp\pip-bu
ild-nja4gr\mysql-python\setup.py';exec(compile(getattr(tokenize, 'open', open)(<strong>file</strong>).read().replace('\r\n', '\n'), <strong>file</strong>, 'exec'))" install -
-record c:\users\scott~1.sco\appdata\local\temp\pip-5htk1y-record\install-record.txt --single-version-externally-managed --compile:
running install<br>
running build<br>
running build_py<br>
copying MySQLdb\release.py -> build\lib.win32-2.7\MySQLdb<br>
running build_ext<br>
building '_mysql' extension<br>
C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,2,5,'
final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\python27\include -Ic:\python27\PC /Tc_mysql.c /Fob
uild\temp.win32-2.7\Release_mysql.obj /Zl
_mysql.c<br>
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory<br>
error: command 'C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe' failed with exit status 2</p>
<pre><code>----------------------------------------
</code></pre>
<p>Command "c:\python27\python.exe -c "import setuptools, tokenize;<strong>file</strong>='c:\users\scott~1.sco\appdata\local\temp\pip-build-nja4gr\mysql-python
\setup.py';exec(compile(getattr(tokenize, 'open', open)(<strong>file</strong>).read().replace('\r\n', '\n'), <strong>file</strong>, 'exec'))" install --record c:\users\scott~1
.sco\appdata\local\temp\pip-5htk1y-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\scott
~1.sco\appdata\local\temp\pip-build-nja4gr\mysql-python</p>
<p>Can anyone tell me whats the problem?</p>
| 0 | 1,177 |
"Class is Already defined" error
|
<p>I have listview app exploring cities each row point to diffrent city , in each city activity include button when clicked open new activity which is infinite gallery contains pics of that city , i add infinite gallery to first city and work fine , when i want to add it to the second city , it gave me red mark error in the class as follow :</p>
<p>1- The type InfiniteGalleryAdapter is already defined.</p>
<p>2-The type InfiniteGallery is already defined.</p>
<p>I tried to change class name with the same result, I delete R.java and eclipse rebuild it with same result. Also I unchecked the java builder from project properties and get same red mark error.</p>
<p>Please any help and advice will be appreciated</p>
<p>thanks</p>
<p>My Code:</p>
<pre><code>public class SecondCity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// Set the layout to use
setContentView(R.layout.main);
if (customTitleSupported) {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);
TextView tv = (TextView) findViewById(R.id.tv);
Typeface face=Typeface.createFromAsset(getAssets(),"BFantezy.ttf");
tv.setTypeface(face);
tv.setText("MY PICTURES");
}
InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne);
galleryOne.setAdapter(new InfiniteGalleryAdapter(this));
}
}
class InfiniteGalleryAdapter extends BaseAdapter {
**//red mark here (InfiniteGalleryAdapter)**
private Context mContext;
public InfiniteGalleryAdapter(Context c, int[] imageIds) {
this.mContext = c;
}
public int getCount() {
return Integer.MAX_VALUE;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
private LayoutInflater inflater=null;
public InfiniteGalleryAdapter(Context a) {
this.mContext = a;
inflater = (LayoutInflater)mContext.getSystemService ( Context.LAYOUT_INFLATER_SERVICE)
}
public class ViewHolder{
public TextView text;
public ImageView image;
}
private int[] images = {
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
R.drawable.pic_5
};
private String[] name = {
"This is first picture (1) " ,
"This is second picture (2)",
"This is third picture (3)",
"This is fourth picture (4)",
" This is fifth picture (5)"
};
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = getImageView();
int itemPos = (position % images.length);
try {
i.setImageResource(images[itemPos]); ((BitmapDrawable) i.getDrawable()).
setAntiAlias (true);
}
catch (OutOfMemoryError e) {
Log.e("InfiniteGalleryAdapter", "Out of memory creating imageview. Using empty view.", e);
}
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.gallery_items, null);
holder=new ViewHolder(); holder.text=(TextView)vi.findViewById(R.id.textView1);
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
} else {
holder=(ViewHolder)vi.getTag();
}
holder.text.setText(name[itemPos]);
final int stub_id=images[itemPos];
holder.image.setImageResource(stub_id);
return vi;
}
private ImageView getImageView() {
ImageView i = new ImageView(mContext);
return i;
}
}
class InfiniteGallery extends Gallery {
**//red mark here (InfiniteGallery)**
public InfiniteGallery(Context context) {
super(context);
init();
}
public InfiniteGallery(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public InfiniteGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
// These are just to make it look pretty
setSpacing(25);
setHorizontalFadingEdgeEnabled(false);
}
public void setResourceImages(int[] name){
setAdapter(new InfiniteGalleryAdapter(getContext(), name));
setSelection((getCount() / 2));
}
}
</code></pre>
| 0 | 1,898 |
How to obtain href values from a div using xpath?
|
<p>I have a div like this:</p>
<pre><code> <div class="widget-archive-monthly widget-archive widget">
<h3 class="widget-header">Monthly <a href="http://myblog.com/blogs/my_name/archives.html">Archives</a></h3>
<div class="widget-content">
<ul>
<li><a href="http://myblog.com/blogs/my_name/2010/10/">October 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/09/">September 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/08/">August 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/07/">July 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/06/">June 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/05/">May 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/04/">April 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/03/">March 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/02/">February 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2010/01/">January 2010</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/12/">December 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/11/">November 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/10/">October 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/09/">September 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/08/">August 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/07/">July 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/06/">June 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/05/">May 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/04/">April 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/03/">March 2009</a></li>
<li><a href="http://myblog.com/blogs/my_name/2009/02/">February 2009</a></li>
</ul>
</div>
</div>
</code></pre>
<p>I'm trying to get the href values inside the <code>widget-content</code> div.</p>
<p>How would I target these links using xpath and ignore any other link on the page such as the one for "Archives" so that I end up just with these values:</p>
<pre><code> http://myblog.com/blogs/my_name/2010/10/
http://myblog.com/blogs/my_name/2010/09/
http://myblog.com/blogs/my_name/2010/08/
http://myblog.com/blogs/my_name/2010/07/
... etc ...
</code></pre>
| 0 | 1,741 |
How to change field types for existing index using Elasticsearch Mapping API
|
<p>I am using <code>ELK</code> and have the following document structure</p>
<pre><code> {
"_index": "prod1-db.log-*",
"_type": "db.log",
"_id": "AVadEaq7",
"_score": null,
"_source": {
"message": "2016-07-08T12:52:42.026+0000 I NETWORK [conn4928242] end connection 192.168.170.62:47530 (31 connections now open)",
"@version": "1",
"@timestamp": "2016-08-18T09:50:54.247Z",
"type": "log",
"input_type": "log",
"count": 1,
"beat": {
"hostname": "prod1",
"name": "prod1"
},
"offset": 1421607236,
"source": "/var/log/db/db.log",
"fields": null,
"host": "prod1",
"tags": [
"beats_input_codec_plain_applied"
]
},
"fields": {
"@timestamp": [
1471513854247
]
},
"sort": [
1471513854247
]
}
</code></pre>
<p>I want to change the <code>message</code> field to <code>not_analyzed</code>. I am wondering how to use <code>Elasticsedarch Mapping API</code> to achieve that? For example, how to use <code>PUT Mapping API</code> to add a new type to the existing index?</p>
<p>I am using <code>Kibana 4.5</code> and <code>Elasticsearch 2.3</code>.</p>
<p>UPDATE
Tried the following <code>template.json</code> in <code>logstash</code>,</p>
<pre><code> 1 {
2 "template": "logstash-*",
3 "mappings": {
4 "_default_": {
5 "properties": {
6 "message" : {
7 "type" : "string",
8 "index" : "not_analyzed"
9 }
10 }
11 }
12 }
13 }
</code></pre>
<p>got the following errors when starting <code>logstash</code>,</p>
<pre><code>logstash_1 | {:timestamp=>"2016-08-24T11:00:26.097000+0000", :message=>"Invalid setting for elasticsearch output plugin:\n\n output {\n elasticsearch {\n # This setting must be a path\n # File does not exist or cannot be opened /home/dw/docker-elk/logstash/core_mapping_template.json\n template => \"/home/dw/docker-elk/logstash/core_mapping_template.json\"\n ...\n }\n }", :level=>:error}
logstash_1 | {:timestamp=>"2016-08-24T11:00:26.153000+0000", :message=>"Pipeline aborted due to error", :exception=>#<LogStash::ConfigurationError: Something is wrong with your configuration.>, :backtrace=>["/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/config/mixin.rb:134:in `config_init'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/outputs/base.rb:63:in `initialize'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/output_delegator.rb:74:in `register'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:181:in `start_workers'", "org/jruby/RubyArray.java:1613:in `each'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:181:in `start_workers'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:136:in `run'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/agent.rb:473:in `start_pipeline'"], :level=>:error}
logstash_1 | {:timestamp=>"2016-08-24T11:00:29.168000+0000", :message=>"stopping pipeline", :id=>"main"}
</code></pre>
| 0 | 1,496 |
align 2 table column widths with each other
|
<p>I have 2 tables one on top of the other and I would like to align their column widths exactly with each other, is there a way to do this? Tried fixed table col widths etc no joy</p>
<p>You can see on fiddle the columns are slightly off each other
<a href="http://jsfiddle.net/askhe/">http://jsfiddle.net/askhe/</a></p>
<p>HTML</p>
<pre><code><table class="tblresults txtblack">
<tr class="tblresultshdr bold">
<td class="col1">Company</td>
<td>Currency</td>
<td>Bid</td>
<td>Ask</td>
<td>YTD Vol</td>
</tr>
<tr>
<td class="col1">ABC</td>
<td>GBP</td>
<td>94</td>
<td>16</td>
<td>3,567,900</td>
</tr>
<tr>
<td class="col1">DEF</td>
<td>GBP</td>
<td>3</td>
<td>46</td>
<td>10,000</td>
</tr>
<tr>
<td class="col1">GHI</td>
<td>GBP</td>
<td>3</td>
<td>46</td>
<td>10,000</td>
</tr>
<tr>
<td class="col1">JKLM</td>
<td>GBP </td>
<td>7</td>
<td>46</td>
<td>56,000</td>
</tr>
</table>
<table class="tblresults txtblack margintop10">
<tr>
<td colspan="5" class="bold" >Investments</td>
</tr>
<tr>
<td class="col1">ghjk</td>
<td>GBP</td>
<td>13</td>
<td>6</td>
<td>130,000</td>
</tr>
<tr>
<td class="col1">asdsa</td>
<td>GBP</td>
<td>120</td>
<td>46</td>
<td>16,000</td>
</tr>
<tr>
<td class="col1">dfdsfsdf </td>
<td>GBP</td>
<td>1</td>
<td>4</td>
<td>13,000</td>
</tr>
</table>
</code></pre>
<p>CSS</p>
<pre><code>table.tblresults {
width:100%;
*width:99.5%;
border: 1px solid #b9b8b8;
top: 0;
}
table.tblresults tr.tblresultshdr {background: lightgrey;}
table.tblresults tr.tblresultshdr td {padding: 6px;}
table.tblresults td {padding: 8px; border: 1px solid #b9b8b8;}
table.tblresults td.col1 {width: 70%;}
</code></pre>
| 0 | 3,097 |
Why can't clang with libc++ in c++0x mode link this boost::program_options example?
|
<p>Compiling this example code for boost::program_options: <a href="http://svn.boost.org/svn/boost/trunk/libs/program_options/example/first.cpp" rel="noreferrer">http://svn.boost.org/svn/boost/trunk/libs/program_options/example/first.cpp</a></p>
<p>...on MacOS Lion (10.7.2), using boost-1.48.0 installed with MacPorts:</p>
<pre><code>$ clang++ -v
Apple clang version 3.0 (tags/Apple/clang-211.12) (based on LLVM 3.0svn)
Target: x86_64-apple-darwin11.2.0
Thread model: posix
$ clang++ -std=c++0x --stdlib=libc++ -lc++ -I/opt/local/include -L/opt/local/lib -lboost_program_options first.cpp -o first
Undefined symbols for architecture x86_64:
"boost::program_options::options_description::options_description(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, unsigned int, unsigned int)", referenced from:
_main in cc-6QQcwm.o
"boost::program_options::operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, boost::program_options::options_description const&)", referenced from:
_main in cc-6QQcwm.o
"boost::program_options::abstract_variables_map::operator[](std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const", referenced from:
boost::program_options::variables_map::operator[](std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const in cc-6QQcwm.o
"boost::program_options::detail::cmdline::set_additional_parser(boost::function1<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>)", referenced from:
boost::program_options::basic_command_line_parser<char>::extra_parser(boost::function1<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>) in cc-6QQcwm.o
"boost::program_options::detail::cmdline::cmdline(std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&)", referenced from:
boost::program_options::basic_command_line_parser<char>::basic_command_line_parser(int, char const* const*) in cc-6QQcwm.o
"boost::program_options::to_internal(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from:
std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > boost::program_options::to_internal<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&) in cc-6QQcwm.o
"boost::program_options::invalid_option_value::invalid_option_value(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from:
void boost::program_options::validate<int, char>(boost::any&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, int*, long) in cc-6QQcwm.o
"boost::program_options::validation_error::validation_error(boost::program_options::validation_error::kind_t, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from:
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const& boost::program_options::validators::get_single_string<char>(std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, bool) in cc-6QQcwm.o
"boost::program_options::value_semantic_codecvt_helper<char>::parse(boost::any&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, bool) const", referenced from:
vtable for boost::program_options::typed_value<int, char> in cc-6QQcwm.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre>
<p>The same code compiled/linked with g++4.7 installed with MacPorts:</p>
<pre><code>$ g++-mp-4.7 -std=c++0x -I/opt/local/include -L/opt/local/lib -lboost_program_options -o first first.cpp
</code></pre>
<p>... works fine. As does using clang without libc++:</p>
<pre><code>clang++ -std=c++0x -I/opt/local/include -L/opt/local/lib -lboost_program_options first.cpp -o first
</code></pre>
<p>What's wrong? Why does boost::program_options and libc++ not work together?</p>
| 0 | 2,657 |
Error:Cannot read packageName from app/src/main/AndroidManifest.xml
|
<p>These are the errors that pop up when running my app for splash screen.</p>
<pre><code>Error:The markup in the document preceding the root element must be well-formed.
Error:Cannot read packageName from /Users/akellavamsimeher/AndroidStudioProjects/WILM/app/src/main/AndroidManifest.xml
</code></pre>
<p>I tried to resolve seeing posts from stackoverflow but I'm still stuck at that. Please help me fix these errors.</p>
<p>Here is the code.</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pratyuvamgmail.wilm">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
android:name="com.pratyuvamgmail.wilm.Splash" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action
android:name="com.coderefer.androidsplashscreenexample.MAINACTIVITY"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<hr>
<p>Below is my code...</p>
<pre class="lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pratyuvamgmail.wilm">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
android:name="com.pratyuvamgmail.wilm.Splash" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.coderefer.androidsplashscreenexample.MAINACTIVITY"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
| 0 | 1,319 |
Error occurred while installing mini_racer (0.2.0)
|
<p>I am using mac 10.14. I have some problem with mini_racer gem. After run bundle install the below error occurs. I don't know how can I solve this.</p>
<p><strong>Error</strong> </p>
<pre><code>Installing mini_racer 0.2.0 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
current directory:
/Users/vipinkumar/.rvm/gems/ruby-2.5.1@ry_rails5/gems/mini_racer-0.2.0/ext/mini_racer_extension
/Users/vipinkumar/.rvm/rubies/ruby-2.5.1/bin/ruby -r
./siteconf20180911-791-fpmt3t.rb extconf.rb
checking for -lpthread... yes
checking for -lobjc... yes
creating Makefile
current directory:
/Users/vipinkumar/.rvm/gems/ruby-2.5.1@ry_rails5/gems/mini_racer-0.2.0/ext/mini_racer_extension
make "DESTDIR=" clean
current directory:
/Users/vipinkumar/.rvm/gems/ruby-2.5.1@ry_rails5/gems/mini_racer-0.2.0/ext/mini_racer_extension
make "DESTDIR="
compiling mini_racer_extension.cc
clang: warning: argument unused during compilation: '-rdynamic'
[-Wunused-command-line-argument]
In file included from mini_racer_extension.cc:2:
In file included from
/Users/vipinkumar/.rvm/rubies/ruby-2.5.1/include/ruby-2.5.0/ruby.h:33:
In file included from
/Users/vipinkumar/.rvm/rubies/ruby-2.5.1/include/ruby-2.5.0/ruby/ruby.h:2040:
/Users/vipinkumar/.rvm/rubies/ruby-2.5.1/include/ruby-2.5.0/ruby/intern.h:47:19:
warning: 'register' storage class specifier is deprecated and incompatible with
C++17 [-Wdeprecated-register]
void rb_mem_clear(register VALUE*, register long);
^~~~~~~~~
/Users/vipinkumar/.rvm/rubies/ruby-2.5.1/include/ruby-2.5.0/ruby/intern.h:47:36:
warning: 'register' storage class specifier is deprecated and incompatible with
C++17 [-Wdeprecated-register]
void rb_mem_clear(register VALUE*, register long);
^~~~~~~~~
2 warnings generated.
linking shared-object mini_racer_extension.bundle
clang: warning: libstdc++ is deprecated; move to libc++ [-Wdeprecated]
ld: library not found for -lstdc++
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mini_racer_extension.bundle] Error 1
make failed, exit code 2
Gem files will remain installed in
/Users/vipinkumar/.rvm/gems/ruby-2.5.1@ry_rails5/gems/mini_racer-0.2.0 for
inspection.
Results logged to
/Users/vipinkumar/.rvm/gems/ruby-2.5.1@ry_rails5/extensions/x86_64-darwin-18/2.5.0/mini_racer-0.2.0/gem_make.out
An error occurred while installing mini_racer (0.2.0), and Bundler
cannot continue.
Make sure that `gem install mini_racer -v '0.2.0' --source
'https://rubygems.org/'` succeeds before bundling.
In Gemfile:
mini_racer
</code></pre>
<p>Ruby version 2.5.0 or 2.5.1 and rails 5.0</p>
<p><strong>GemFile</strong> </p>
<pre><code>gem 'mini_racer', platforms: :ruby
</code></pre>
| 0 | 1,122 |
Save CSV files into mysql database
|
<p>I have a lot of csv files in a directory. With these files, I have to write a script that put their content in the right fields and tables of my database. I am almost beginner in php language : I have found some bits of code on the Internet. It seems to work, but I am stuck at a stage. Some topics are related on this website, but I did not found the ecat problem.</p>
<p>I have written a php script that permits to get the path and the name of these files. I managed too to create a table whose name depends of each csv (e.g : file ‘data_1.csv’ gives the table data_1.csv in my-sql). All the tables have the three same fields, id, url, value.
The last thing to do is to populate these tables, by reading each file and put the values separated by ‘|’ character in the right tables. For example, if a line of ‘data_1.csv’ is</p>
<p>8756|htttp://example.com|something written</p>
<p>I would like to get a record in data_1.csv table where 8756 is in id, htttp://example.com in url field, and something written in value field.
I have found the way to read and print these csv with fcsvget function. But I do not know how to make these lines go into the SQL database. Could anyone help me on this point?</p>
<p>Here is my script below</p>
<pre><code><?php
ini_set('max_execution_time', 300);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, true) or die ('Error connecting to mysql');
$dbname = 'test_database';
mysql_select_db($dbname);
$bdd = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else {
echo "hello <br>";
}
$dir = 'C:\wamp\www\test';
$imgs = array();
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file) && preg_match("/\.(csv)$/", $file)) {
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
foreach ($imgs as $idx=>$img) {
$class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
$filePath=$dir . '\\'. $img;
$file = fopen($filePath, "r") or exit("Unable to open file!");
$nom = 'FILE: ' . $dir . '\\'. $img;
echo $nom;
settype($nom, "string");
echo '<br>';
$chemin = '<img src="' . $dir . $img . '" alt="' .
$img . '"' . $class . ' />' . "\n";
echo $chemin;
$file_name = basename($filePath);
$sql = 'CREATE TABLE `' . $file_name . '` (id int(20000), url varchar(15), value TEXT)';
mysql_query($sql,$conn);
$handle = fopen($filePath, 'r');
while (($row = fgetcsv($handle)) !== false) {
foreach ($row as $field) {
echo $field . '<br />';
}
}
fclose($handle);
}
echo ("VERIFY");
for ($i = 1; $i <= 1682; $i++) {
echo ("<br>A : " . $i);
$checkRequest= "select * from movies where movieID='". $i."'";
echo ("<br>". $checkRequest);
if ($result = $mysqli->query($checkRequest)) {
printf("<br> Select ". $i ."returned %d rows.\n", $result->num_rows);
if ($result->num_rows == 0) {
echo ("I : " . $i);
}
$result->close();
}
}
$mysqli->close();
?>
</code></pre>
| 0 | 1,367 |
Find the index of the n'th item in a list
|
<p>I want to find the index of the n'th occurrence of an item in a list. e.g., </p>
<pre><code>x=[False,True,True,False,True,False,True,False,False,False,True,False,True]
</code></pre>
<p>What is the index of the n'th true? If I wanted the fifth occurrence (4th if zero-indexed), the answer is 10.</p>
<p>I've come up with:</p>
<pre><code>indargs = [ i for i,a in enumerate(x) if a ]
indargs[n]
</code></pre>
<p>Note that <code>x.index</code> returns the first occurrence or the first occurrence after some point, and therefore as far as I can tell is not a solution.</p>
<p>There is also a solution in numpy for cases similar to the above, e.g. using <code>cumsum</code> and <code>where</code>, but I'd like to know if there's a numpy-free way to solve the problem.</p>
<p>I'm concerned about performance since I first encountered this while implemented a Sieve of Eratosthenes for a <a href="https://projecteuler.net" rel="noreferrer">Project Euler</a> problem, but this is a more general question that I have encountered in other situations.</p>
<p>EDIT: I've gotten a lot of great answers, so I decided to do some performance tests. Below are <code>timeit</code> execution times in seconds for lists with <code>len</code> nelements searching for the 4000'th/1000'th True. The lists are random True/False. Source code linked below; it's a touch messy. I used short / modified versions of the posters' names to describe the functions except <code>listcomp</code>, which is the simple list comprehension above.</p>
<pre><code>True Test (100'th True in a list containing True/False)
nelements eyquem_occur eyquem_occurrence graddy taymon listcomp hettinger26 hettinger
3000: 0.007824 0.031117 0.002144 0.007694 0.026908 0.003563 0.003563
10000: 0.018424 0.103049 0.002233 0.018063 0.088245 0.003610 0.003769
50000: 0.078383 0.515265 0.002140 0.078074 0.442630 0.003719 0.003608
100000: 0.152804 1.054196 0.002129 0.152691 0.903827 0.003741 0.003769
200000: 0.303084 2.123534 0.002212 0.301918 1.837870 0.003522 0.003601
True Test (1000'th True in a list containing True/False)
nelements eyquem_occur eyquem_occurrence graddy taymon listcomp hettinger26 hettinger
3000: 0.038461 0.031358 0.024167 0.039277 0.026640 0.035283 0.034482
10000: 0.049063 0.103241 0.024120 0.049383 0.088688 0.035515 0.034700
50000: 0.108860 0.516037 0.023956 0.109546 0.442078 0.035269 0.035373
100000: 0.183568 1.049817 0.024228 0.184406 0.906709 0.035135 0.036027
200000: 0.333501 2.141629 0.024239 0.333908 1.826397 0.034879 0.036551
True Test (20000'th True in a list containing True/False)
nelements eyquem_occur eyquem_occurrence graddy taymon listcomp hettinger26 hettinger
3000: 0.004520 0.004439 0.036853 0.004458 0.026900 0.053460 0.053734
10000: 0.014925 0.014715 0.126084 0.014864 0.088470 0.177792 0.177716
50000: 0.766154 0.515107 0.499068 0.781289 0.443654 0.707134 0.711072
100000: 0.837363 1.051426 0.501842 0.862350 0.903189 0.707552 0.706808
200000: 0.991740 2.124445 0.498408 1.008187 1.839797 0.715844 0.709063
Number Test (750'th 0 in a list containing 0-9)
nelements eyquem_occur eyquem_occurrence graddy taymon listcomp hettinger26 hettinger
3000: 0.026996 0.026887 0.015494 0.030343 0.022417 0.026557 0.026236
10000: 0.037887 0.089267 0.015839 0.040519 0.074941 0.026525 0.027057
50000: 0.097777 0.445236 0.015396 0.101242 0.371496 0.025945 0.026156
100000: 0.173794 0.905993 0.015409 0.176317 0.762155 0.026215 0.026871
200000: 0.324930 1.847375 0.015506 0.327957 1.536012 0.027390 0.026657
</code></pre>
<p>Hettinger's itertools solution is almost always the best. taymon's and graddy's solutions are next best for most situations, though the list comprehension approach can be better for short arrays when you want the n'th instance such that n is high or lists in which there are fewer than n occurrences. If there's a chance that there are fewer than n occurrences, the initial <code>count</code> check saves time. Also, graddy's is more efficient when searching for numbers instead of True/False... not clear why that is. eyquem's solutions are essentially equivalent to others with slightly more or less overhead; eyquem_occur is approximately the same as taymon's solution, while eyquem_occurrence is similar to listcomp.</p>
| 0 | 3,280 |
Build is Success but No sources to compile
|
<p>Maven test output in the Eclipse console:</p>
<pre><code>[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for Mabi:Mabi:jar:0.0.1-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.seleniumhq.selenium:selenium-java:jar -> duplicate declaration of version 2.45.0 @ line 20, column 21
[WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-surefire-plugin @ line 74, column 10
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Mabi 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Mabi ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory E:\workspace\Mabi\src\com.TestCase
[INFO]
[INFO] --- maven-compiler-plugin:3.5:compile (default-compile) @ Mabi ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 166 source files to E:\workspace\Mabi\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ Mabi ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory E:\workspace\Mabi\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.5:testCompile (default-testCompile) @ Mabi ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ Mabi ---
[INFO] No tests to run.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.287 s
[INFO] Finished at: 2016-03-23T11:32:40+05:30
[INFO] Final Memory: 21M/283M
[INFO] ------------------------------------------------------------------------
</code></pre>
<p><img src="https://i.stack.imgur.com/wLhf6.png" alt=""></p>
<p>Above image shows the directory of my project but when I run the project via Maven it gives me the above result without running the test. Looking forward for some accurate solutions.</p>
<p>And this is what my POM.XML file looks like:</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Mabi</groupId>
<artifactId>Mabi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.40.2</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.45.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src/com.TestCase</directory>
<includes>
<include>**/com.*TestCase.java</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source/>
<target/>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<inherited>true</inherited>
<configuration>
<suiteXmlFile>testng.xml</suiteXmlFile>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
| 0 | 2,497 |
ERROR: Kendo"Something" is not a function
|
<p>So I am trying to convert my plain HTML/Javascript site (which works fine) into an ASP MVC4 project. What I do is get and XML and use and XSLT to transform. I litreally use the code <a href="https://stackoverflow.com/questions/7471391/using-xslt-in-asp-net-mvc-3">from here</a> to do that </p>
<p>In my <code>_Layout.cshtml</code> I use razor to load the resource</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
... things...
@Scripts.Render("~/bundles/kendoScripts")
@Scripts.Render("~/bundles/customScript")
@Styles.Render("~/Content/themes/Kendo")
@Styles.Render("~/Content/themes/customCSS")
</code></pre>
<p>my view that uses the layout is very straight forward, this is all that is in the page</p>
<pre><code>@using Summ.ExtensionCode
@model SumMVC.Models.SummaryModel
@{
ViewBag.Title = "_Summary";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div data-role="content">
@Html.RenderXml(Model.ProgramFilename, Model.StylesheetFilename, Model.Parameters)
</div>
</code></pre>
<p>In <code>@Scripts.Render("~/bundles/customScript")</code>, is a JS file, renderpage.js that has this bit of code <code>$(this).kendoDropDownList();</code> where this is a select element. But I am getting a error that <code>.kendoDropDownList();</code> is not a function. The error from firebug: <code>TypeError: $(...).kendoDropDownList is not a function</code> and the errror from GoogleChrome <code>Uncaught TypeError: Object [object Object] has no method 'kendoDropDownList'</code>. It seems that in my bundle the JS file kendo.all.min.js is not begin loaded here is what is looks like</p>
<pre><code>bundles.Add(new ScriptBundle("~/bundles/kendoScripts")
.Include("~/Scripts/kendoui/kendo.web.min.js")
.Include("~/Scripts/kendoui/kendo.all.min.js")
);
....
bundles.Add(new ScriptBundle("~/bundles/customScript")
.....
.Include("~/Scripts/SummaryScript/renderpage.js")
....
);
</code></pre>
<p>I am assuming that perhaps the code is being executed before kendo.all.min.js is done loading, but as you can see above renderpage.js is after kendo. Any ideas or insight? </p>
<p><strong>UPDATE</strong></p>
<p>I forgot to add that when I manually load the resource in the MVC project in the head tag</p>
<pre><code><script type="text/javascript" src="~/Scripts/kendoui/kendo.web.min.js"></script>
<script type="text/javascript" src="~/Scripts/kendoui/kendo.all.min.js"></script>
....
<script type="text/javascript" src="~/Scripts/ExecSummaryScript/renderpage.js"></script>
</code></pre>
<p>it works fine.</p>
<p><strong>Update2</strong></p>
<p>Turns out the Kendo JS file is not being loaded at all. I check the resource in the dev console and notice that it not even there.Upon closer inspection I notice that all resources are loaded except some <code>.min.js</code> files. There are a few loaded but some that are not loaded are jquery-ui-1.10.3.min.js, and jquery.browser.min.js.</p>
| 0 | 1,240 |
Optimizing the backtracking algorithm solving Sudoku
|
<p>I'm hoping to optimize my backtracking algorithm for my Sudoku Solver.</p>
<hr>
<p>What it does now:</p>
<p>The recursive solver function takes a sudoku puzzle with various given values.</p>
<p>I will scour through all the empty slots in the puzzle, looking for the slot that has the least possibilities, and get the list of values.</p>
<p>From the list of values, I will loop through it by placing one of the values from the list in the slot, and recursively solve it, until the entire grid is filled.</p>
<hr>
<p>This implementation still takes incredibly long for some puzzles and I hope to further optimize this. Does anyone have any ideas how I might be able to further optimize this?</p>
<hr>
<p>Here's my code in Java if you're interested.</p>
<pre class="lang-java prettyprint-override"><code>public int[][] Solve(int[][] slots) {
// recursive solve v2 : optimization revision
int[] least = new int[3];
least[2] = Integer.MAX_VALUE;
PuzzleGenerator value_generator = new PuzzleGenerator();
LinkedList<Integer> least_values = null;
// 1: find a slot with the least possible solutions
// 2: recursively solve.
// 1 - scour through all slots.
int i = 0;
int j = 0;
while (i < 9) {
j = 0;
while (j < 9) {
if (slots[i][j] == 0) {
int[] grid_posi = { i, j };
LinkedList<Integer> possible_values = value_generator
.possibleValuesInGrid(grid_posi, slots);
if ((possible_values.size() < least[2])
&& (possible_values.size() != 0)) {
least[0] = i;
least[1] = j;
least[2] = possible_values.size();
least_values = possible_values;
}
}
j++;
}
i++;
}
// 2 - work on the slot
if (least_values != null) {
for (int x : least_values) {
int[][] tempslot = new int[9][9];
ArrayDeepCopy(slots, tempslot);
tempslot[least[0]][least[1]] = x;
/*ConsoleInterface printer = new gameplay.ConsoleInterface();
printer.printGrid(tempslot);*/
int[][] possible_sltn = Solve(tempslot);
if (noEmptySlots(possible_sltn)) {
System.out.println("Solved");
return possible_sltn;
}
}
}
if (this.noEmptySlots(slots)) {
System.out.println("Solved");
return slots;
}
slots[0][0] = 0;
return slots;
}
</code></pre>
| 0 | 1,188 |
How to grab values from key:value pairs in parsed JSON in Python
|
<p>I am trying to extract data from a JSON file. Here is my code.</p>
<pre><code>import json
json_file = open('test.json')
data = json.load(json_file)
json_file.close()
</code></pre>
<p>At this point I can print the file using print data and it appears that the file has been read in properly.</p>
<p>Now I would like to grab a value from a key:value pair that is in a dictionary nested within a list nested within a dictionary (Phew!). My initial strategy was to create a dictionary and plop the dictionary nested within the list in it and then extract the key:value pairs I need.</p>
<pre><code>dict = {}
dict = json_file.get('dataObjects', None)
dict[0]
</code></pre>
<p>When I try to look at the contents of dict, I see that there is only one element. The entire dictionary appears to have been read as a list. I've tried a couple of different approaches, but I still wind up with a dictionary read as a list. I would love to grab the nested dictionary and use another .get to grab the values I need. Here is a sample of the JSON I am working with. Specifically, I am trying to pull out the identifier and description values from the dataObjects section.</p>
<pre><code>{
"identifier": 213726,
"scientificName": "Carcharodon carcharias (Linnaeus, 1758)",
"richness_score": 89.6095,
"synonyms": [
],
"taxonConcepts": [
{
"identifier": 20728481,
"scientificName": "Carcharodon carcharias (Linnaeus, 1758)",
"nameAccordingTo": "WORMS Species Information (Marine Species)",
"canonicalForm": "Carcharodon carcharias",
"sourceIdentfier": "105838"
},
{
"identifier": 24922984,
"scientificName": "Carcharodon carcharias",
"nameAccordingTo": "IUCN Red List (Species Assessed for Global Conservation)",
"canonicalForm": "Carcharodon carcharias",
"sourceIdentfier": "IUCN-3855"
},
],
"dataObjects": [
{
"identifier": "5e1882d822ec530069d6d29e28944369",
"dataObjectVersionID": 5671572,
"dataType": "http://purl.org/dc/dcmitype/Text",
"dataSubtype": "",
"vettedStatus": "Trusted",
"dataRating": 3.0,
"subject": "http://rs.tdwg.org/ontology/voc/SPMInfoItems#TaxonBiology",
"mimeType": "text/html",
"title": "Biology",
"language": "en",
"license": "http://creativecommons.org/licenses/by-nc-sa/3.0/",
"rights": "Copyright Wildscreen 2003-2008",
"rightsHolder": "Wildscreen",
"audience": [
"General public"
],
"source": "http://www.arkive.org/great-white-shark/carcharodon-carcharias/",
"description": "Despite its worldwide notoriety, very little is known about the natural ecology and behaviour of this predator. These sharks are usually solitary or occur in pairs, although it is apparently a social animal that can also be found in small aggregations of 10 or more, particularly around a carcass (3) (6). Females are ovoviviparous; the pups hatch from eggs retained within their mother's body, and she then gives birth to live young (10). Great white sharks are particularly slow-growing, late maturing and long-lived, with a small litter size and low reproductive capacity (8). Females do not reproduce until they reach about 4.5 to 5 metres in length, and litter sizes range from two to ten pups (8). The length of gestation is not known but estimated at between 12 and 18 months, and it is likely that these sharks only reproduce every two or three years (8) (11). After birth, there is no maternal care, and despite their large size, survival of young is thought to be low (8).&nbsp;Great whites are at the top of the marine food chain, and these sharks are skilled predators. They feed predominately on fish but will also consume turtles, molluscs, and crustaceans, and are active hunters of small cetaceans such as dolphins and porpoises, and of other marine mammals such as seals and sea lions (12). Using their acute senses of smell, sound location and electroreception, weak and injured prey can be detected from a great distance (7). Efficient swimmers, sharks have a quick turn of speed and will attack rapidly before backing off whilst the prey becomes weakened; they are sometimes seen leaping clear of the water (6). Great whites, unlike most other fish, are able to maintain their body temperature higher than that of the surrounding water using a heat exchange system in their blood vessels (11).",
"agents": [
{
"full_name": "ARKive",
"homepage": "http://www.arkive.org/",
"role": "provider"
}
],
}
]
}
</code></pre>
| 0 | 1,601 |
showDialog in button Listview adapter
|
<p>i have a listView like <a href="https://stackoverflow.com/questions/30092158/set-button-onclick-in-listview-android/30092841#30092841">THIS</a></p>
<p><img src="https://i.stack.imgur.com/iBS2E.png" alt="enter image description here"></p>
<p>i want when i press the delete. it show a dialog like this image</p>
<p><img src="https://i.stack.imgur.com/BEFdl.png" alt="enter image description here"></p>
<p>so when i press YES. it will remove from list.</p>
<p>here's my code..</p>
<pre><code>public class customadapter extends BaseAdapter{
ArrayList<HashMap<String, String>> oslist;
Context context;
private Button btnDelete;
private Button btnEdit;
AlertDialog.Builder alertDialogBuilder;
public customadapter(ArrayList<HashMap<String, String>> oslist,Context context) {
System.out.println("skdjfhksdfjskfjhsdkjfh");
this.context = context;
this.oslist = oslist;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return oslist.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return oslist.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
System.out.println("oslist oslist = "+oslist);
System.out.println("oslist 1 = "+oslist);
System.out.println("oslist size = "+oslist.size());
System.out.println("oslist oslist = "+oslist.getClass());
System.out.println("position = "+position);
System.out.println("convertView = "+convertView);
System.out.println("parent = "+parent);
System.out.println("position = "+position);
LayoutInflater lif = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = lif.inflate(R.layout.listitem, null);
TextView id = (TextView) convertView.findViewById(R.id.varId);
TextView noNota = (TextView) convertView.findViewById(R.id.varNoNota);
TextView senderName = (TextView) convertView.findViewById(R.id.varSenderName);
TextView totalAmount = (TextView) convertView.findViewById(R.id.varTotalAmount);
id.setText(oslist.get(position).get("id"));
noNota.setText(oslist.get(position).get("noNota"));
senderName.setText(oslist.get(position).get("senderName"));
totalAmount.setText(oslist.get(position).get("totalAmount"));
Button btnEdit = (Button) convertView.findViewById(R.id.btnEdit);
Button btnDelete = (Button) convertView.findViewById(R.id.btnDelete);
btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Edit ditekan!", Toast.LENGTH_LONG).show();
//I want show YES NO dialog here.
}
});
btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//I want show YES NO dialog here
}
});
return convertView;
}
</code></pre>
<p>}</p>
<p>how can i do to create a dialog like that..i tried this code</p>
<pre><code>final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher); //line 115
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
</code></pre>
<p>but itsnt success.</p>
<p>i got this error</p>
<p><img src="https://i.stack.imgur.com/CPorB.png" alt="enter image description here"></p>
| 0 | 1,749 |
Angular2- Getting confused with Observable Catch closure scope
|
<p>Wondering if you can give a little assistance. I appear to be getting myself a bit confused when it comes to using <code>catch</code> with <code>Observable</code>s.</p>
<p>Basically what I'm trying to do is the following:
When my API returns a 403 error, I want to perform some actions on my <code>TokenStore</code>, namely, delete the local token and mark the user as unauthenticated. The way I'm trying to do this may be wrong, so please do let me know if there's a better way of accomplishing this.</p>
<p>I'm trying to accomplish this with the following code:</p>
<p><strong>APIConnector.service.ts</strong> - a single service for API communication methods</p>
<pre><code>import {Injectable} from 'angular2/core';
import {Http, Response, Headers, RequestOptions} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import * as _ from 'lodash';
import {Logger} from './logger.service';
import {TokenStore} from '../stores/token.store';
@Injectable()
export class APIConnector {
private _apiUrl:string = 'https://api.sb.zerojargon.com/';
private _token:string = null;
constructor(
private _http:Http,
private _logger:Logger,
private _tokenStore:TokenStore
) {}
get(endpoint:String, includes:Array<string>) {
let includeString = (!_.isUndefined(includes)) ? this._parseIncludes(includes) : '';
let headers = this._createHeaders();
let options = new RequestOptions({ headers: headers });
return this._http.get(this._apiUrl + endpoint + '?include=' + includeString, options);
}
post(endpoint:String, formData:Object, includes:Array<string>) {
let includeString = (!_.isUndefined(includes)) ? this._parseIncludes(includes) : '';
let body = JSON.stringify(formData);
let headers = this._createHeaders();
let options = new RequestOptions({ headers: headers });
return this._http.post(this._apiUrl + endpoint + '?include=' + includeString, body, options);
}
handleError(error: Response) {
// log out the user if we get a 401 message
if (error.json().error.http_code === 401) {
this._tokenStore.destroy();
}
return Observable.throw(error.json().error || 'Server error');
}
private _parseIncludes(includes:Array<String>) {
return includes.join();
}
private _createHeaders() {
return new Headers({ 'Content-Type': 'application/json', 'Authorization': 'bearer ' + localStorage.getItem('token') });
}
}
</code></pre>
<p>In each of my services which use the APIConnector, I have catch methods on the <code>Observable</code>s, to run the <code>handleError</code> closure. e.g.</p>
<pre><code>public createEvent(event:Object) {
let endpoint = this._endpoint;
return this._apiConnector.post('clients/'+this.client+'/events', event, this._defaultIncludes)
.map(res => {
return this._transformer.map('event', <Object[]>res.json());
})
.catch(this._apiConnector.handleError);
}
</code></pre>
<p>However, this gives the following error:</p>
<blockquote>
<p>EXCEPTION: TypeError: Cannot read property 'destroy' of undefined</p>
</blockquote>
<p>Presumably this is because handleError is a closure. I'm unsure of the best way to deal with this, though.</p>
<p>Any thoughts would be greatly appreciated</p>
| 0 | 1,203 |
Fortran Error Meanings
|
<p>I have been following books and PDFs on writing in FORTRAN to write an integration program. I compile the code with gfortran and get several copies of the following errors.</p>
<pre><code>1)Unexpected data declaration statement at (1)
2)Unterminated character constant beginning at (1)
3)Unclassifiable statement at (1)
4)Unexpected STATEMENT FUNCTION statement at (1)
5)Expecting END PROGRAM statement at (1)
6)Syntax error in data declaration at (1)
7)Statement function at (1) is recursive
8)Unexpected IMPLICIT NONE statement at (1)
</code></pre>
<p>I do not know hat they truly mean or how to fix them, google search has proven null and the other topics on this site we about other errors. for Error 5) i put in Program main and end program main like i might in C++ but still got the same result. Error 7) makes no sense, i am trying for recursion in the program. Error 8) i read implicit none was to prevent unnecessary decelerations.</p>
<p>Ill post the code itself but i am more interested in the compiling errors because i still need to fine tune the array data handling, but i cant do that until i get it working.</p>
<pre><code> Program main
implicit none
real, dimension(:,:), allocatable :: m, oldm
real a
integer io, nn
character(30) :: filename
real, dimension(:,:), allocatable :: alt, temp, nue, oxy
integer locationa, locationt, locationn, locationo, i
integer nend
real dz, z, integral
real alti, tempi, nuei, oxyi
integer y, j
allocate( m(0, 0) ) ! size zero to start with?
nn = 0
j = 0
write(*,*) 'Enter input file name: '
read(*,*) filename
open( 1, file = filename )
do !reading in data file
read(1, *, iostat = io) a
if (io < 0 ) exit
nn = nn + 1
allocate( oldm( size(m), size(m) ) )
oldm = m
deallocate( m )
allocate( m(nn, nn) )
m = oldm
m(nn, nn) = a ! The nnth value of m
deallocate( oldm )
enddo
! Decompose matrix array m into column arrays [1,n]
write(*,*) 'Enter Column Number for Altitude'
read(*,*) locationa
write(*,*) 'Enter Column Number for Temperature'
read(*,*) locationt
write(*,*) 'Enter Column Number for Nuetral Density'
read(*,*) locationn
write(*,*) 'Enter Column Number for Oxygen density'
read(*,*) locationo
nend = size(m, locationa) !length of column #locationa
do i = 1, nend
alt(i, 1) = m(i, locationa)
temp(i, 1) = log(m(i, locationt))
nue(i, 1) = log(m(i, locationn))
oxy(i, 1) = log(m(i, locationo))
enddo
! Interpolate Column arrays, Constant X value will be array ALT with the 3 other arrays
!real dz = size(alt)/100, z, integral = 0
!real alti, tempi, nuei, oxyi
!integer y, j = 0
dz = size(alt)/100
do z = 1, 100, dz
y = z !with chopped rounding alt(y) will always be lowest integer for smooth transition.
alti = alt(y, 1) + j*dz ! the addition of j*dz's allow for all values not in the array between two points of the array.
tempi = exp(linear_interpolation(alt, temp, size(alt), alti))
nuei = exp(linear_interpolation(alt, nue, size(alt), alti))
oxyi = exp(linear_interpolation(alt, oxy, size(alt), alti))
j = j + 1
!Integration
integral = integral + tempi*nuei*oxyi*dz
enddo
end program main
!Functions
real function linear_interpolation(x, y, n, x0)
implicit none
integer :: n, i, k
real :: x(n), y(n), x0, y0
k = 0
do i = 1, n-1
if ((x0 >= x(i)) .and. (x0 <= x(i+1))) then
k = i ! k is the index where: x(k) <= x <= x(k+1)
exit ! exit loop
end if
enddo
if (k > 0) then ! compute the interpolated value for a point not in the array
y0 = y(k) + (y(k+1)-y(k))/(x(k+1)-x(k))*(x0-x(k))
else
write(*,*)'Error computing the interpolation !!!'
write(*,*) 'x0 =',x0, ' is out of range <', x(1),',',x(n),'>'
end if
! return value
linear_interpolation = y0
end function linear_interpolation
</code></pre>
<p>I can provide a more detailed description of the exact errors, i was hoping that the error name would be enough since i have a few of each type.</p>
| 0 | 1,483 |
How to install vuetify 2.0 beta to the new vue cli project?
|
<p>Vuetify 2.0.0-beta.0 has just been released and I want to try it out and play around in a new vue test application.
But I get errors when I try to install it in a fresh new project. Here are the steps I've taken.</p>
<p>I use <code>@vue/cli v3.8.2</code> to create a new project with default settings:</p>
<pre><code>vue create testapp
</code></pre>
<p>which gives me successful result:</p>
<pre><code> Successfully created project testapp.
Get started with the following commands:
$ cd testapp
$ npm run serve
</code></pre>
<p>Then I add vuetify plugin to the project with default (recommended) preset:</p>
<pre><code>cd testapp
vue add vuetify
</code></pre>
<p>which gives me success:</p>
<pre><code> Installing vue-cli-plugin-vuetify...
+ vue-cli-plugin-vuetify@0.5.0
added 1 package from 1 contributor and audited 23942 packages in 9.235s
found 0 vulnerabilities
✔ Successfully installed plugin: vue-cli-plugin-vuetify
? Choose a preset: Default (recommended)
Invoking generator for vue-cli-plugin-vuetify...
Installing additional dependencies...
added 11 packages from 49 contributors and audited 23980 packages in 9.252s
found 0 vulnerabilities
⚓ Running completion hooks...
✔ Successfully invoked generator for plugin: vue-cli-plugin-vuetify
</code></pre>
<p>Now in <code>package.json</code> I see vuetify version:
<code>"vuetify": "^1.5.5"</code></p>
<p>I now update it to the <code>v2.0.0-beta.0</code> like this:</p>
<pre><code>npm install vuetify@2.0.0-beta.0
</code></pre>
<p>I get success again:</p>
<pre><code>+ vuetify@2.0.0-beta.0
updated 1 package and audited 23980 packages in 10.302s
found 0 vulnerabilities
</code></pre>
<p>Now when I try to run it:</p>
<pre><code>npm run serve
</code></pre>
<p>I get error:</p>
<pre><code>> testapp@0.1.0 serve c:\temp\testapp
> vue-cli-service serve
INFO Starting development server...
98% after emitting CopyPlugin
ERROR Failed to compile with 99 errors 6:17:04 PM
This dependency was not found:
* vuetify/src/stylus/app.styl in ./src/plugins/vuetify.js
To install it, you can run: npm install --save vuetify/src/stylus/app.styl
Failed to resolve loader: sass-loader
You may need to install it.
</code></pre>
<p>If I install sass-loader like this:</p>
<pre><code>npm i -D node-sass sass-loader
</code></pre>
<p>I get success. Then I try to run it again:</p>
<pre><code>npm run serve
</code></pre>
<p>Now again I get different error:</p>
<pre><code> ERROR Failed to compile with 1 errors 6:27:06 PM
This dependency was not found:
* vuetify/src/stylus/app.styl in ./src/plugins/vuetify.js
To install it, you can run: npm install --save vuetify/src/stylus/app.styl
</code></pre>
<p>I am stuck here as I don't know how to fix this error. <code>npm install --save vuetify/src/stylus/app.styl</code> obviously don't work. Also I couldn't make it work neither by following official <a href="https://next.vuetifyjs.com/en/getting-started/quick-start#full-install" rel="noreferrer">vuetify page</a> for this beta release.</p>
| 0 | 1,479 |
Error inflating class fragment: Duplicate id , tag null, or parent id with another fragment
|
<p>I am trying to make an app in which when user clicks on item in ListView, the GoogleMaps is displayed.</p>
<p>I have tried following code:</p>
<p><strong>ShowPlacesActivity.java</strong></p>
<pre><code>public class ShowPlaceActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_place);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container_showplaces, new PlaceholderFragment())
.commit();
}
getActionBar().setSubtitle(getString(R.string.activity_showplaces_subtitle));
}
}
</code></pre>
<p><strong>activity_show_place.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_showplaces"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.krupal.rememberthisplace.ShowPlaceActivity" tools:ignore="MergeRootFrame" />
</code></pre>
<p><strong>fragment_show_place.xml</strong></p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:id="@+id/listView_places"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
</code></pre>
<p><strong>fragment_maps.xml</strong></p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="@+id/mymap"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</code></pre>
<p>I want to show maps on listview's item click...so, I have implemented two fragments as follows:</p>
<p>In <strong>PlaceholderFragment.java</strong>, I have set <code>onitemclicklistener</code> as: </p>
<pre><code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_show_place, container, false);
final MySqliteHelper db = new MySqliteHelper(getActivity().getBaseContext());
listview_places = (ListView)rootView.findViewById(R.id.listView_places);
final PlacesAdapter places_adapter = new PlacesAdapter(getActivity(),R.layout.listview_item_row,places);
listview_places.setAdapter(places_adapter);
listview_places.setLongClickable(true);
listview_places.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position,long id) {
Place place = places_adapter.getItem(position);
String dbvaluename = place.getname();
Place selectedplace = db.getPlace(dbvaluename);
dblatitude = selectedplace.getlatitude();
dblongitude = selectedplace.getlongitude();
dbplacename = place.getname();
maps = new MapsFragment();
Bundle bundle = new Bundle();
bundle.putDouble("dbplacename",dblatitude);
bundle.putDouble("dbplacename",dblongitude);
bundle.putString("dbplacename",dbplacename);
maps.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container_showplaces,maps);
ft.addToBackStack(null);
ft.commit();
}
});
}
}
</code></pre>
<p>and In <strong>MapsFragment.java</strong>, I have shown maps as:</p>
<pre><code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_maps, container, false);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
</code></pre>
<p>When I click first time on ListView's item, it shows the Map...Then, when I select another item, it crashes:</p>
<p><strong>Logcat log:</strong></p>
<blockquote>
<p>android.view.InflateException: Binary XML file line #7: Error
inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at com.krupal.rememberthisplace.MapsFragment.onCreateView(MapsFragment.java:40)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:828)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1032)
at android.app.BackStackRecord.run(BackStackRecord.java:622)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1382)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IllegalArgumentException: Binary XML file line #7: Duplicate
id 0x7f0b001e, tag null, or parent id 0xffffffff with another fragment
for com.google.android.gms.maps.MapFragment
at android.app.Activity.onCreateView(Activity.java:4248)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:673)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at com.krupal.rememberthisplace.MapsFragment.onCreateView(MapsFragment.java:40)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:828)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1032)
at android.app.BackStackRecord.run(BackStackRecord.java:622)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1382)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
at dalvik.system.NativeStart.main(Native Method)</p>
</blockquote>
<p><strong>EDIT:</strong> <a href="https://stackoverflow.com/questions/14083950/duplicate-id-tag-null-or-parent-id-with-another-fragment-for-com-google-androi?rq=1">this</a> soloution didn't work for me</p>
| 0 | 3,480 |
How to fix `Warning: Text content did not match. Server: "Some Data" Client: "Loading..."`
|
<p>I'm getting this error on initial load of my SSR application:
<code>Warning: Text content did not match. Server: "SOME DATA" Client: "Loading..."</code>
How to initialize client side of the app without setting <code>loading</code> flag to true?</p>
<p>I’m setting up a SSR with react, express and apollo. I get a properly rendered HTML with data from the renderer server, but when client bundle loads up it’s trying to refetch data.
Hydration is set up and all the data from renderer server is injected into the HTML of the page.</p>
<p>/index.js</p>
<pre><code><Query query={GET_USERS} variables={queryVariables}>
{({
loading,
error,
data
}) => {
if (loading) return <p>Loading...</p>;
if (error) return `Error: ${error}`;
return data.users.map(user => <p key={user.id}>{user.login}</p>);
}}
</Query>
</code></pre>
<p>/renderer.js</p>
<pre><code>export default async (req, client) => {
const serverSideApp = (
<ApolloProvider client={client}>
<StaticRouter location={req.path} context={{}}>
<div>{renderRoutes(RoutesList)}</div>
</StaticRouter>
</ApolloProvider>
);
return getDataFromTree(serverSideApp).then(() => {
const content = renderToString(serverSideApp);
return `
<html>
<head></head>
<body>
<div id="root">${content}</div>
<script src="bundle.js"></script>
<script>
window.__APOLLO_STATE__=${serialize(client.extract())}
</script>
</body>
</html>
`;
})
};
</code></pre>
<p>/server.js</p>
<pre><code>const app = express();
app.use(express.static("public"));
app.get("*", (req, res) => {
const httpLink = createHttpLink({
uri: "http://10.10.10.139:4000/",
fetch
});
const client = new ApolloClient({
link: httpLink,
ssrMode: true,
cache: new InMemoryCache()
});
renderer(req, client).then((html) => res.send(html));
});
app.listen(3000, () => {
console.log("Server is up");
});
</code></pre>
<p>/client.js</p>
<pre><code>const httpLink = createHttpLink({
uri: "http://10.10.10.139:4000/"
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache().restore(window.__APOLLO_STATE__)
});
ReactDOM.hydrate(
<ApolloProvider client={client}>
<BrowserRouter>
<div>{renderRoutes(RoutesList)}</div>
</BrowserRouter>
</ApolloProvider>,
document.getElementById("root")
);
</code></pre>
<p>I expect client side of the app rehydrate server side values and not to trigger <code>loading</code> flag on initial load.</p>
| 0 | 1,461 |
p:commandButton in p:dataTable
|
<p>I got a problem with a p:commandButton inside a p:dataTable
My button does not call the procedure in my backing bean.
Does anyone have an idea why this button won't work?</p>
<p>Best Regards</p>
<p>Button Code:</p>
<pre><code> <p:column headerText="Details" style="width: 10px;">
<p:outputPanel id="buttonDetail">
<p:commandButton icon="ui-icon-vwfList"
styleClass="colButton"
action="#{customerChangeHistoryHandler.selectHistoryElement()}"
id="buttonDetail"
update=":historyDetail"
title="GO!!!">
</p:commandButton>
</p:outputPanel>
</p:column>
</code></pre>
<p>Full Code of JSF-Page:</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:m="http://java.sun.com/jsf/composite/components/mmnet">
<h:form id="historyList">
<p:dataTable id="historyTable"
value="#{customerChangeHistoryListHandler.dataModel}"
var="_history"
lazy="true"
paginator="true"
rows="20"
paginatorAlwaysVisible="false"
paginatorPosition="bottom"
rowsPerPageTemplate="5,10,15,20,25,50"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
selectionMode="single"
selection="#{customerChangeHistoryHandler.entity}"
style="margin-top:5px;">
<f:facet name="header">
<h:outputText value="#{labels.historie} (#{customerChangeHistoryListHandler.dataModel.rowCount})"/>
</f:facet>
<p:ajax event="rowSelect" listener="#{customerChangeHistoryHandler.onRowSelect}" update=":contentPanel"/>
<p:column headerText="#{labels.typ}"
style="width: 10px;">
<p:outputPanel id="buttonImage">
<p:commandButton icon="ui-icon-workflow"
styleClass="colButton"
action="#{customerChangeHistoryHandler.onRowSelect}"
update=":contentPanel"
rendered="#{_history.changeType == 'WORKFLOW_CHANGED' or _history.changeType == 'WORKFLOW_CREATED' or _history.changeType == 'WORKFLOW_DELETED'}">
</p:commandButton>
<p:commandButton icon="ui-icon-note"
styleClass="colButton"
action="#{customerChangeHistoryHandler.onRowSelect}"
update=":contentPanel"
rendered="#{_history.changeType == 'NOTE_CHANGED' or _history.changeType == 'NOTE_CREATED' or _history.changeType == 'NOTE_DELETED'}">
</p:commandButton>
<p:commandButton icon="ui-icon-diso"
styleClass="colButton"
action="#{customerChangeHistoryHandler.onRowSelect}"
update=":contentPanel"
rendered="#{_history.changeType == 'ERP_CHANGE'}">
</p:commandButton>
<p:commandButton icon="ui-icon-info"
styleClass="colButton"
action="#{customerChangeHistoryHandler.onRowSelect}"
update=":contentPanel"
rendered="#{_history.changeType == 'CUSTOMER_MERGED'}">
</p:commandButton>
<p:commandButton icon="ui-icon-arrowthickstop-1-s"
styleClass="colButton"
action="#{customerChangeHistoryHandler.onRowSelect}"
update=":contentPanel"
rendered="#{_history.changeType == 'FILE_UPLOADED'}">
</p:commandButton>
</p:outputPanel>
</p:column>
<p:column headerText="Details" style="width: 10px;">
<p:outputPanel id="buttonDetail">
<p:commandButton icon="ui-icon-vwfList"
styleClass="colButton"
action="#{customerChangeHistoryHandler.selectHistoryElement()}"
id="buttonDetail"
update=":historyDetail"
title="GO!!!">
</p:commandButton>
</p:outputPanel>
</p:column>
<p:column headerText="ChangeType"
sortBy="#{_history.changeType}">
<h:outputText value="#{labels[_history.changeType]}" />
</p:column>
<p:column headerText="#{labels.beschreibung}">
<h:outputText value="#{_history.description}" />
</p:column>
<p:column headerText="#{labels.modDate} und #{labels.modUser}"
sortBy="#{_history.modDate}">
<m:outputDateUser valueDate="#{_history.modDate}" valueUser="#{_history.modUser}" />
</p:column>
</p:dataTable>
</h:form>
<h:form id="historyDetail">
<p:panel id="detailPanel" rendered="#{customerChangeHistoryHandler.entity != null}">
History Detail --> ToDo
</p:panel>
</h:form>
</ui:composition>
</code></pre>
<p>Backing Bean:</p>
<pre><code>import javax.inject.Inject;
import javax.inject.Named;
import org.apache.myfaces.extensions.cdi.core.api.scope.conversation.ViewAccessScoped;
import org.primefaces.event.SelectEvent;
@Named
@ViewAccessScoped
public class CustomerChangeHistoryHandler extends JccPersistenceHandler<Integer, CustomerChangeHistory>{
@Inject
NewsMessageHandler newsMessageHandler;
@Inject
DebitorenakteState debitorenakteState;
@Inject
private WorkflowHandler workflowHandler;
@Override
protected Class<CustomerChangeHistory> getEntityType() {
return CustomerChangeHistory.class;
}
@Override
public CustomerChangeHistory getEntity() {
return super.getEntity();
}
@Override
public void onRowSelect(SelectEvent event) {
Integer tmpId = this.entity.getLinkedId();
try {
ChangeType tmpChangeType = this.entity.getChangeType();
if(tmpChangeType.equals(CustomerChangeHistory.ChangeType.WORKFLOW_CHANGED) || tmpChangeType.equals(CustomerChangeHistory.ChangeType.WORKFLOW_CREATED) || tmpChangeType.equals(CustomerChangeHistory.ChangeType.WORKFLOW_DELETED)){
workflowHandler.setSelectionId(tmpId);
workflowHandler.selectById();
workflowHandler.select();
} else if(tmpChangeType.equals(CustomerChangeHistory.ChangeType.NOTE_CHANGED) || tmpChangeType.equals(CustomerChangeHistory.ChangeType.NOTE_CREATED) || tmpChangeType.equals(CustomerChangeHistory.ChangeType.NOTE_DELETED)){
newsMessageHandler.setSelectionId(tmpId);
newsMessageHandler.selectById();
newsMessageHandler.onRowSelect(event);
debitorenakteState.setActivePage(DebitorenakteEnvironment.PAGE_MORE_NOTES);
debitorenakteState.setActiveTabIndex(6);
} else if(tmpChangeType.equals(CustomerChangeHistory.ChangeType.ERP_CHANGE)){
//TODO
} else if(tmpChangeType.equals(CustomerChangeHistory.ChangeType.CUSTOMER_MERGED)){
//TODO
} else if(tmpChangeType.equals(CustomerChangeHistory.ChangeType.FILE_UPLOADED)){
//TODO
} else {
logError("ChangeType nicht gefunden: " + this.entity.getChangeType().toString());
}
super.onRowSelect(event);
} catch (Exception e) {
// TODO: handle exception
jsfMessageService.info("Eintrag nicht mehr vorhanden", event);
}
}
public void selectHistoryElement(){
System.out.println("<-------------------------YEA, Button pressed!!! --------------------------------->");
// logDebug("Showing History Entity: " + this.entity);
}
}
</code></pre>
<hr>
<p>Is there a way to let the bean for the data model RequestScoped?</p>
| 0 | 5,868 |
Maven error : Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher
|
<p>I'd been stuck with this simple issue for an hour now. Maven was working fine last week, I don't know what went wrong it gives me this error. I tried all the ways to debug and all the solutions found in StackOverflow and many other places. I even tried replacing M2_HOME path with M3_HOME and MAVEN_HOME. Nothing worked. I'm on OS X. Below is the output of few maven commands. I'll be happy to provide more information</p>
<pre><code>$ mvn
Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher
$ which mvn
/Library/Maven-3.3.3/bin/mvn
$ echo $M2_HOME
/Library/Maven-3.3.3
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home
$ which java
/usr/bin/java
$ /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home/bin/java -version
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)
$ echo $PATH
/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Tomcat/bin:/Library/Maven-3.3.3/bin
$ java -version
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)
$ ls -lR /Library/Maven-3.3.3
total 56
-rw-r--r--@ 1 USERNAME wheel 19091 Apr 22 04:58 LICENSE
-rw-r--r--@ 1 USERNAME wheel 182 Apr 22 04:58 NOTICE
-rw-r--r--@ 1 USERNAME wheel 2541 Apr 22 04:55 README.txt
drwxr-xr-x@ 8 USERNAME wheel 272 Oct 14 12:24 bin
drwxr-xr-x@ 3 USERNAME wheel 102 Oct 14 12:24 boot
drwxr-xr-x@ 5 USERNAME wheel 170 Apr 22 04:55 conf
drwxr-xr-x@ 75 USERNAME wheel 2550 Oct 14 12:24 lib
/Library/Maven-3.3.3/bin:
total 64
-rw-r--r--@ 1 USERNAME wheel 230 Apr 22 04:58 m2.conf
-rwxr-xr-x@ 1 USERNAME wheel 7075 Apr 22 04:58 mvn
-rw-r--r--@ 1 USERNAME wheel 6007 Apr 22 04:58 mvn.cmd
-rwxr-xr-x@ 1 USERNAME wheel 1796 Apr 22 04:58 mvnDebug
-rw-r--r--@ 1 USERNAME wheel 1513 Apr 22 04:58 mvnDebug.cmd
-rwxr-xr-x@ 1 USERNAME wheel 1843 Apr 22 04:58 mvnyjp
/Library/Maven-3.3.3/boot:
total 104
-rw-r--r--@ 1 USERNAME wheel 52684 Aug 29 2014 plexus-classworlds-2.5.2.jar
/Library/Maven-3.3.3/conf:
total 32
drwxr-xr-x@ 3 USERNAME wheel 102 Apr 22 04:55 logging
-rw-r--r--@ 1 USERNAME wheel 10216 Apr 22 04:55 settings.xml
-rw-r--r--@ 1 USERNAME wheel 3649 Apr 22 04:55 toolchains.xml
/Library/Maven-3.3.3/conf/logging:
total 8
-rw-r--r--@ 1 USERNAME wheel 1126 Apr 22 04:55 simplelogger.properties
/Library/Maven-3.3.3/lib:
total 18656
-rw-r--r--@ 1 USERNAME wheel 136324 Jan 29 2015 aether-api-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME wheel 12637 Apr 22 04:58 aether-api.license
-rw-r--r--@ 1 USERNAME wheel 36745 Jan 29 2015 aether-connector-basic-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME wheel 12637 Apr 22 04:58 aether-connector-basic.license
-rw-r--r--@ 1 USERNAME wheel 172998 Jan 29 2015 aether-impl-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME wheel 12637 Apr 22 04:58 aether-impl.license
-rw-r--r--@ 1 USERNAME wheel 30705 Jan 29 2015 aether-spi-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME wheel 12637 Apr 22 04:58 aether-spi.license
-rw-r--r--@ 1 USERNAME wheel 25355 Jan 29 2015 aether-transport-wagon-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME wheel 12637 Apr 22 04:58 aether-transport-wagon.license
-rw-r--r--@ 1 USERNAME wheel 146876 Jan 29 2015 aether-util-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME wheel 12637 Apr 22 04:58 aether-util.license
-rw-r--r--@ 1 USERNAME wheel 4467 May 7 2013 aopalliance-1.0.jar
-rw-r--r--@ 1 USERNAME wheel 44908 May 7 2013 cdi-api-1.0.jar
-rw-r--r--@ 1 USERNAME wheel 21837 Apr 22 04:58 cdi-api.license
-rw-r--r--@ 1 USERNAME wheel 41123 May 7 2013 commons-cli-1.2.jar
-rw-r--r--@ 1 USERNAME wheel 173587 May 7 2013 commons-io-2.2.jar
-rw-r--r--@ 1 USERNAME wheel 284220 May 7 2013 commons-lang-2.6.jar
drwxr-xr-x@ 3 USERNAME wheel 102 Apr 22 04:55 ext
-rw-r--r--@ 1 USERNAME wheel 2256213 Nov 1 2014 guava-18.0.jar
-rw-r--r--@ 1 USERNAME wheel 2497 May 7 2013 javax.inject-1.jar
-rw-r--r--@ 1 USERNAME wheel 293671 Jul 24 2013 jsoup-1.7.2.jar
-rw-r--r--@ 1 USERNAME wheel 3449 Apr 22 04:58 jsoup.license
-rw-r--r--@ 1 USERNAME wheel 5848 May 7 2013 jsr250-api-1.0.jar
-rw-r--r--@ 1 USERNAME wheel 18116 Apr 22 04:58 jsr250-api.license
-rw-r--r--@ 1 USERNAME wheel 66349 Apr 22 04:57 maven-aether-provider-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-aether-provider.license
-rw-r--r--@ 1 USERNAME wheel 55090 Apr 22 04:56 maven-artifact-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-artifact.license
-rw-r--r--@ 1 USERNAME wheel 14964 Apr 22 04:56 maven-builder-support-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-builder-support.license
-rw-r--r--@ 1 USERNAME wheel 286726 Apr 22 04:58 maven-compat-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-compat.license
-rw-r--r--@ 1 USERNAME wheel 631881 Apr 22 04:57 maven-core-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-core.license
-rw-r--r--@ 1 USERNAME wheel 86051 Apr 22 04:58 maven-embedder-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-embedder.license
-rw-r--r--@ 1 USERNAME wheel 160817 Apr 22 04:56 maven-model-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 176410 Apr 22 04:56 maven-model-builder-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-model-builder.license
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-model.license
-rw-r--r--@ 1 USERNAME wheel 46099 Apr 22 04:56 maven-plugin-api-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-plugin-api.license
-rw-r--r--@ 1 USERNAME wheel 25957 Apr 22 04:57 maven-repository-metadata-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-repository-metadata.license
-rw-r--r--@ 1 USERNAME wheel 43032 Apr 22 04:57 maven-settings-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 43154 Apr 22 04:57 maven-settings-builder-3.3.3.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-settings-builder.license
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 maven-settings.license
-rw-r--r--@ 1 USERNAME wheel 375267 Feb 20 2015 org.eclipse.sisu.inject-0.3.0.jar
-rw-r--r--@ 1 USERNAME wheel 12637 Apr 22 04:58 org.eclipse.sisu.inject.license
-rw-r--r--@ 1 USERNAME wheel 205404 Feb 20 2015 org.eclipse.sisu.plexus-0.3.0.jar
-rw-r--r--@ 1 USERNAME wheel 12637 Apr 22 04:58 org.eclipse.sisu.plexus.license
-rw-r--r--@ 1 USERNAME wheel 13350 May 7 2013 plexus-cipher-1.7.jar
-rw-r--r--@ 1 USERNAME wheel 21837 Apr 22 04:58 plexus-cipher.license
-rw-r--r--@ 1 USERNAME wheel 4211 May 7 2013 plexus-component-annotations-1.5.5.jar
-rw-r--r--@ 1 USERNAME wheel 62458 Oct 29 2014 plexus-interpolation-1.21.jar
-rw-r--r--@ 1 USERNAME wheel 28555 May 7 2013 plexus-sec-dispatcher-1.3.jar
-rw-r--r--@ 1 USERNAME wheel 21837 Apr 22 04:58 plexus-sec-dispatcher.license
-rw-r--r--@ 1 USERNAME wheel 243128 Oct 29 2014 plexus-utils-3.0.20.jar
-rw-r--r--@ 1 USERNAME wheel 399672 Feb 20 2015 sisu-guice-3.2.5-no_aop.jar
-rw-r--r--@ 1 USERNAME wheel 26084 Jul 24 2013 slf4j-api-1.7.5.jar
-rw-r--r--@ 1 USERNAME wheel 14853 Apr 22 04:58 slf4j-api.license
-rw-r--r--@ 1 USERNAME wheel 10680 Aug 17 2013 slf4j-simple-1.7.5.jar
-rw-r--r--@ 1 USERNAME wheel 14853 Apr 22 04:58 slf4j-simple.license
-rw-r--r--@ 1 USERNAME wheel 11432 Apr 21 06:27 wagon-file-2.9.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 wagon-file.license
-rw-r--r--@ 1 USERNAME wheel 2259073 Apr 21 06:32 wagon-http-2.9-shaded.jar
-rw-r--r--@ 1 USERNAME wheel 11787 Apr 21 06:27 wagon-http-shared-2.9.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 wagon-http-shared.license
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 wagon-http.license
-rw-r--r--@ 1 USERNAME wheel 53543 Apr 21 06:27 wagon-provider-api-2.9.jar
-rw-r--r--@ 1 USERNAME wheel 11358 Apr 22 04:58 wagon-provider-api.license
/Library/Maven-3.3.3/lib/ext:
total 8
-rw-r--r--@ 1 USERNAME wheel 152 Apr 22 04:55 README.txt
</code></pre>
| 0 | 3,768 |
Why incompatible version of Java EE error throw from WebSphere?
|
<p>I was using WebSphere Allication Server version 7.0.0.13 in deploying my application. The war was build using Ant version 1.8.2 to build the war and ear file. When I am installing my application through WebSphere, I hit the following error:</p>
<blockquote>
<p>The EAR file could be corrupt and/or incomplete. Make sure that the
application is at a compatible Java(TM) Platform, Enterprise Edition
(Java EE) level for the current version of WebSphere(R) Application
Server.</p>
<p>com.ibm.websphere.management.application.client.AppDeploymentException
[Root exception is org.eclipse.jst.j2ee.commonarchivecore.internal.exception.DeploymentDescriptorLoadException:
dd_in_ear_load_EXC_]</p>
</blockquote>
<p>May I know what cause the problem? Or did I miss configure something in Ant script? Below are the ANT script for compiling the WAR and EAR.</p>
<pre><code><target name="compilewar" description="generating war">
<war destfile="${dist.path}/WebApp.war" webxml="${source.path}/mywebapp/src/main/webapp/WEB-INF/web.xml">
<webinf dir="${source.path}/mywebapp/src/main/webapp/WEB-INF/" includes="**/*"/>
<lib dir="${dist.path}/" includes="*.jar"/>
<classes dir="${source.path}/mywebapp/src/main/resources/" includes="**/*"/>
<fileset dir="${source.path}/mywebapp/src/main/webapp/">
<include name="**/*.jsp"/>
</fileset>
<fileset dir="${source.path}/mywebapp/src/main/webapp/">
<include name="main/**/*"/>
</fileset>
</war>
</target>
<target name="compileear" description="Compile Ear file">
<ear destfile="${source.path}/myear/src/main/application/WebApp.ear" appxml="${svn.working.project.path}application.xml">
<metainf dir="${source.path}/mywebapp/src/main/webapp/META-INF"/>
<fileset dir="${dist.path}/" includes="*.war"/>
</ear>
</target>
</code></pre>
<p>THanks @!</p>
| 0 | 1,029 |
getting java.lang.reflect.InvocationTargetException while adding a button to layout
|
<p>I am totally new in javafx!!
I tried a very very simple code and I got stuck.
when I tried to add a button to the layout It does not work.
I know this question may be too simple but I really do not know how to fix it.
I would appreciated if you could help me.
This is my code:</p>
<pre><code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Test extends Application{
Button button;
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("Title");
StackPane layout = new StackPane();
button = new Button();
layout.getChildren().add(button);
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}
}
</code></pre>
<p>and I got the error:</p>
<pre><code>Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.scene.control.ControlHelper (in unnamed module @0x46b3f4cf) cannot access class com.sun.javafx.scene.layout.RegionHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene.layout to unnamed module @0x46b3f4cf
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:802)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:623)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at javafx.scene.control.Control.<clinit>(Control.java:86)
at Test.start(Test.java:21)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more
Exception running application Test
</code></pre>
| 0 | 1,638 |
How to use NPM and install packages inside Visual Studio 2017?
|
<p>I have a simple Visual Studio solution, running ASP.NET Core v2 and building a React app.</p>
<p>Now, I want to install a simple component using the NPM. In this particular example, it could be:</p>
<pre><code>npm install --save react-bootstrap-typeahead
</code></pre>
<p>I want this package to work just in my solution and nowhere else.</p>
<p><strong>My result:</strong></p>
<p>When I run this, I get the following nice error which obviously makes some sense. If NPM believes it can find my project file at <code>'C:\Users\LarsHoldgaard\package.json'</code>, it's out of luck. The correct path would be <code>C:\Users\LarsHoldgaard\Documents\Github\Likvido.CreditRisk\Likvido.CreditRisk\Likvido.CreditRisk</code> .</p>
<pre><code>npm : npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\LarsHoldgaard\package.json'
At line:1 char:1
+ npm install --save react-bootstrap-typeahead
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (npm WARN saveEr...d\package.json':String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
npm
WARN
enoent
ENOENT: no such file or directory, open 'C:\Users\LarsHoldgaard\package.json'
npm
WARN
grunt-sass@2.0.0 requires a peer of grunt@>=0.4.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
react-rating@1.0.6 requires a peer of react@>=0.13.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
react-bootstrap-typeahead@2.5.1 requires a peer of react@^0.14.0 || ^15.2.0 || ^16.0.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
react-bootstrap-typeahead@2.5.1 requires a peer of react-dom@^0.14.0 || ^15.2.0 || ^16.0.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
prop-types-extra@1.0.1 requires a peer of react@>=0.14.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
react-overlays@0.8.3 requires a peer of react@^0.14.9 || >=15.3.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
react-overlays@0.8.3 requires a peer of react-dom@^0.14.9 || >=15.3.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
react-onclickoutside@6.7.1 requires a peer of react@^15.5.x || ^16.x but none is installed. You must install peer dependencies yourself.
npm
WARN
react-onclickoutside@6.7.1 requires a peer of react-dom@^15.5.x || ^16.x but none is installed. You must install peer dependencies yourself.
npm
WARN
react-transition-group@2.2.1 requires a peer of react@>=15.0.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
react-transition-group@2.2.1 requires a peer of react-dom@>=15.0.0 but none is installed. You must install peer dependencies yourself.
npm
WARN
LarsHoldgaard No description
npm
WARN
LarsHoldgaard No repository field.
npm
WARN
LarsHoldgaard No README data
npm
WARN
LarsHoldgaard No license field.
</code></pre>
<p><strong>My thinking:</strong></p>
<p>Being a <strong>console noob</strong>, I would guess I just needed to change my current folder. But if I run <code>dir</code>, I am in the right folder, and I can see my <code>package.json</code> along with other files.</p>
<p>What is the right way to install components?</p>
| 0 | 1,123 |
My Java program is testing if integer is divisible by 3 or 5, but is just printing every integer, how do I fix it?
|
<p>I am not getting errors at all in my code but it is NOT doing what I want it to - at all. I understand that there is <a href="https://stackoverflow.com/questions/31106668/find-if-a-number-is-divisible-by-3-or-5-fizzbuzz">another question related to divisibility to 3 or 5</a> but I do not think the question relates, as our coding is built completely different. I also find that <a href="https://stackoverflow.com/questions/26700089/java-program-that-prints-out-numbers-that-are-divisible-by-other-numbers">this answer</a>, <a href="https://stackoverflow.com/questions/26675725/java-programming-divisibility-and-counting">this other answer</a>, <a href="https://stackoverflow.com/questions/13792435/java-program-divisibility-test-with-varification-how-do-i-write-this-in-text">or even this answer</a> are not helping me, either.</p>
<p>Anyway, I am trying to use a simple boolean expression to determine if an expression is true or not, then if it is true or not printing different lines. The intended look I would get is something like:</p>
<pre><code>3 is divisible by 3
3 is not divisible by 5
4 is not divisible by 3
4 is not divisible by 5
5 is not divisible by 3
5 is divisible by 5
and so on...
</code></pre>
<p>However, I'm getting this:</p>
<pre><code>3 is divisible by 3
3 is not divisible by 3
3 is divisible by 5
3 is not divisible by 5
and so on...
</code></pre>
<p>Initial problem can be found <a href="https://projecteuler.net/problem=1" rel="nofollow noreferrer">here.</a> Right now I am just experimenting with the code, trying to get myself to a better understanding of Java. I wanted to start by knowing how to separate integers that are divisible by the numbers from integers that are not divisible by the numbers and I figured the best way to test this was to print the lines out. I do not know if I am going in the right direction at ALL here. Can anyone either give me pointers on the current code I have, or some hints, such as links to the corresponding Java commands that I will have to use for this program to work. If you post code that works, so I can see what I should be doing, that is fine too but please explain it to me, then. I don't want to just know what to type, I am trying to develop a solid foundation of programming problem-solving.</p>
<p>Sorry if this is a terrible question, I am EXTREMELY new to programming in general and am completely self-teaching. Give me some pointers, and I can most definitely change the question!</p>
<pre><code>package multiplesof3and5;
public class InitialProgram {
public static void main(String[] args) {
// TODO Auto-generated method stub
int integer1;
integer1 = 0;
boolean divisibleby3 = (integer1 % 3) == 0;
boolean divisibleby5 = (integer1 % 5) == 0;
for( integer1=0; integer1<1000; integer1++){
if(divisibleby3 = true);{
System.out.println(integer1 + " can be divided by 3");}
if(divisibleby3 = false);{
System.out.println(integer1 + " cannot be divided by 3");}
if(divisibleby5 = true);{
System.out.println(integer1 + " can be divided by 5");}
if(divisibleby5 = false);{
System.out.println(integer1 + " cannot be divided by 5");
}
}
}
}
</code></pre>
| 0 | 1,145 |
Reactjs: how to modify dynamic child component state or props from parent?
|
<p>I'm essentially trying to make tabs in react, but with some issues.</p>
<p>Here's file <code>page.jsx</code></p>
<pre><code><RadioGroup>
<Button title="A" />
<Button title="B" />
</RadioGroup>
</code></pre>
<p><strong>When you click on button A, the RadioGroup component needs to de-select button B</strong>.</p>
<p>"Selected" just means a className from a state or property</p>
<p>Here's <code>RadioGroup.jsx</code>:</p>
<pre><code>module.exports = React.createClass({
onChange: function( e ) {
// How to modify children properties here???
},
render: function() {
return (<div onChange={this.onChange}>
{this.props.children}
</div>);
}
});
</code></pre>
<p>The source of <code>Button.jsx</code> doesn't really matter, it has a regular HTML radio button that triggers the native DOM <code>onChange</code> event</p>
<p><strong>The expected flow is:</strong></p>
<ul>
<li>Click on Button "A"</li>
<li>Button "A" triggers onChange, native DOM event, which bubbles up to RadioGroup</li>
<li>RadioGroup onChange listener is called</li>
<li><strong>RadioGroup needs to de-select button B</strong>. This is my question.</li>
</ul>
<p>Here's the main problem I'm encountering: I <strong>cannot move <code><Button></code>s into <code>RadioGroup</code></strong>, because the structure of this is such that the children are <strong>arbitrary</strong>. That is, the markup could be</p>
<pre><code><RadioGroup>
<Button title="A" />
<Button title="B" />
</RadioGroup>
</code></pre>
<p>or</p>
<pre><code><RadioGroup>
<OtherThing title="A" />
<OtherThing title="B" />
</RadioGroup>
</code></pre>
<p><strong>I've tried a few things.</strong></p>
<p><strong>Attempt:</strong> In <code>RadioGroup</code>'s onChange handler:</p>
<pre><code>React.Children.forEach( this.props.children, function( child ) {
// Set the selected state of each child to be if the underlying <input>
// value matches the child's value
child.setState({ selected: child.props.value === e.target.value });
});
</code></pre>
<p><strong>Problem:</strong></p>
<pre><code>Invalid access to component property "setState" on exports at the top
level. See react-warning-descriptors . Use a static method
instead: <exports />.type.setState(...)
</code></pre>
<hr>
<p><strong>Attempt:</strong> In <code>RadioGroup</code>'s onChange handler:</p>
<pre><code>React.Children.forEach( this.props.children, function( child ) {
child.props.selected = child.props.value === e.target.value;
});
</code></pre>
<p><strong>Problem:</strong> Nothing happens, even I give the <code>Button</code> class a <code>componentWillReceiveProps</code> method</p>
<hr>
<p><strong>Attempt:</strong> I attempted to pass some specific state of the parent to the children, so I can just update the parent state and have the children respond automatically. In the render function of RadioGroup:</p>
<pre><code>React.Children.forEach( this.props.children, function( item ) {
this.transferPropsTo( item );
}, this);
</code></pre>
<p><strong>Problem:</strong></p>
<pre><code>Failed to make request: Error: Invariant Violation: exports: You can't call
transferPropsTo() on a component that you don't own, exports. This usually
means you are calling transferPropsTo() on a component passed in as props
or children.
</code></pre>
<hr>
<p><strong>Bad solution #1</strong>: Use react-addons.js <a href="http://facebook.github.io/react/docs/clone-with-props.html" rel="noreferrer">cloneWithProps</a> method to clone the children at render time in <code>RadioGroup</code> to be able to pass them properties</p>
<p><strong>Bad solution #2</strong>: Implement an abstraction around HTML / JSX so that I can pass in the properties dynamically (kill me):</p>
<pre><code><RadioGroup items=[
{ type: Button, title: 'A' },
{ type: Button, title: 'B' }
]; />
</code></pre>
<p>And then in <code>RadioGroup</code> dynamically build these buttons.</p>
<p><a href="https://stackoverflow.com/questions/21758103/react-passing-props-to-descendants">This question</a> doesn't help me because I need to render my children without knowing what they are</p>
| 0 | 1,512 |
Install APK using root, handling new limitations of "/data/local/tmp/" folder
|
<h2>Background</h2>
<p>So far, I was able to install APK files using root (within the app), via this code:</p>
<pre><code>pm install -t -f fullPathToApkFile
</code></pre>
<p>and if I want to (try to) install to sd-card :</p>
<pre><code>pm install -t -s fullPathToApkFile
</code></pre>
<h2>The problem</h2>
<p>Recently, not sure from which Android version (issue exists on Android P beta, at least), the above method fails, showing me this message:</p>
<pre><code>avc: denied { read } for scontext=u:r:system_server:s0 tcontext=u:object_r:sdcardfs:s0 tclass=file permissive=0
System server has no access to read file context u:object_r:sdcardfs:s0 (from path /storage/emulated/0/Download/FDroid.apk, context u:r:system_server:s0)
Error: Unable to open file: /storage/emulated/0/Download/FDroid.apk
Consider using a file under /data/local/tmp/
Error: Can't open file: /storage/emulated/0/Download/FDroid.apk
Exception occurred while executing:
java.lang.IllegalArgumentException: Error: Can't open file: /storage/emulated/0/Download/FDroid.apk
at com.android.server.pm.PackageManagerShellCommand.setParamsSize(PackageManagerShellCommand.java:306)
at com.android.server.pm.PackageManagerShellCommand.runInstall(PackageManagerShellCommand.java:884)
at com.android.server.pm.PackageManagerShellCommand.onCommand(PackageManagerShellCommand.java:138)
at android.os.ShellCommand.exec(ShellCommand.java:103)
at com.android.server.pm.PackageManagerService.onShellCommand(PackageManagerService.java:21125)
at android.os.Binder.shellCommand(Binder.java:634)
at android.os.Binder.onTransact(Binder.java:532)
at android.content.pm.IPackageManager$Stub.onTransact(IPackageManager.java:2806)
at com.android.server.pm.PackageManagerService.onTransact(PackageManagerService.java:3841)
at android.os.Binder.execTransact(Binder.java:731)
</code></pre>
<p>This seems to also affect popular apps such as "<a href="https://play.google.com/store/apps/details?id=com.keramidas.TitaniumBackup&hl=en" rel="noreferrer"><strong>Titanium backup</strong></a> (pro)", which fails to restore apps.</p>
<h2>What I've tried</h2>
<p>Looking at what's written, it appears it lacks permission to install APK files that are not in <code>/data/local/tmp/</code>.</p>
<p>So I tried the next things, to see if I can overcome it:</p>
<ol>
<li>set the access to the file (<code>chmod 777</code>) - didn't help.</li>
<li>grant permissions to my app, of both storage and <a href="https://developer.android.com/reference/android/Manifest.permission.html#REQUEST_INSTALL_PACKAGES" rel="noreferrer"><strong>REQUEST_INSTALL_PACKAGES</strong></a> (using <a href="https://developer.android.com/reference/android/provider/Settings#ACTION_MANAGE_UNKNOWN_APP_SOURCES" rel="noreferrer"><strong>ACTION_MANAGE_UNKNOWN_APP_SOURCES</strong></a> Intent) - didn't help.</li>
<li><p>create a symlink to the file, so that it will be inside the <code>/data/local/tmp/</code>, using official API:</p>
<pre><code> Os.symlink(fullPathToApkFile, symLinkFilePath)
</code></pre>
<p>This didn't do anything.</p></li>
<li><p>create a symlink using this :</p>
<pre><code> ln -sf $fullPathToApkFile $symLinkFilePath
</code></pre>
<p>This partially worked. The file is there, as I can see it in Total Commander app, but when I try to check if it exists there, and when I try to install the APK from there, it fails. </p></li>
<li><p>Copy/move (using <code>cp</code> or <code>mv</code>) the file to the <code>/data/local/tmp/</code> path, and then install from there. This worked, but it has disadvantages: moving is risky because it temporarily hides the original file, and it changes the timestamp of the original file. Copying is bad because of using extra space just for installing (even temporarily) and because it wastes time in doing so.</p></li>
<li><p>Copy the APK file, telling it to avoid actual copy (meaning hard link), using this command (taken from <a href="https://superuser.com/a/220216/152400"><strong>here</strong></a>) :</p>
<pre><code> cp -p -r -l $fullPathToApkFile $tempFileParentPath"
</code></pre>
<p>This didn't work. It got me this error:</p>
<pre><code> cp: /data/local/tmp/test.apk: Cross-device link
</code></pre></li>
<li><p>Checking what happens in other cases of installing apps. When you install via via the IDE, it actually does create the APK file in this special path, but if you install via the Play Store, simple APK install (via Intent) or adb (via PC), it doesn't.</p></li>
<li><p>Wrote about this here too: <a href="https://issuetracker.google.com/issues/80270303" rel="noreferrer">https://issuetracker.google.com/issues/80270303</a></p></li>
</ol>
<h2>The questions</h2>
<ol>
<li><p>Is there any way to overcome the disadvantages of installing the APK using root on this special path? Maybe even avoid handling this path at all?</p></li>
<li><p>Why does the OS suddenly require to use this path? Why not use the original path instead, just like in the other methods of installing apps? What do the other methods of installing apps do, that somehow avoids using the spacial path?</p></li>
</ol>
| 0 | 1,713 |
Why am I receiving a "Plugin execution not covered by lifecycle configuration with GWT" error?
|
<p>I'm using STS and I imported a GWT project from another machine. The project uses m2eclipse. I'm getting these two errors when building the project:</p>
<pre><code>Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:gwt-maven-plugin:2.2.0:i18n (execution: default, phase: generate-sources) pom.xml /contactsgwt line 175
Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-war-plugin:2.1.1:exploded (execution: default, phase: compile) pom.xml /contactsgwt line 198
</code></pre>
<p>What's wrong? Is there any further configuration that needs to be done so the <code>gwt maven plugin</code> works?</p>
<p>The <code>pom.xml</code> code causing the error: </p>
<pre class="lang-xml prettyprint-override"><code><!-- GWT Maven Plugin -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<version>2.2.0</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test</goal>
<goal>i18n</goal>
</goals>
</execution>
</executions>
<!-- Plugin configuration. There are many available options, see gwt-maven-plugin documentation at codehaus.org -->
<configuration>
<runTarget>Contacts.html</runTarget>
<hostedWebapp>${webappDirectory}</hostedWebapp
<i18nMessagesBundle>es.indra.gwt.contactsgwt.client.ContactsMessages</i18nMessagesBundle>
</configuration>
</plugin>
<!-- Copy static web files before executing gwt:run -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>exploded</goal>
</goals>
</execution>
</executions>
<configuration>
<webappDirectory>${webappDirectory}</webappDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.maven.ide.eclipse</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>0.9.9-SNAPSHOT</version>
<configuration>
<mappingId>generic</mappingId>
<configurators></configurators>
<mojoExecutions>
<mojoExecution runOnIncremental="true">org.codehaus.mojo:gwt-maven-plugin:2.2.0:i18n</mojoExecution>
<mojoExecution runOnIncremental="true">org.apache.maven.plugins:maven-resources-plugin:2.4.1:resources</mojoExecution>
<mojoExecution runOnIncremental="false">org.apache.maven.plugins:maven-compiler-plugin:2.0.2:compile</mojoExecution>
<mojoExecution runOnIncremental="false">org.apache.maven.plugins:maven-war-plugin:2.1.1:exploded</mojoExecution>
<mojoExecution runOnIncremental="false">org.apache.maven.plugins:maven-resources-plugin:2.4.1:testResources</mojoExecution>
</mojoExecutions>
</configuration>
</plugin>
</code></pre>
| 0 | 1,646 |
Adding Spaces between words and making every word except the first lowercase in java
|
<p>I'll go ahead and let you know that yes, this is homework. I have hit a brick wall in completing it however and desperately need help. I'm also pretty new to Java and am still learning the language.</p>
<p>Okay, I am trying to write a program that asks the user to enter a sentence with no spaces but have them capitalize the first letter of each word. The program should then add spaces between the words and have only the first word capitalized, the rest should start with a lowercase. I can get the space inserted between the words, but I cannot get the first letter of each word lower-cased. I have tried several different ways, and the latest one is giving me this error message:</p>
<pre><code> Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 72
at java.lang.AbstractStringBuilder.setCharAt(Unknown Source)
at java.lang.StringBuilder.setCharAt(Unknown Source)
at renfroKristinCh9PC14.main(renfroKristinCh9PC14.java:45)
</code></pre>
<p>I'm posting up my code and any and all help you can give me will be very much appreciated.
Thanks.</p>
<pre><code>/*
This program will ask the user to enter a sentence without whitespaces, but
with the first letter of each word capitilized. It will then separate the words
and have only the first word of the sentence capitalized.
*/
import java.util.*;
public class renfroKristinCh9PC14
{
public static void main(String[] args)
{
//a string variable to hold the user's input and a variable to hold the modified sentence
String input = "";
//variable to hold a character
char index;
//create an instance of the scanner class for input
Scanner keyboard = new Scanner(System.in);
//welcome the user and explain the program
userWelcome();
//get the sentence from the user
System.out.println("\n Please enter a sentence without spaces but with the\n");
System.out.println(" first letter of each word capitalized.\n");
System.out.print(" Example: BatmanIsTheBestSuperheroEver! ");
input = keyboard.nextLine();
//create an instance of the StringBuilder class
StringBuilder sentence = new StringBuilder(input);
//add spaces between the words
for(int i=0; i < sentence.length(); i++)
{
index = sentence.charAt(i);
if(i != 0 && Character.isUpperCase(index))
{
sentence.setCharAt(index, Character.toLowerCase(index));
sentence.append(' ');
}
sentence.append(index);
}
//show the new sentence to the user
System.out.println("\n\n Your sentence is now: "+sentence);
}
/*********************************************************************************** *************************
************************************************************************************ *************************
This function welcomes the user and exlains the program
*/
public static void userWelcome()
{
System.out.println("\n\n **************** ****************************************************\n");
System.out.println(" * Welcome to the Word Seperator Program *");
System.out.println(" * This application will ask you to enter a sentence without *");
System.out.println(" * spaces but with each word capitalized, and will then alter the *");
System.out.println(" * sentence so that there arespaces between each word and *");
System.out.println(" * only the first word of the sentence is capitalized *");
System.out.println("\n ********************************************************************\n");
}
</code></pre>
<p>}</p>
| 0 | 1,132 |
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.dict' is not mapped
|
<p>I'm trying to insert a new User into a DB using SQLAlchemy and Marshmallow. The <code>user</code> parameter is received from an API endpoint. Everything works until I get to this line in the <code>create</code> function:</p>
<pre><code>db.session.add(new_user)
</code></pre>
<p>The value of the <code>new_user</code> variable at that point is:</p>
<pre><code>{'password': 'string', 'email': 'fave@string', 'username': 'string'}
</code></pre>
<p>Function:</p>
<pre><code>def create(user):
uname = user.get('username')
email = user.get('email')
password = user.get ('password')
existing_username = User.query.filter(User.username == uname).one_or_none()
if existing_username is None:
schema = UserSchema()
new_user = schema.load(user, session=db.session)
db.session.add(new_user) <- It fails here
db.session.commit()
return schema.dump(new_user), 201
</code></pre>
<p>Models:</p>
<pre><code> class User (db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
profile_picture = db.Column(db.String(20), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
creation_date = db.Column(db.DateTime(120), nullable=False, default=datetime.utcnow)
updated_date = db.Column(db.DateTime(120), nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return f"User ('{self.username}','{self.email}','{self.profile_picture}') "
</code></pre>
<pre><code> class Post (db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime(120), nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Post ('{self.title}','{self.date_posted}') "
</code></pre>
<p>Schema:</p>
<pre><code>class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = User
sqla_session = db.session
</code></pre>
<p>Part of the console errors that I think are relevant:</p>
<pre><code>127.0.0.1 - - [14/May/2020 21:33:35] "POST /api/v1/users HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1975, in add
state = attributes.instance_state(instance)
AttributeError: 'dict' object has no attribute '_sa_instance_state'
The above exception was the direct cause of the following exception:
.
.
.
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/connexion/decorators/parameter.py", line 121, in wrapper
return function(**kwargs)
File "/Users/user/development/flask/apis/src/users.py", line 100, in create
db.session.add(new_user)
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1978, in add
exc.UnmappedInstanceError(instance), replace_context=err,
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.dict' is not mapped
</code></pre>
<p>I'm not sure why is throwing that <code>Class 'builtins.dict' is not mapped</code> error. Any tips?</p>
| 0 | 1,617 |
java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
|
<p>I'm trying to retrieve the data from the database. When I run the program it shows the error <code>java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException</code> I have the <code>json-lib</code> jar file in my <code>WEB-INF --> lib</code> directory, I don't know why it is showing this error for <code>JSONArray</code>.</p>
<p>My code is :</p>
<pre><code> StringBuilder sb=new StringBuilder(1024);
sb.append("select * from ").append(uname.trim()).append("vcomments").append(" where itemid=").append(itemId).append(" and albumid=").append(albumId);
sql=sb.toString();
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
//ArrayList<String> CommArray=new ArrayList();
JSONArray arrayObj=new JSONArray(); //#100
while(rs.next()){
Commenter comment = new Commenter();
comment.setUname(rs.getString("uname").trim());
comment.setComment(rs.getString("comments").trim());
arrayObj.add(comment.toString());
}
commentObj=gson.toJsonTree(arrayObj);
myObj.add("commentInfo", commentObj);
out.println(myObj.toString());
rs.close();
stmt.close();
stmt = null;
conn.close();
conn = null;
}
</code></pre>
<p>And the console output is :</p>
<pre><code> SEVERE: Servlet.service() for servlet [VComment] in context with path [/skypark] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2904)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at skypark.VComment.doGet(VComment.java:100)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
</code></pre>
<p>Please anyone tell me how to solve this problem......Thanks....</p>
| 0 | 1,770 |
Dynamically generate columns in PostgreSQL
|
<p>I have seen that there are quit a few similar questions like this one, but I havent understood how to code it myself. Please have in mind that I am just a beginner in this field.</p>
<p>Basically I want to pivot the table like this:</p>
<pre><code>zoom | day | point zoom | 2015-10-01 | 2015-10-02 | ......
------+-----------+------- ---> ------+------------+-------------+
1 | 2015-10-01 | 201 1 | 201 | 685 |
2 | 2015-10-01 | 43 2 | 43 | 346 |
3 | 2015-10-01 | 80 3 | 80 | 534 |
4 | 2015-10-01 | 324 4 | 324 | 786 |
5 | 2015-10-01 | 25 5 | 25 | 685 |
1 | 2015-10-02 | 685
2 | 2015-10-02 | 346
3 | 2015-10-02 | 534
4 | 2015-10-02 | 555
5 | 2015-10-02 | 786
:
:
:
</code></pre>
<p>Time can vary.</p>
<p>Results on left I get with:</p>
<pre><code>SELECT
zoom,
to_char(date_trunc('day', time), 'YYYY-MM-DD') AS day,
count(*) as point
FROM province
WHERE time >= '2015-05-01' AND time < '2015-06-01'
GROUP BY to_char(date_trunc('day', time), 'YYYY-MM-DD'), zoom;
</code></pre>
<p>I have read that there are some issues if I use <code>count</code> and also that it would be better if I use <code>CASE</code> and <code>GROUP BY</code>, however I have no idea how to <code>CASE</code> this.</p>
<p><code>Crosstab</code> itself doesnt support dynamic creation of column names, but that can be achieved with <code>crosstab_hash</code>, if I understood it correctly.</p>
<p>This might be probably nice solution: <a href="http://okbob.blogspot.ca/2008/08/using-cursors-for-generating-cross.html" rel="noreferrer">http://okbob.blogspot.ca/2008/08/using-cursors-for-generating-cross.html</a> however I am stucked with it trying to program it myself.</p>
<p>I have to use this kind of pivoting quite often, so I would appriciate any kind of help and additional explanation behind it.</p>
<p><strong>Edit1</strong></p>
<p>I am trying to figure out how crosstab works with dates, currently without returning dynamic names of columns. Later on I will explain why. It is realted to the main question. For this example I am using only period of 2 dates.</p>
<p>Based on @Erwin Brandstetter answer:</p>
<pre><code>SELECT * FROM crosstab(
'SELECT zoom, day, point
FROM province
ORDER BY 1, 2'
, $$VALUES ('2015-10-01'::date), ('2015-10-02')$$)
AS ct (zoom text, day1 int, day2 int);
</code></pre>
<p>returned results are:</p>
<pre><code>zoom | day1 | day2 |
-----+------------+-------------+
1 | 201 | 685 |
2 | 43 | 346 |
3 | 80 | 534 |
4 | 324 | 786 |
</code></pre>
<p>I am trying to get this</p>
<pre><code>zoom | 2015-10-01 | 2015-10-02 |
-----+------------+-------------+
1 | 201 | 685 |
2 | 43 | 346 |
3 | 80 | 534 |
4 | 324 | 786 |
</code></pre>
<p>but my query doesnt work:</p>
<pre><code>SELECT *
FROM crosstab(
'SELECT *
FROM province
ORDER BY 1,2')
AS ct (zoom text, "2015-10-01" date, "2015-10-02" date);
ERROR: return and sql tuple descriptions are incompatible
</code></pre>
<p><strong>Edit1, Q1. Why does this doesnt work and how can I return results like that?</strong></p>
<p>I have read links that @Erwin Brandstetter provided me, especially this one: <a href="https://stackoverflow.com/questions/36804551/execute-a-dynamic-crosstab-query/36831103#36831103">Execute a dynamic crosstab query</a>. I have copied/pasted his function:</p>
<pre><code>CREATE OR REPLACE FUNCTION pivottab(_tbl regclass,
_row text, _cat text,
_expr text,
_type regtype)
RETURNS text AS
$func$
DECLARE
_cat_list text;
_col_list text;
BEGIN
-- generate categories for xtab param and col definition list
EXECUTE format(
$$SELECT string_agg(quote_literal(x.cat), '), (')
, string_agg(quote_ident (x.cat), %L)
FROM (SELECT DISTINCT %I AS cat FROM %s ORDER BY 1) x$$
, ' ' || _type || ', ', _cat, _tbl)
INTO _cat_list, _col_list;
-- generate query string
RETURN format(
'SELECT * FROM crosstab(
$q$SELECT %I, %I, %s
FROM %I
GROUP BY 1, 2
ORDER BY 1, 2$q$
, $c$VALUES (%5$s)$c$
) ct(%1$I text, %6$s %7$s)'
, _row, _cat, _expr, _tbl, _cat_list, _col_list, _type
);
END
$func$ LANGUAGE plpgsql;
</code></pre>
<p>and call it with query</p>
<pre><code>SELECT pivottab('province','zoom','day','point','date');
</code></pre>
<p>Function returned me:</p>
<pre><code> pivottab
----------------------------------------------------------
SELECT * FROM crosstab( +
$q$SELECT zoom, day, point +
FROM province +
GROUP BY 1, 2 +
ORDER BY 1, 2$q$ +
, $c$VALUES ('2015-10-01'), ('2015-10-02')$c$ +
) ct(zoom text, "2015-10-01" date, "2015-10-02" date)
(1 row)
</code></pre>
<p>So when I edited the query and added ; (it would be nice that ; is already there) I got:</p>
<pre><code>ERROR: column "province.point" must appear in the GROUP BY clause or be used in an aggregate function
</code></pre>
<p><strong>Edit1, Q2. Any ideas how to solove this?</strong></p>
<p><strong>Edit1, Q3. I guess next question will be how to execute function automaticlly</strong>, which is also mentioned on the same link, but got stucked on previous steps.</p>
| 0 | 2,619 |
Spring websocket send to specific people
|
<p>I have added custom token based authentication for my spring-web app and extending the same for spring websocket as shown below</p>
<pre><code>public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(new ChannelInterceptorAdapter() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
String jwtToken = accessor.getFirstNativeHeader("Auth-Token");
if (!StringUtils.isEmpty(jwtToken)) {
Authentication auth = tokenService.retrieveUserAuthToken(jwtToken);
SecurityContextHolder.getContext().setAuthentication(auth);
accessor.setUser(auth);
//for Auth-Token '12345token' the user name is 'user1' as auth.getName() returns 'user1'
}
}
return message;
}
});
}
}
</code></pre>
<p>The client side code to connect to the socket is</p>
<pre><code>var socket = new SockJS('http://localhost:8080/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({'Auth-Token': '12345token'}, function (frame) {
stompClient.subscribe('/user/queue/greetings', function (greeting) {
alert(greeting.body);
});
});
</code></pre>
<p>And from my controller I am sending message as </p>
<pre><code>messagingTemplate.convertAndSendToUser("user1", "/queue/greetings", "Hi User1");
</code></pre>
<p>For the auth token <code>12345token</code> the user name is <code>user1</code>. But when I send a message to <code>user1</code>, its not received at the client end. Is there anything I am missing with this?</p>
| 0 | 1,046 |
Cannot set headers after they are sent to the client with express-validator, express, mongoose and Next.js
|
<p>I am building a login/registration form using <a href="https://express-validator.github.io/docs/custom-validators-sanitizers.html" rel="nofollow noreferrer">express-validator</a> and <a href="https://mongoosejs.com/docs/queries.html" rel="nofollow noreferrer">mongoose</a> in <a href="https://nextjs.org/" rel="nofollow noreferrer">next.js</a>. </p>
<p>Heard the best practice was to sanitize your data on the front <em>and</em> backend.</p>
<p>I have some validations on the frontend (i.e. checking if an email via Regex and making sure a password in a particular length). </p>
<p>But now I'd like to use <a href="https://express-validator.github.io/docs/custom-validators-sanitizers.html#custom-validator" rel="nofollow noreferrer">Custom validator</a> to check if a email exists in my mongodb database. </p>
<pre><code> .post(body('username').custom(value => {
UserModel.findOne({ 'email': value }).then(user => {
if (user) {
return Promise.reject('E-mail already in use');
}
});
}),
</code></pre>
<p>This is the rest of my code:</p>
<pre><code>var router = require('express').Router()
var UserModel = require('../models/UserModel')
var { body } = require('express-validator');
router
.route('/registration')
.get(function(req, res) {
UserModel.find({}, (err, users) => {
if (err) res.status(500).send(err)
res.json(users)
})
})
.post(body('username').custom(value => {
UserModel.findOne({ 'email': value }).then(user => {
if (user) {
return Promise.reject('E-mail already in use');
}
});
}), async(req, res, next) => {
try {
let newUser = new UserModel(req.body)
let savedUser = await newUser.save(err => {
if (err) return res.json({ success: false, error: err })
return res.json({ success: true })
})
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
module.exports = router
</code></pre>
<p>And this is the error I'm getting:</p>
<pre><code>Error: Failed to save user for unknown reasons
at router.route.get.post (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/users/index.js:34:25)
at process._tickCallback (internal/process/next_tick.js:68:7)
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:267:15)
at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/index.js:108:17
at Layer.handle_error (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:315:13)
at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:335:12)
at next (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:275:10)
at Layer.handle_error (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/layer.js:73:5)
at trim_prefix (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:315:13)
at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:335:12)
at Immediate.next (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:275:10)
at Immediate.<anonymous> (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:635:15)
at runCallback (timers.js:706:11)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
</code></pre>
<p>Also do I even need this when Mongoose provides when designing models/schema?</p>
<pre><code>var mongoose = require('mongoose')
var emailValidator = require('email-validator')
var bcrypt = require('bcrypt') // hashing function dedicated for passwords
const SALT_ROUNDS = 12
var UserSchema = new mongoose.Schema(
{
username_email: {
type: String,
required: true,
lowercase: true,
index: { unique: true }, // I mean this!
validate: {
validator: emailValidator.validate,
message: props => `${props.value} is not a valid email address`
}
},
password: {
type: String,
required: true,
trim: true,
index: { unique: true },
minlength: 8
}
},
{
timestamps: true
}
)
UserSchema.pre('save', async function preSave(next) {
var user = this
var hash
if (!user.isModified('password')) return next()
try {
hash = await bcrypt.hash(user.password, SALT_ROUNDS)
user.password = hash
return next()
} catch (err) {
return next(err)
}
})
UserSchema.methods.comparePassword = async function comparePassword(candidate) {
return bcrypt.compare(candidate, this.password)
};
module.exports = mongoose.model('User', UserSchema)
</code></pre>
<p>And if I don't does that mean checking if the email exists should be moved to the frontend? And If that's the case how would I approach that?</p>
<p><strong>UPDATE</strong></p>
<p>I tried Nick's suggestion but not sure why I'm still getting </p>
<pre><code>`Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
</code></pre>
<p>`
These are the updated routes:</p>
<pre><code>router
.route('/registration')
.get(function(req, res) {
console.log(0)
UserModel.find({}, (err, users) => {
console.log(1)
if (err) res.status(500).send(err)
console.log(2)
return res.json(users)
console.log(3)
})
})
.post(body('email').custom(value => {
console.log(4)
UserModel.findOne({ 'email': value }).then(user => {
console.log(5)
if (user) {
console.log(6)
return Promise.reject('E-mail already in use');
}
});
}), async(req, res, next) => {
console.log(7)
try {
let newUser = new UserModel(req.body)
let savedUser = await newUser.save(err => {
if (err) return res.json({ success: false, error: err })
console.log(8)
return res.json({ success: true })
})
console.log(9)
if (savedUser) return res.redirect('/users/registration?success=true');
console.log("savedUser ", savedUser);
console.log(10)
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
Note that pages will be compiled when you first load them.
GET /_next/static/webpack/d691821e71bf01c860e6.hot-update.json 404 299.194 ms - 1862
GET /_next/static/webpack/42c7a9cb77dec12fc8a3.hot-update.json 200 40.276 ms - 35
4
7
9
savedUser undefined
10
POST /users/registration 200 21.490 ms - 422
Error: Failed to save user for unknown reasons
at router.route.get.post (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/users/index.js:42:25)
at process._tickCallback (internal/process/next_tick.js:68:7)
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:267:15)
at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/index.js:108:17
at Layer.handle_error (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:315:13)
at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:335:12)
at next (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:275:10)
at Layer.handle_error (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/layer.js:73:5)
at trim_prefix (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:315:13)
at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:335:12)
at Immediate.next (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:275:10)
at Immediate.<anonymous> (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:635:15)
at runCallback (timers.js:706:11)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
5
6
(node:68936) UnhandledPromiseRejectionWarning: E-mail already in use
(node:68936) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:68936) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
^C
</code></pre>
| 0 | 4,501 |
ASP.NET Core: Create and Open PDF (in browser)
|
<p>Working in ASP.NET Core and using iTextSharp, I'm building a PDF and save it to the local system. I now want to open that file in the browser but can't seem to make that work since I get a FileStream error in one try and nothing at all in another try.</p>
<p>My logic is in the controller below. I've replaced the unnecessary code with <code>// region description</code>. The important code (the things I tried) is inside the <code>TODO: Open the file</code> region.</p>
<h1>Controller</h1>
<pre><code> [HttpPost]
public (JsonResult, IActionResult) CreatePDF([FromBody] ReportViewModel model)
{
try
{
// region Logic code
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
// Create the document
iTextSharp.text.Document document = new iTextSharp.text.Document();
// Place the document in the PDFWriter
iTextSharp.text.pdf.PdfWriter PDFWriter =
iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);
// region Initialize Fonts
// Open the document
document.Open();
// region Add content to document
// Close the document
document.Close();
#region Create and Write the file
// Create the directory
string directory = $"{_settings.Value.ReportDirectory}\\";
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(directory));
// region Create the fileName
// Combine the directory and the fileName
directory = System.IO.Path.Combine(directory, fileName);
// Create the file
byte[] content = memoryStream.ToArray();
using (System.IO.FileStream fs = System.IO.File.Create(directory))
{
fs.Write(content, 0, (int)content.Length);
}
#endregion
#region TODO: Open the file
// TRY: File(Stream, type) => Newtonsoft.Json.JsonSerializationException:
// Error getting value from 'ReadTimeout' on 'System.IO.FileStream'.
// ---> System.InvalidOperationException: Timeouts are supported for this stream.
System.IO.FileStream fileStream = new System.IO.FileStream(directory, System.IO.FileMode.Open);
var returnPDF = File(fileStream, contentType: "application/pdf");
// TRY: File(path, type) => Newtonsoft.Json.JsonSerializationException:
// Error getting value from 'ReadTimeout' on 'System.IO.FileStream'.
// ---> System.InvalidOperationException: Timeouts are supported for this stream.
returnPDF = File(System.IO.File.OpenRead(directory), contentType: "application/pdf" );
// TRY: File(byte[], type) => Nothing happened
returnPDF = File(content, contentType: "apllication/pdf");
#endregion
return ( Json(new { isError = false }), returnPDF );
}
}
catch (System.Exception ex)
{
Serilog.Log.Error($"ReportController.CreatePDF() - {ex}");
return ( Json(new { isError = true, errorMessage = ex.Message }), null );
}
}
</code></pre>
<h3>References to useful Stackoverflow answers</h3>
<ul>
<li><a href="https://stackoverflow.com/a/40488246/6761698">Return PDF to the Browser using Asp.net core</a></li>
<li><a href="https://stackoverflow.com/a/37465015/6761698">Open PDF in a new tab in browser</a></li>
<li><a href="https://stackoverflow.com/a/12865689/6761698">Web api controller method giving exception while serializing the Stream object</a></li>
<li><a href="https://stackoverflow.com/a/43069192/6761698">stream.ReadTimeout threw an exception of type System.InvalidOperationException</a></li>
</ul>
| 0 | 1,707 |
Rotating a rectangle-shaped Polygon around it's center. (Java)
|
<p>I have this code to draw a rectangle (Polygon object), and then draw another rectangle which is the original one, rotated 90 degrees, using the rotation matrix.</p>
<pre><code>public class DrawingPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Point p1,p2,p3,p4;
p1 = new Point(50,50);
p2 = new Point(200,50);
p3 = new Point(200,100);
p4 = new Point(50,100);
int[] x = {(int) p1.getX(), (int) p2.getX(), (int)p3.getX(), (int) p4.getX()};
int[] y = {(int) p1.getY(), (int) p2.getY(), (int)p3.getY(), (int) p4.getY()};
Polygon poly = new Polygon(x, y, x.length);
g2d.draw(poly);
p1.setLocation(p1.getX() * Math.cos(Math.toRadians(90)) - p1.getY() * Math.sin(Math.toRadians(90)),
p1.getX() * Math.sin(Math.toRadians(90)) + p1.getY() * Math.cos(Math.toRadians(90)));
p2.setLocation(p2.getX() * Math.cos(Math.toRadians(90)) - p2.getY() * Math.sin(Math.toRadians(90)),
p2.getX() * Math.sin(Math.toRadians(90)) + p2.getY() * Math.cos(Math.toRadians(90)));
p3.setLocation(p3.getX() * Math.cos(Math.toRadians(90)) - p3.getY() * Math.sin(Math.toRadians(90)),
p3.getX() * Math.sin(Math.toRadians(90)) + p3.getY() * Math.cos(Math.toRadians(90)));
p4.setLocation(p4.getX() * Math.cos(Math.toRadians(90)) - p4.getY() * Math.sin(Math.toRadians(90)),
p4.getX() * Math.sin(Math.toRadians(90)) + p4.getY() * Math.cos(Math.toRadians(90)));
int[] x2 = {(int) p1.getX(), (int) p2.getX(), (int)p3.getX(), (int) p4.getX()};
int[] y2 = {(int) p1.getY(), (int) p2.getY(), (int)p3.getY(), (int) p4.getY()};
Polygon poly2 = new Polygon(x2, y2, x2.length);
g2d.draw(poly2);
}
}
</code></pre>
<p>Currently, the second rectangle doesn't show up. When I asked about this in a different question, someone answered that that's because it draws outside the screen.</p>
<p>I asked how to rotate the rectangle around it's center, so the new drawing will appear in the screen, and he answered but I didn't really understand how to implement what he said in the code (tried different things that didn't work).</p>
<p>Could you show me exactly in the code, how to rotate the rectangle around it's center?</p>
<p>(Of course this isn't actual rotating of an object. It's making a rotated-duplicate of an object).</p>
<p>Help would be appreciated. Thanks</p>
| 0 | 1,119 |
Spring Boot Security CORS
|
<p>I have a problem with CORS filter on spring security URL's.
It doesn't set <code>Access-Control-Allow-Origin</code> and other exposed header on URL's belonging to spring sec (login/logout) or filtered by Spring Security.</p>
<p>Here are the configurations.</p>
<p><strong>CORS:</strong></p>
<pre><code>@Configuration
@EnableWebMvc
public class MyWebMvcConfig extends WebMvcConfigurerAdapter {
********some irrelevant configs************
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
.allowCredentials(true).maxAge(3600);
}
}
</code></pre>
<p><strong>Security:</strong></p>
<pre><code>@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/authentication").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}
}
</code></pre>
<p>So, if I make a request to the url's which are not listened by security - CORS headers are set. Spring security URL's - not set.</p>
<p><strong>Spring boot 1.4.1</strong></p>
| 0 | 1,070 |
java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment
|
<p>I am trying to move from one fragment to another.. It shows following error during fragment transaction-</p>
<pre><code> java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment PhotosFragment2{41a57218 #3 id=0x1020002}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:930)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Below are the classes.I have used following code for fragment transaction</p>
<pre><code>Fragment fragment = new PhotosFragment2();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
</code></pre>
<p>PhotosFragment.java</p>
<pre><code> public class PhotosFragment extends Fragment {
private FragmentActivity myContext;
@Override
public void onAttach(Activity activity) {
myContext = (FragmentActivity) activity;
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.photos, container, false);
rootView.setVerticalScrollBarEnabled(false);
int[] mThumbIds = {
R.drawable.album8, R.drawable.album3,
R.drawable.album4, R.drawable.album8,
R.drawable.album6, R.drawable.album7,
R.drawable.album12, R.drawable.album10,
};
int[] mThumbIds2 = {
R.drawable.album8, R.drawable.album3,
R.drawable.album4,
R.drawable.album6, R.drawable.album7,
R.drawable.album9, R.drawable.album10,
R.drawable.album11, R.drawable.album12, R.drawable.album8,
R.drawable.album8, R.drawable.album3,
R.drawable.album4,
R.drawable.album6, R.drawable.album7,
R.drawable.album9, R.drawable.album10,
R.drawable.album11, R.drawable.album12, R.drawable.album8,
};
CustomGridSingle2 adapter = new CustomGridSingle2(myContext, mThumbIds);
GridView grid = (GridView)rootView.findViewById(R.id.gridView);
final ImageView img= (ImageView)rootView.findViewById(R.id.imageView7);
grid.setFocusable(false);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new PhotosFragment2();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
});
CustomGridSingle2 adapter2 = new CustomGridSingle2(myContext, mThumbIds2);
GridView grid2 = (GridView)rootView.findViewById(R.id.gridView2);
grid2.setFocusable(false);
grid2.setAdapter(adapter2);
grid2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new PhotosFragment2();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
});
return rootView;
}
}
</code></pre>
<p>PhotosFragment2.java</p>
<pre><code>public class PhotosFragment2 extends Fragment {
private FragmentActivity myContext;
@Override
public void onAttach(Activity activity) {
myContext = (FragmentActivity) activity;
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.photos2, container, false);
myContext.getActionBar().hide();
return rootView;
}
}
</code></pre>
<p>Activity xml file</p>
<pre><code><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="@+id/left_drawer_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@drawable/bgmenu"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/profilelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:paddingTop="10dp">
<ImageView
android:id="@+id/drawer_profile_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/drawer_profile_background"
android:layout_alignLeft="@+id/drawer_profile_background"
android:layout_alignRight="@+id/drawer_profile_background"
android:layout_alignTop="@+id/drawer_profile_background"
android:layout_marginBottom="7.667dp"
android:layout_marginLeft="6.5dp"
android:layout_marginRight="8.3dp"
android:layout_marginTop="7.667dp"
android:scaleType="centerCrop"></ImageView>
<ImageView
android:id="@+id/drawer_profile_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:scaleType="centerCrop"
android:src="@drawable/profileblock">
</ImageView>
<ImageView
android:id="@+id/settingicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/drawer_profile_background"
android:layout_marginLeft="-15dp"
android:layout_toRightOf="@+id/drawer_profile_background"
android:background="@drawable/settings" />
<textview
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/drawer_profile_background"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="@android:color/white" />
</RelativeLayout>
<ListView
android:id="@+id/list_slidermenu"
style="@style/buttonStyle"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="30dp"
android:layout_weight="2"
android:cacheColorHint="@android:color/transparent"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="1dp"
android:listSelector="@android:color/transparent"
android:scrollbars="none" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</code></pre>
| 0 | 4,378 |
Redirect Loop error in CodeIgniter
|
<p>I worked on this for a day. I get this <a href="https://stackoverflow.com/questions/9157293/redirect-error-in-codeigniter">same problem</a>, but I don't understand.</p>
<pre><code><?php
class Users extends CI_Controller
{
function index()
{
redirect('Users/login');
}
function login()
{
$data['title'] = 'Selamat datang di Sistem Informasi Koperasi';
$data['main_content'] = 'login';
$this->load->view('Users/template', $data);
}
function logout()
{
$this->session->sess_destroy();
$this->session->set_flashdata('info_login', 'Anda sudah keluar dari sistem');
redirect('Users/login');
}
function validate()
{
//Load User Model
$this->load->model('Users_Model');
//Validate User
$query = $this->Users_Model->validate();
if($query != '') {
//Mengambil Roles dari Groups
$roles = $this->Users_Model->roles($query->group_id);
//$this->login_model->last_login($query);
$data = array(
'username' => $query->username,
'roles' => $roles,
'is_logged_in' => true
);
$this->session->set_userdata($data);
if($roles == 'administrators') {
redirect('Administrators/index');
} elseif($roles == 'managers') {
redirect('Managers/index');
}
else {
$this->session->set_flashdata('info_login', 'Mohon maaf anda belum terdaftar sebagai Group! Silahkan hubungi admin!');
redirect('Users/login');
}
} else {
$this->session->set_flashdata('info_login', 'Maaf,username dan password yang anda masukkan salah,silahkan coba kembali!');
redirect('Users/login');
}
}
}
</code></pre>
<p>In Chrome and Firefox I get this message. What should i do?</p>
<blockquote>
<p>This webpage has a redirect loop The webpage at
<code>http://localhost/simpks/index.php/Users/login</code> has resulted in too
many redirects. Clearing your cookies for this site or allowing
third-party cookies may fix the problem. If not, it is possibly a
server configuration issue and not a problem with your computer. Here
are some suggestions: Reload this webpage later. Learn more about this
problem. Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many
redirects.</p>
</blockquote>
<p>this is my view template.php</p>
<pre><code><?php
$this->load->view('includes/header',$main_content);
$this->load->view('Users/'.$main_content);
$this->load->view('includes/footer');
?>
</code></pre>
<p>this is my model Users_Model.php</p>
<pre><code> <?php
class Users_Model extends CI_Model{
function validate(){
$this->db->where('username',$this->input->post('username'));
$this->db->where('password',md5($this->input->post('password')));
$query = $this->db->get('Users');
if($query->num_rows == 1){
$row = $query->row();
return $row;
}
}
function roles($id){
$this->db->where('id',$id);
$query = $this->db->get('Groups');
if($query->num_rows == 1){
$row = $query->row();
return $row->name;
}
}
}
?>
</code></pre>
| 0 | 1,729 |
Partial page rendering with Primefaces - JSF 2.0 navigation
|
<p>I am trying to create a facelet page which updates <code><ui:insert></code> elements with ajax calls. Whenever a <code><p:commandButton action="next"/></code> is clicked ajax call should take place and only <code><ui:insert></code> parts of the facelet template should be updated. My question is exactly same as the question in <a href="https://stackoverflow.com/questions/5685354/partial-page-update-when-navigating-primefaces-ajax">here</a> but the solution over there does not work. Furthermore, considering the comment, it is quite ambiguous if the answer is accepted or not. I am stuck without any solution and not sure if this is related to <a href="http://www.primefaces.org/faq.html" rel="nofollow noreferrer">PrimeFaces FAQ#4</a> </p>
<p>I have another solution proposal with <code><ui:import></code> but not quite sure if this is a good solution. I am storing active page in a bean attribute and updating the value with ajax calls. So any comments and/or ideas are more than appreciated.
Here is my proposal: </p>
<h3>template.xhtml</h3>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title><ui:insert name="title" />
</title>
</h:head>
<h:body>
<div id="wrapper">
<div id="header">Primafaces Partial Page Update navigation</div>
<h:panelGroup id="content" layout="block">
<ui:insert name="content">
Sample content.
</ui:insert>
</h:panelGroup>
</div>
<div id="footer">Made using JSF &amp; Primefaces</div>
</h:body>
</html>
</code></pre>
<h3>main.xhtml</h3>
<pre><code><ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui" template="template.xhtml">
<ui:define name="title">Main page</ui:define>
<ui:define name="content">
<ui:include src="#{navBean.activePage}" />
</ui:define>
</ui:composition>
</code></pre>
<h3>NavigationBean.java</h3>
<pre><code>@Component("navBean")
@Scope("session")
public class NavigationBean implements Serializable{
private String activePage="firstAjax.xhtml";
public String getActivePage() {
return activePage;
}
public void setActivePage(String activePage) {
this.activePage = activePage;
}
public void next(ActionEvent e) {
this.setActivePage("lastAjax.xhtml");
}
public void back(ActionEvent e) {
this.setActivePage("firstAjax.xhtml");
}
}
</code></pre>
<h3>firstAjax.xhtml</h3>
<pre><code><ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h2>First Page!</h2>
<h:form>
<p>Click the button to go to next page!</p>
<p:commandButton value="Next"
actionListener="#{navBean.next}" update=":content" />
</h:form>
</ui:composition>
</code></pre>
<h3>lastAjax.xhtml</h3>
<pre><code><ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h2>Last Page!</h2>
<h:form>
<p>Click the Back button to go to previous page!</p>
<p:commandButton value="Back"
actionListener="#{navBean.back}" update=":content" />
</h:form>
</ui:composition>
</code></pre>
| 0 | 1,614 |
Use a simple c++ class in Android NDK
|
<p>I'm trying to learn the basics of Android NDK but I'm stucked when I have to use it with a c++ class.</p>
<p>I understand how to use it with a simple function but what should I do to be able to manipulate the fields and the methods of a c++ class ?</p>
<p>I'm trying to do it with this simple c++ class :</p>
<pre><code>#include <cstdlib>
#include <jni.h>
using namespace std;
class Point {
int x, y; // coordonnées du point
public:
Point() {
this->x = 0;
this->y = 0;
}
Point(int x, int y) {
this->x = x;
this->y = y;
}
int getX() const {
return x;
}
int getY() const {
return y;
}
Point symetrique() const {
return Point(-x, -y);
}
bool operator ==(const Point &p) const {
return this->x == p.getX() && this->y == p.getY();
}
};
extern "C" {
JNIEXPORT jlong JNICALL Java_com_example_jnipoint_JPoint_createPoint__
(JNIEnv *, jobject);
JNIEXPORT jlong JNICALL Java_com_example_jnipoint_JPoint_createPoint__II
(JNIEnv *, jobject, jint, jint);
JNIEXPORT jint JNICALL Java_com_example_jnipoint_JPoint_nativeGetX
(JNIEnv *, jobject, jlong);
JNIEXPORT jint JNICALL Java_com_example_jnipoint_JPoint_nativeGetY
(JNIEnv *, jobject, jlong);
JNIEXPORT jlong JNICALL Java_com_example_jnipoint_JPoint_nativeSymetrique
(JNIEnv *, jobject, jlong);
};
JNIEXPORT jlong JNICALL Java_com_example_jnipoint_JPoint_createPoint__(JNIEnv* env, jobject thiz) {
return (jlong)(new Point());
}
JNIEXPORT jlong JNICALL Java_com_example_jnipoint_JPoint_createPoint__II(JNIEnv* env, jobject thiz, jint x, jint y) {
return (jlong)(new Point(x, y));
}
JNIEXPORT jint JNICALL Java_com_example_jnipoint_JPoint_nativeGetX(JNIEnv* env, jobject thiz, jlong nativePointer) {
return ((Point*)nativePointer)->getX();
}
JNIEXPORT jint JNICALL Java_com_example_jnipoint_JPoint_nativeGetY(JNIEnv* env, jobject thiz, jlong nativePointer) {
return ((Point*)nativePointer)->getY();
}
jlong Java_com_example_jnipoint_JPoint_nativeSymetrique(JNIEnv* env, jobject thiz, jlong nativePointer) {
return ((Point*)nativePointer)->symetrique();
}
</code></pre>
<p>I tried to find samples but nothing so far... Maybe I'm not using the right keywords</p>
<p><em><strong></em>* UPDATE <em>*</em></strong></p>
<p>I created a Java wrapper for the c++ Point class and added to the c++ file JNI methods. The code is the following :</p>
<pre><code>public class JPoint {
private long nativePointer;
public JPoint() {
nativePointer = createPoint();
}
public JPoint(int x, int y) {
nativePointer = createPoint(x, y);
}
public int getX() {
return nativeGetX(nativePointer);
}
public int getY() {
return nativeGetY(nativePointer);
}
public JPoint symetrique() {
JPoint tmp = new JPoint();
tmp.nativePointer = nativeSymetrique(nativePointer);
return tmp;
}
// TODO
/*public boolean equals(Object o) {
return nativeEquals(o);
}*/
private native long createPoint(); // Void constructor
private native long createPoint(int x, int y);
private native int nativeGetX(long nativePointer);
private native int nativeGetY(long nativePointer);
private native long nativeSymetrique(long nativePointer);
//private native boolean nativeEquals(Object p); TODO
}
</code></pre>
<p>Right now I'm stucked with the nativeSymetrique function, it says that I cannot convert 'Point' to 'jlong'. Can anyone help me on this ? Thanks</p>
<p><em><strong></em>* UPDATE 2 <em>*</em></strong></p>
<p>SWIG solved my issues, you don't have to handwrite the wrappers and it seems to be a good choice for big libraries.</p>
| 0 | 1,593 |
Resize UILabel to fit text inside custom UITableViewCell regardless of width
|
<p>I'm trying to get a label in a cell to be the right size, regardless of device or orientation. I am able to get the row height to size correctly. I am also able to set the label height correctly in <code>cellForRowAtIndexPath</code>, and can check that in my logs. But, by the time it gets to <code>willDisplayRowAtIndexPath</code>, the label height has changed, but only when the cell is not 320 pts wide.</p>
<p>Here's my code-</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomCellIdentifier";
CustomInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
cell = [[CustomInfoCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
NSArray *objects = [[NSBundle mainBundle] loadNibNamed:@"CustomInfoCell" owner:self options:nil];
cell = objects[0];
}
// Configure the cell...
cell.customTitleLabel.text = [_data[indexPath.row] objectForKey:t];
CGFloat labelWidth = self.view.frame.size.width-40;
NSLog(@"labelWidth:%f",labelWidth);
NSString *text = [_data[indexPath.row] objectForKey:d];//correct text
CGSize labelsize=[text sizeWithFont:cell.customDetailLabel.font constrainedToSize:CGSizeMake(labelWidth, 2000.0) lineBreakMode:cell.customDetailLabel.lineBreakMode];
NSLog(@"labelsize:%f,%f",labelsize.width,labelsize.height);
//For testing
cell.customDetailLabel.backgroundColor = [UIColor redColor];
NSLog(@"Pre: %@",cell.customDetailLabel);
cell.customDetailLabel.frame=CGRectMake(20, 22, labelWidth, labelsize.height);
cell.customDetailLabel.text = text;
NSLog(@"Post: %@",cell.customDetailLabel);
return cell;
}
</code></pre>
<p>In <code>willDisplayRowAtIndexPath</code> I also print the label info. Here's what one row prints-</p>
<pre><code>2013-03-24 18:33:44.009 Bridge Alert[57793:1e503] labelWidth:728.000000
2013-03-24 18:33:44.010 Bridge Alert[57793:1e503] labelsize:713.000000,76.000000
2013-03-24 18:33:44.010 Bridge Alert[57793:1e503] Pre: <UILabel: 0xad3eaf0; frame = (20 20; 280 21); text = 'Detail'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x17372eb0>>
2013-03-24 18:33:44.011 Bridge Alert[57793:1e503] Post: <UILabel: 0xad3eaf0; frame = (20 22; 728 76); text = 'Detail'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x17372eb0>>
2013-03-24 18:33:44.011 Bridge Alert[57793:1e503] Text set: <UILabel: 0xad3eaf0; frame = (20 22; 728 76); text = 'A bridge is considered “f...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x17372eb0>>
2013-03-24 18:33:44.014 Bridge Alert[57793:1e503] Display:<UILabel: 0xad3eaf0; frame = (20 20; 728 190); text = 'A bridge is considered “f...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x17372eb0>>
</code></pre>
<p>As you can see, by Display, the label is resized. I'm assuming the height is recalculated somehow, based on if the cell were 320 pt wide, which is the built in UITableViewCell width.</p>
<p>How can I get the label to size correctly?</p>
| 0 | 1,193 |
AngularJS Controller execute twice
|
<p>I must add I am working on Sharepoint 2013, visual web part.
my ascx:</p>
<pre><code><%@ Control Language="C#" Inherits="SharePoint.BLL.UserControls.VODCatalog, SharePoint.BLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=81fc048468441ab3" %>
<%@ Register TagPrefix="SPWP" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<div ng-app="VODCatalogModule">
<div class="wrapper" ng-view="">
</div>
</div>
</code></pre>
<p>My JS:</p>
<pre><code>var VODCatalogModule = angular.module('VODCatalogModule', []);
var testWPDefinedView = 'TopLevelView';
VODCatalogModule.config(function ($routeProvider) {
$routeProvider.when('/TopLevelView', { controller: 'VODCatalogController', templateUrl: '/_catalogs/masterpage/html/VODCatalog_TopLevelView.html' })
.when('/LowLevelView', { controller: 'VODCatalogController', templateUrl: '/_catalogs/masterpage/html/VODCatalog_LowLevelView.html' })
.otherwise({ redirectTo: '/' + testWPDefinedView });
});
function VODCatalogController($scope, $http) {
$scope.VODCatalogLevel = 1;
$scope.BreadCrumbs = [];
$scope.MainCatalog = [];
$scope.NavCatalog = [];
$scope.crumbsVisible = $scope.BreadCrumbs.length == 0 ? "hidden" : "";
var getVODCatalogData = function (PARENT_VOD_CATALOG_GK, vodLevel) {
var url = "VODCatalogHandler.ashx?action=GetVODCatalogData&vodLevel=" + vodLevel;
if (PARENT_VOD_CATALOG_GK)
url += "&PARENT_VOD_CATALOG_GK=" + PARENT_VOD_CATALOG_GK;
$http.get(url, { cache: true })
.success(function (data, status, headers, config) {
setVODCatalogData(data, vodLevel);
}).error(function (data, status, headers, config) {
alert('ERROR in VODCatalogDataService get');
});
};
var setVODCatalogData = function (data, vodLevel) {
$scope.BreadCrumbs = data;
$scope.MainCatalog = data;
$scope.NavCatalog = data;
};
$scope.catalogItemClick = function (catalogItem) {
getVODCatalogData(catalogItem.VOD_CATALOG_GK, ++$scope.VODCatalogLevel);
};
getVODCatalogData(null, $scope.VODCatalogLevel);
}
VODCatalogModule.controller("VODCatalogController", VODCatalogController);
</code></pre>
<p>My view (VODCatalog_TopLevelView.html):</p>
<pre><code><section class="zebra brightBGcolor">
<div class="catalog">
<div class="centerPage">
<div class="pageTitle withBreadCrumbs">
<h3>VOD</h3>
<ul class="breadCrumbs {{ crumbsVisible }}">
<li>
<a href="#">VOD</a>
</li>
<li ng-repeat-start="crumb in BreadCrumbs">
<span>&nbsp;</span>
</li>
<li ng-repeat-end>
<a href="#">{{ crumb.NAME }}</a>
</li>
</ul>
</div>
<ul class="list inRow4 clearfix">
<li ng-repeat="catalogItem in MainCatalog" ng-click="catalogItemClick(catalogItem)">
<a class="box" href="#">
<img src="{{ catalogItem.MEDIA_URI_Complete}}" alt="">
<div class="textContainer">
<h4>{{ catalogItem.NAME }}</h4>
</div>
</a>
</li>
</ul>
</div>
</div>
</section>
</code></pre>
<p>At the start all looks great, it loads the 1st ajax call with all the pics and data.</p>
<p>Then when I click at one of the li's with the ng-click the 2nd ajax gets executed twice, once it gets the right data and immediately after it calls itself again with the initial call of getVODCatalogData(null, $scope.VODCatalogLevel); and brings back the old view.</p>
<p>When I tried to put something in module.run it also runs twice, can it help?</p>
<p>I would appreciate any hint and help as it is my 1st time with angular.</p>
<p>thx!
ariel</p>
<p>EDIT:
some more info - I put a log at the beginning of the controller and after the click the controller gets initialized again</p>
| 0 | 2,219 |
How to render a view inside of other twig + Modal Dialog Symfony2
|
<p>Today I wanna a show a <a href="http://bootboxjs.com/" rel="nofollow">modal dialog</a> with a form</p>
<p>This is my code of main:</p>
<pre class="lang-html prettyprint-override"><code><button class="btn btn-primary btn-lg btn-new" data-toggle="modal" data-target="#agregarPunto">
Nueva Ronda
</button>
<div style="display: none;" class="modal fade" id="agregarPunto" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Agregar ronda</h4>
</div>
<div class="modal-body">
{% embed "controlidMembersBundle:Members:newRonda.html.twig" %}
{% endembed %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-primary">Crear ronda</button>
</div>
</div>
</div>
</div>
</code></pre>
<p>This is the code of my view that I wanna embed</p>
<pre><code>{% block nueva_ronda -%}
<h1>Nueva ronda</h1>
{{ form(form) }}
<ul class="record_actions"></ul>
{% endblock %}
</code></pre>
<p>The trouble is when I click on the button, because I get the following error:</p>
<pre class="lang-php prettyprint-override"><code>Variable "form" does not exist in /var/www/html/controlid/src/controlid/Bundle/MembersBundle/Resources/views/Members/newRo nda.html.twig at line 5
</code></pre>
<p>This mistake is obviusly, because I don't know how to call the controller to render the form.</p>
<p>This is the action on symfony that should rendered the form</p>
<pre><code>/*
* @Route("/ronda/crear", name="members_ronda_new")
* @Method("GET")
* @Template()
*/
public function newRondaAction()
{
$entity = new Ronda();
$form = $this->createRondaForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
</code></pre>
<p>How to embed code inside of my <a href="http://bootboxjs.com/" rel="nofollow">modal-dialog</a> to render the form?</p>
| 0 | 1,181 |
Allocate exception for servlet Jersey REST Service Error
|
<p>I'm re-coding a webservice that I've already created so that I can create a "how-to" with git for the other members of my group who will be taking over the project.</p>
<p>This time around, I started to get an error when trying to use my webservice and I can't seem to find the problem because the code looks exactly like what I've previously coded (a code that worked).</p>
<p>I am using apache tomcat and Jersey with JSON.</p>
<p>Here is the error:</p>
<p><code>mai 14, 2015 6:08:02 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet Jersey REST Service
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1359)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:180)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:799)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:795)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1213)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:827)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)</code></p>
<p>Here is my web.xml file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>com.labtabdb.rest</display-name>
<welcome-file-list>
<welcome-file>readme.html</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.labtabdb.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/nxp/*</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>Here is a class that uses the @Path annotation:</p>
<pre><code>//url path for class it's methods/chemin url pour la classe et ses methodes
@Path ("/v1/inventory")
public class V1__inventory
{
@GET //url ending in only /v1/inventory /chemin terminé par /v1/inventory
@Produces(MediaType.APPLICATION_JSON)
public Response errorIfNoQueryParamSpecified() throws Exception
{
return Response
.status(400) //bad request
.entity("Error: Please specify extension and parameter for this search.")
.build();
}
/**
* Method that returns materials filter by material name
* @param material name
* @return Response
* @throws Exception
*/
@Path("/{material_label}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response returnMaterial(@PathParam("material_label") String material) throws Exception
{
material = URLDecoder.decode(material, "UTF-8"); //decode URL param
String returnString = null;
JSONArray json;
try
{
json = LabTab_MySQLQuerys
.getMaterialsByName(material);
//if there are no results to the query
if(json.length() == 0)
throw new CustomException("No results returned");
else //otherwise return results
returnString = json.toString();
}
catch(CustomException e)
{
return Response
.status(204)
.entity(e.getMessage())
.build();
}
catch (Exception e)
{
e.printStackTrace();
return Response
.status(500) //internal server error
.entity("Server was not able to process your request")
.build();
}
return Response
.ok(returnString)
.build();
}
</code></pre>
<p>I've been searching and reading the same articles over and over for 3 days now and I have yet to find a solution that solves my error.</p>
<p>All help is appreciated</p>
| 0 | 2,611 |
IntelliJ Error: java.lang.OutOfMemoryError: GC overhead limit exceeded
|
<p>I'm running Grails 2.5.0 on IntelliJ Idea Ultimate Edition 2020.2.2 . It compiles and builds the code just fine but it keeps throwing a "java.lang.OutOfMemoryError: GC overhead limit exceeded" error (the entire error is copy and pasted at the end). Here are the things I've tried based off researching this error:</p>
<p>1.) Increasing build process heap size (tried at 2G, 4G, and 6G)
<a href="https://intellij-support.jetbrains.com/hc/en-us/community/posts/360003315120-GC-overhead-limit-exceeded" rel="noreferrer">https://intellij-support.jetbrains.com/hc/en-us/community/posts/360003315120-GC-overhead-limit-exceeded</a></p>
<p>2.) Increasing memory heap size (tried at 2G, 4G, and 6G)
<a href="https://www.jetbrains.com/help/idea/increasing-memory-heap.html" rel="noreferrer">https://www.jetbrains.com/help/idea/increasing-memory-heap.html</a></p>
<p>3.) Increasing the maximum memory setting for the JVM in the launch configuration (tried at 2G, 4G, and 6G)</p>
<p>I saw that one of the fixes for this error is to "Reuse existing objects when possible to save some memory." However I believe strongly that this is not an issue with the code but with settings on my IDE. The code I am using works fine without errors on the production website and this OutOfMemoryError only appears on my local machine. I would appreciate any help anyone can give, thank you!!!</p>
<pre><code>2020-09-21 09:19:56.661 ERROR --- [nio-8805-exec-3] o.s.l.agent.SpringLoadedPreProcessor : Unexpected problem transforming call sites
org.springsource.loaded.ReloadException: Unexpected problem locating the bytecode for ch/qos/logback/classic/spi/IThrowableProxy.class
at org.springsource.loaded.TypeRegistry.couldBeReloadable(TypeRegistry.java:775)
at org.springsource.loaded.TypeRegistry.isReloadableTypeName(TypeRegistry.java:942)
at org.springsource.loaded.TypeRegistry.isReloadableTypeName(TypeRegistry.java:780)
at org.springsource.loaded.MethodInvokerRewriter$RewriteClassAdaptor$RewritingMethodAdapter.visitMethodInsn(MethodInvokerRewriter.java:1133)
at sl.org.objectweb.asm.ClassReader.a(Unknown Source)
at sl.org.objectweb.asm.ClassReader.b(Unknown Source)
at sl.org.objectweb.asm.ClassReader.accept(Unknown Source)
at sl.org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.springsource.loaded.MethodInvokerRewriter.rewrite(MethodInvokerRewriter.java:348)
at org.springsource.loaded.MethodInvokerRewriter.rewrite(MethodInvokerRewriter.java:99)
at org.springsource.loaded.TypeRegistry.methodCallRewriteUseCacheIfAvailable(TypeRegistry.java:1002)
at org.springsource.loaded.agent.SpringLoadedPreProcessor.preProcess(SpringLoadedPreProcessor.java:361)
at org.springsource.loaded.agent.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:107)
at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:55)
at ch.qos.logback.classic.spi.LoggingEvent.<init>(LoggingEvent.java:119)
at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:419)
at ch.qos.logback.classic.Logger.filterAndLog_0_Or3Plus(Logger.java:383)
at ch.qos.logback.classic.Logger.log(Logger.java:765)
at org.slf4j.bridge.SLF4JBridgeHandler.callLocationAwareLogger(SLF4JBridgeHandler.java:221)
at org.slf4j.bridge.SLF4JBridgeHandler.publish(SLF4JBridgeHandler.java:303)
at java.util.logging.Logger.log(Logger.java:738)
at java.util.logging.Logger.doLog(Logger.java:765)
at java.util.logging.Logger.logp(Logger.java:1042)
at org.apache.juli.logging.DirectJDKLog.log(DirectJDKLog.java:182)
at org.apache.juli.logging.DirectJDKLog.error(DirectJDKLog.java:148)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:251)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException: null
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springsource.loaded.TypeRegistry.couldBeReloadable(TypeRegistry.java:718)
... 54 common frames omitted
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.util.Arrays.copyOfRange(Arrays.java:3664)
at java.lang.String.<init>(String.java:207)
at java.lang.StringBuilder.toString(StringBuilder.java:407)
at java.io.UnixFileSystem.resolve(UnixFileSystem.java:108)
at java.io.File.<init>(File.java:367)
at sun.misc.URLClassPath$FileLoader.getResource(URLClassPath.java:1331)
at sun.misc.URLClassPath$FileLoader.findResource(URLClassPath.java:1301)
at sun.misc.URLClassPath.findResource(URLClassPath.java:225)
at java.net.URLClassLoader$2.run(URLClassLoader.java:572)
at java.net.URLClassLoader$2.run(URLClassLoader.java:570)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findResource(URLClassLoader.java:569)
at java.lang.ClassLoader.getResource(ClassLoader.java:1096)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springsource.loaded.TypeRegistry.couldBeReloadable(TypeRegistry.java:718)
at org.springsource.loaded.TypeRegistry.isReloadableTypeName(TypeRegistry.java:942)
at org.springsource.loaded.TypeRegistry.isReloadableTypeName(TypeRegistry.java:780)
at org.springsource.loaded.MethodInvokerRewriter$RewriteClassAdaptor$RewritingMethodAdapter.visitMethodInsn(MethodInvokerRewriter.java:1133)
at sl.org.objectweb.asm.ClassReader.a(Unknown Source)
at sl.org.objectweb.asm.ClassReader.b(Unknown Source)
at sl.org.objectweb.asm.ClassReader.accept(Unknown Source)
at sl.org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.springsource.loaded.MethodInvokerRewriter.rewrite(MethodInvokerRewriter.java:348)
at org.springsource.loaded.MethodInvokerRewriter.rewrite(MethodInvokerRewriter.java:99)
at org.springsource.loaded.TypeRegistry.methodCallRewriteUseCacheIfAvailable(TypeRegistry.java:1002)
at org.springsource.loaded.agent.SpringLoadedPreProcessor.preProcess(SpringLoadedPreProcessor.java:361)
at org.springsource.loaded.agent.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:107)
at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)
at java.lang.ClassLoader.defineClass1(Native Method)
2020-09-21 09:19:57.566 ERROR --- [nio-8805-exec-3] .a.c.c.C.[.[.[.[grailsDispatcherServlet] : Servlet.service() for servlet [grailsDispatcherServlet] in context with path [] threw exception
java.lang.reflect.UndeclaredThrowableException: null
at org.springframework.util.ReflectionUtils.rethrowRuntimeException(ReflectionUtils.java:316)
at org.grails.web.servlet.mvc.GrailsWebRequest.<init>(GrailsWebRequest.java:106)
at grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition.determineUrl(AnnotationFilterInvocationDefinition.groovy:106)
at grails.plugin.springsecurity.web.access.intercept.AbstractFilterInvocationDefinition.getAttributes(AbstractFilterInvocationDefinition.groovy:75)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:197)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at grails.plugin.springsecurity.web.filter.GrailsHttpPutFormContentFilter.doFilterInternal(GrailsHttpPutFormContentFilter.groovy:54)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at javax.servlet.FilterChain$doFilter.call(Unknown Source)
at grails.plugin.springsecurity.rest.RestTokenValidationFilter.processFilterChain(RestTokenValidationFilter.groovy:121)
at grails.plugin.springsecurity.rest.RestTokenValidationFilter.doFilter(RestTokenValidationFilter.groovy:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at grails.plugin.springsecurity.rest.RestAuthenticationFilter.doFilter(RestAuthenticationFilter.groovy:139)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.groovy:64)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at grails.plugin.springsecurity.web.SecurityRequestHolderFilter.doFilter(SecurityRequestHolderFilter.groovy:58)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:103)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:1076)
at org.grails.web.servlet.mvc.GrailsWebRequest.<init>(GrailsWebRequest.java:102)
... 63 common frames omitted
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.lang.reflect.Method.copy(Method.java:153)
at java.lang.reflect.ReflectAccess.copyMethod(ReflectAccess.java:140)
at sun.reflect.ReflectionFactory.copyMethod(ReflectionFactory.java:316)
at java.lang.Class.copyMethods(Class.java:3124)
at java.lang.Class.getMethods(Class.java:1615)
at java.beans.MethodRef.find(MethodRef.java:76)
at java.beans.MethodRef.get(MethodRef.java:62)
at java.beans.PropertyDescriptor.getReadMethod(PropertyDescriptor.java:207)
at groovy.lang.MetaClassImpl.applyPropertyDescriptors(MetaClassImpl.java:2527)
at groovy.lang.MetaClassImpl.setupProperties(MetaClassImpl.java:2265)
at groovy.lang.MetaClassImpl.addProperties(MetaClassImpl.java:3338)
at groovy.lang.MetaClassImpl.initialize(MetaClassImpl.java:3303)
at org.codehaus.groovy.reflection.ClassInfo.getMetaClassUnderLock(ClassInfo.java:289)
at org.codehaus.groovy.reflection.ClassInfo.getMetaClass(ClassInfo.java:331)
at org.codehaus.groovy.reflection.ClassInfo.getMetaClass(ClassInfo.java:341)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.getMetaClass(MetaClassRegistryImpl.java:281)
at org.codehaus.groovy.runtime.InvokerHelper.getMetaClass(InvokerHelper.java:901)
at org.codehaus.groovy.runtime.InvokerHelper.invokePojoMethod(InvokerHelper.java:934)
at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:926)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToBoolean(DefaultTypeTransformation.java:198)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.booleanUnbox(DefaultTypeTransformation.java:87)
at org.grails.web.context.ServletEnvironmentGrailsApplicationDiscoveryStrategy.findApplicationContext(ServletEnvironmentGrailsApplicationDiscoveryStrategy.groovy:61)
at grails.util.Holders.findApplicationContext(Holders.java:106)
at org.grails.web.servlet.DefaultGrailsApplicationAttributes.<init>(DefaultGrailsApplicationAttributes.java:74)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:1076)
at org.grails.web.servlet.mvc.GrailsWebRequest.<init>(GrailsWebRequest.java:102)
at grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition.determineUrl(AnnotationFilterInvocationDefinition.groovy:106)
at grails.plugin.springsecurity.web.access.intercept.AbstractFilterInvocationDefinition.getAttributes(AbstractFilterInvocationDefinition.groovy:75)
Exception in thread "http-nio-8805-exec-3" java.lang.OutOfMemoryError: GC overhead limit exceeded
</code></pre>
| 0 | 6,632 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.