title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Authentication Pages spec with valid information tests failing
|
<p>I am following Michael Hart'l RoR Tutorial but seem to have a problem getting the authentication_pages test "with valid information" to pass in chapter 8.</p>
<p>Specifically, the test complains that the relevant links are missing from the page, even though when I actually visit the page, they are there just fine. In fact, even when I hard these links into every page, the tests complain that the relevant links are not present.</p>
<p>The tests are below: the failing ones are the ones 'with valid information' - everything apart from the it { should have_title(user.name) }</p>
<pre><code> require 'spec_helper'
describe "AuthenticationPages" do
subject {page}
describe "signin page" do
before {visit signin_path}
it {should have_content("Sign in")}
it {should have_title("Sign in")}
describe "with invalid information" do
before {click_button('Sign in')}
it {should have_title('Sign in')}
it {should have_selector("div.alert.alert-error", text: "Invalid")}
describe "after visiting another page" do
before {click_link "Home"}
it {should_not have_selector("div.alert.alert-error", text: "Invalid")}
end
end
**describe "with valid information" do
let(:user) { FactoryGirl.create(:user) }
before do
fill_in "Email", with: user.email.upcase
fill_in "Password", with: user.password
click_button "Sign in"
end
it { should have_title(user.name) }
it { should have_link('Profile', href: user_path(user)) }
it { should have_link('Sign out', href: signout_path) }
it { should_not have_link('Sign in', href: signin_path) }
it { should have_content('This is the user page')}**
end
end
end
</code></pre>
<p>Here's the error message:</p>
<pre><code>......................................FFFF
Failures:
1) AuthenticationPages signin page with valid information should have link "Sign out", {:href=>"/signout"}
Failure/Error: it { should have_link('Sign out', href: signout_path) }
expected #has_link?("Sign out", {:href=>"/signout"}) to return true, got false
# ./spec/requests/authentication_pages_spec.rb:34:in `block (4 levels) in <top (required)>'
2) AuthenticationPages signin page with valid information should have content "This is the user page"
Failure/Error: it { should have_content('This is the user page')}
expected #has_content?("This is the user page") to return true, got false
# ./spec/requests/authentication_pages_spec.rb:36:in `block (4 levels) in <top (required)>'
3) AuthenticationPages signin page with valid information should not have link "Sign in", {:href=>"/signin"}
Failure/Error: it { should_not have_link('Sign in', href: signin_path) }
expected #has_link?("Sign in", {:href=>"/signin"}) to return false, got true
# ./spec/requests/authentication_pages_spec.rb:35:in `block (4 levels) in <top (required)>'
4) AuthenticationPages signin page with valid information should have link "Profile", {:href=>"/users/1"}
Failure/Error: it { should have_link('Profile', href: user_path(user)) }
expected #has_link?("Profile", {:href=>"/users/1"}) to return true, got false
# ./spec/requests/authentication_pages_spec.rb:33:in `block (4 levels) in <top (required)>'
Finished in 0.74198 seconds
42 examples, 4 failures
Failed examples:
rspec ./spec/requests/authentication_pages_spec.rb:34 # AuthenticationPages signin page with valid information should have link "Sign out", {:href=>"/signout"}
rspec ./spec/requests/authentication_pages_spec.rb:36 # AuthenticationPages signin page with valid information should have content "This is the user page"
rspec ./spec/requests/authentication_pages_spec.rb:35 # AuthenticationPages signin page with valid information should not have link "Sign in", {:href=>"/signin"}
rspec ./spec/requests/authentication_pages_spec.rb:33 # AuthenticationPages signin page with valid information should have link "Profile", {:href=>"/users/1"}
</code></pre>
<p>Here's a screenshot of the page after signin
<img src="https://i.stack.imgur.com/lXhgs.png" alt="enter image description here"></p>
<p>One of the catches is that I can't sign out now!! (i haven't got to the bit of the tutorial where you actually enable sign out yet).</p>
<p>Here's the markup in _header_html.erb which provides the header to the application:</p>
<pre><code><header class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<%= link_to "sample app", root_path, id: "logo" %>
<nav>
<ul class="nav pull-right">
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Help", help_path %></li>
<% if signed_in? %>
<li><%= link_to "Users", '#' %></li>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Profile", current_user %></li>
<li><%= link_to "Settings", '#' %></li>
<li class="divider"></li>
<li>
<%= link_to "Sign out", signout_path, method: "delete" %>
</li>
</ul>
</li>
<% else %>
<li><%= link_to "Sign in", signin_path %></li>
<% end %>
</ul>
</nav>
</div>
</div>
</header>
</code></pre>
| 3 | 2,425 |
NSMutableArray won't fill up
|
<p>I am trying to fill up an NSmutableAray with data from sqlite database.</p>
<p>ItemShow class:</p>
<pre><code>@interface ItemShow : NSObject
{
NSInteger itemID;
NSString *itemYear;
NSInteger rarity;
NSString *mintage;
NSInteger availability;
NSInteger quality;
NSString *mintMark;
NSString *masterMark;
NSString *dateCode;
NSString *dateDescription;
}
</code></pre>
<p>Getters/setters are ok</p>
<p>Method in DBAccess class:</p>
<pre><code>-(NSMutableArray*)getItemsOverView:(int)itemID
{
NSMutableArray *itemsArray=[[[NSMutableArray alloc]init]autorelease];
const char *sqlItems=sqlite3_mprintf("SELECT itm.itemID,itm.itemYear,itm.rarity,itm.mintage,iaval.availability as avalibility,iaval.quality as quality,itm.Mintmark,itm.masterMark,dc.dateCode,dc.dateDescription\
from items as itm\
join itemAvailability as iaval on iaval.itemID=itm.itemID\
join dateCultures as dc ON dc.dateCultureID=itm.dateCulture\
WHERE itm.itemID=%i",itemID);
sqlite3_stmt *statement;
int sqlResult = sqlite3_prepare_v2(database, sqlItems, -1, &statement, NULL);
if ( sqlResult== SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
ItemShow *itemShow=[[ItemShow alloc]init];
itemShow.itemID=sqlite3_column_int(statement, 0);
char *itemYear=(char *)sqlite3_column_text(statement, 1);
itemShow.rarity=sqlite3_column_int(statement, 2);
char *mintage=(char *)sqlite3_column_text(statement, 3);
itemShow.availability=sqlite3_column_int(statement, 4);
itemShow.quality=sqlite3_column_int(statement, 5);
char *mintMark=(char *)sqlite3_column_text(statement, 6);
char *masterMark=(char *)sqlite3_column_text(statement, 7);
char *dateCode=(char *)sqlite3_column_text(statement, 8);
char *dateDescription=(char *)sqlite3_column_text(statement, 9);
itemShow.itemYear=(itemYear)?[NSString stringWithUTF8String:itemYear]:@"";
itemShow.mintMark=(mintMark)?[NSString stringWithUTF8String:mintMark]:@"";
itemShow.masterMark=(masterMark)?[NSString stringWithUTF8String:masterMark]:@"";
itemShow.mintage=(mintage)?[NSString stringWithUTF8String:mintage]:@"Unknown";
itemShow.dateCode=(dateCode)?[NSString stringWithUTF8String:dateCode]:@"";
itemShow.dateCode=(dateDescription)?[NSString stringWithUTF8String:dateDescription]:@"";
[itemsArray addObject:itemShow];
[itemShow release];
}
sqlite3_finalize(statement);
}
else
{
[self dbConnectionError];
}
return itemsArray;
}
</code></pre>
<p>code in ViewDidLoad</p>
<pre><code>DBAccess *dbAccess=[[DBAccess alloc]init];
self.dataArr=[dbAccess getItemsOverView:itemID];
// ItemShow *itmShow=[dataArr objectAtIndex:1];
NSLog(@"%d",[dataArr count]); //returns 1. So, empty array
[dbAccess closeDataBase];
[dbAccess release];
</code></pre>
<p>Same construction works fine in other views, but now it gives error - empty array out of bounds.</p>
<p>What was checked</p>
<ol>
<li>Select works. checked it in SQLiteStudio</li>
<li>itemID is int and the view getting it correct from previous view like it gets title.</li>
</ol>
| 3 | 1,336 |
useState updating for all list elements
|
<p><a href="https://i.stack.imgur.com/FehvQ.png" rel="nofollow noreferrer">Before Clicking on picture</a></p>
<p><a href="https://i.stack.imgur.com/Q5oVp.png" rel="nofollow noreferrer">After clicking on picture</a></p>
<p>So I used useState to play with margins and make a description slide down div which initially hides behind the image itself. I am using map() to diplay a list of images with the same properties. But the useState works fine when using a single image. For multiple images clicking o 1 image activates the slidedown div for all the images. I want them to be seperate. Is there any solution to this?</p>
<pre><code>import React,{useState} from 'react'
import Image1 from '../../images/background1.jpg'
import Image2 from '../../images/background2.jpg'
import {Arts,ArtHeading,CardContainer, Card,CardImg1,CardDetails,CardText} from './ArtsElements';
const images = [
{ title:"Title1", src:Image1},
{ title:"Title2", src:Image1},
{ title:"Title3", src:Image1},
{ title:"Title4", src:Image1},
{ title:"Title5", src:Image1},
{ title:"Title6", src:Image1},
{ title:"Title7", src:Image1},
{ title:"Title8", src:Image1},
{ title:"Title9", src:Image1},
{ title:"Title10", src:Image1},
{ title:"Title11", src:Image1},
{ title:"Title12", src:Image1},
{ title:"Title13", src:Image1},
{ title:"Title14", src:Image1},
];
const Artworks = () => {
const [isOpen,setIsOpen] = useState(true);
const toggle = () => {
setIsOpen(!isOpen)
}
return (
<Arts >
<ArtHeading>
Artworks
</ArtHeading>
<CardContainer>
{
images.map((img,index) => (
<Card >
{/* <CardImg1 key={index} src={img.src} /> */}
<CardImg1 src={Image1} onClick={toggle} />
<CardDetails isOpen={isOpen} onClick={toggle} >
<CardText >
title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title
4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4
title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4
title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4
title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4
title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title
title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4
title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4title 4
</CardText>
</CardDetails>
</Card>
))}
</CardContainer>
</Arts>
)
}
export default Artworks
</code></pre>
<p>styled components file:</p>
<pre><code>import styled from 'styled-components'
export const Arts = styled.div`
background-color: #fff;
margin-bottom: 150px;
@media screen and (max-width:768px){
margin-bottom: 100px;
}
@media screen and (max-width:480px){
margin-bottom: 100px;
}
`
export const ArtHeading = styled.h1`
font-size: 50px;
margin-left: 0px;
font-weight: bold;
font-family: Verdana, Geneva, Tahoma, sans-serif;
text-align: center;
@media screen and (max-width:768px){
font-size: 50px;
margin-left: 10px;
}
@media screen and (max-width:480px){
font-size: 30px;
margin-left: 0px;
}
`
export const CardContainer = styled.section`
margin: 50px auto;
width: 90%;
display: grid;
grid-template-columns: repeat(3,1fr);
grid-gap: 20px;
`
export const Card = styled.div`
position: relative;
height: 430px;
width:350px;
border-radius: 10px;
box-shadow: 0px 5px 10px rgb(0,0,0,0.5);
`
export const CardImg1 = styled.img`
width: 100%;
height:100%;
box-sizing: border-box;
border-radius: 10px;
`
export const CardText = styled.p`
`
export const CardDetails = styled.div`
background: white;
border-radius: 10px;
margin-top:${({isOpen}) => (isOpen ? '40px' : '440px')};
transition: 1s ease-in-out;
cursor: pointer;
`
</code></pre>
| 3 | 2,316 |
How to speed up the deletion of entries from a table with a large number of entries
|
<p>I have a table that currently has over 150 million records. The table has no foreign keys.</p>
<p><a href="https://i.stack.imgur.com/s7VOR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s7VOR.png" alt="[TABLE]" /></a></p>
<p>The database was previously based on MySQL and was migrated to SQL Server.
Since then, one specific query on that table has taken much, much longer.
On MySQL, the query counterpart took less than 3 seconds to execute. On SQL Server, the query can be executed even for more than 1 minute.</p>
<p>There is no problem with any other table or query at the moment - just this one on this one table.</p>
<p>[EXAMPLE] : I CAN'T CHANGE A QUERY.</p>
<pre><code>delete from Features WITH(ROWLOCK)
where ParentType=N'DokHandlowe' and Parent=3023658
or ParentType=N'PozycjeDokHan' and Parent in (25302311, 25302312,
25302313, 25302314, 25302315, 25302316, 25302317, 25302318, 25302319,
25302320, 25302321, 25302322, 25302323, 25302324, 25302325, 25302326,
25302327, 25302328, 25302329, 25302330, 25302331, 25302332, 25302333,
25302334, 25302335, 25302336, 25302337, 25302338, 25302339, 25302340,
25302341, 25302342, 25302343, 25302344, 25302345, 25302346, 25302347,
25302348, 25302349, 25302350, 25302351, 25302352, 25302353, 25302354,
25302355, 25302356, 25302357, 25302358, 25302359, 25302360, 25302361,
25302362, 25302363, 25302364, 25302365, 25302366, 25302367, 25302368,
25302369, 25302370, 25302371, 25302372, 25302373, 25302374, 25302375,
25302376, 25302377, 25302378, 25302379, 25302380, 25302381, 25302382,
25302383, 25302384, 25302385, 25302386, 25302387, 25302388, 25302389,
25302390, 25302391, 25302392, 25302393, 25302394, 25302395, 25302396,
25302397, 25302398, 25302399, 25302400, 25302401, 25302402, 25302403,
25302404, 25302405, 25302406, 25302407, 25302408, 25302409, 25302410,
25302411, 25302412, 25302413, 25302414, 25302415, 25302416, 25302417,
25302418, 25302419, 25302420, 25302421, 25302422, 25302423, 25302424,
25302425, 25302426, 25302427, 25302428, 25302429, 25302430, 25302431,
25302432, 25302433, 25302434, 25302435, 25302436, 25302437, 25302438,
25302439, 25302440, 25302441, 25302442, 25302443, 25302444, 25302445,
25302446, 25302447, 25302448, 25302449, 25302450, 25302451, 25302452,
25302453, 25302454, 25302455, 25302456, 25302457, 25302458, 25302459,
25302460, 25302461, 25302462, 25302463, 25302464, 25302465, 25302466,
25302467, 25302468, 25302469, 25302470, 25302471, 25302472, 25302473,
25302474, 25302475, 25302476, 25302477, 25302478, 25302479, 25302480,
25302481, 25302482, 25302483, 25302484, 25302485, 25302486, 25302487,
25302488, 25302489, 25302490, 25302491, 25302492, 25302493, 25302494,
25302495, 25302496, 25302497, 25302498, 25302499, 25302500, 25302501,
25302502, 25302503, 25302504, 25302505, 25302506, 25302507, 25302508,
25302509, 25302510, 25302511, 25302512, 25302513, 25302514, 25302515,
25302516, 25302517, 25302518, 25302519, 25302520, 25302521, 25302522,
25302523, 25302524, 25302525, 25302526, 25302527, 25302528, 25302529,
25302530, 25302531, 25302532, 25302533, 25302534, 25302535, 25302536,
25302537, 25302538, 25302539, 25302540, 25302541, 25302542, 25302543,
25302544, 25302545, 25302546, 25302547, 25302548, 25302549, 25302550)
</code></pre>
<p>Tried doing indexes but either I've created them incorected or it didn't help.</p>
<p>Indexes :</p>
<p><a href="https://i.stack.imgur.com/8JCic.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8JCic.png" alt="enter image description here" /></a></p>
<p>[EDIT#1]</p>
<pre><code>/****** Object: Index [Features_Data_INDEX] Script Date: 2021-09-01 10:51:34 ******/
CREATE NONCLUSTERED INDEX [Features_Data_INDEX] ON [dbo].[Features]
(
[ParentType] ASC,
[Name] ASC,
[DataKey] ASC,
[Lp] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object: Index [NCI_Features_Parent_ParentType] Script Date: 2021-09-01 10:59:29 ******/
CREATE NONCLUSTERED INDEX [NCI_Features_Parent_ParentType] ON [dbo].[Features]
(
[ParentType] ASC,
[Parent] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object: Index [NCI_Features_ParentType_Parent] Script Date: 2021-09-01 10:59:55 ******/
CREATE NONCLUSTERED INDEX [NCI_Features_ParentType_Parent] ON [dbo].[Features]
(
[Parent] ASC,
[ParentType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object: Index [PK_Feature] Script Date: 2021-09-01 11:00:13 ******/
ALTER TABLE [dbo].[Features] ADD CONSTRAINT [PK_Feature] PRIMARY KEY CLUSTERED
(
[Parent] ASC,
[ParentType] ASC,
[Name] ASC,
[Lp] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
</code></pre>
<p>[EDIT#2]
(Estimated) Query plan : <a href="https://www.brentozar.com/pastetheplan/?id=HkyJqphbt" rel="nofollow noreferrer">https://www.brentozar.com/pastetheplan/?id=HkyJqphbt</a></p>
<p>[EDIT#3]
(Actual) Query plan : <a href="https://www.brentozar.com/pastetheplan/?id=ryVNnC2ZY" rel="nofollow noreferrer">https://www.brentozar.com/pastetheplan/?id=ryVNnC2ZY</a></p>
| 3 | 2,643 |
Toggling TableColumn.setVisible resets width, setPrefWidth doesn't change it
|
<p>I have a TableView full of nested columns. On these columns, I have 2 context menu options -- "Hide Column" and "Unhide All Columns", which toggle the visibility of the columns and their children as such.</p>
<p>The tableview is populated after the UI is initialized, so the size of the columns is set to the default width, which is smaller than the size of the longest cell value. This is what I want to happen. I don't want the columns to extend to thousands of pixels wide because of a single particularly long entry.</p>
<p>My problem is this: <strong>when the user hides the column and unhides it, the width of that column stretches out to the smallest length possible to fit the longest cell value. This is not what I want to happen.</strong> I want it to ideally keep its original width when the visibility is toggled in this way.</p>
<p>To solve this, I tried setting the max width to the current width before I hide the column, and then unsetting the max width and setting the prefwidth to the former maxwidth after I unhide it (thus locking it from resizing itself). This doesn't work.</p>
<p>Here's an example to show what's happening.</p>
<p><strong>TestExample.java</strong></p>
<pre><code>package testexample;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Testexample extends Application {
private TableView table;
@Override
public void start(Stage primaryStage) {
//Create table
table = new TableView();
//Create table items
final ObservableList<DataContainer> data = FXCollections.observableArrayList(
new DataContainer("Alice", "Red", "Yellow"),
new DataContainer("Bob", "purple", "green"),
new DataContainer("Sir Jean-Jaques-Charles III", "Deep green-cyan turqoise", "Fluorescent pink")
);
//Create table columns
TableColumn nameColumn = new TableColumn("name");
TableColumn colorsColumn = new TableColumn("colors");
TableColumn color1Column = new TableColumn("color1");
TableColumn color2Column = new TableColumn("color2");
//Make it so columns can properly display the table items
nameColumn.setCellValueFactory( new PropertyValueFactory<>("name"));
color1Column.setCellValueFactory( new PropertyValueFactory<>("color1"));
color2Column.setCellValueFactory( new PropertyValueFactory<>("color2"));
//Set the header context menus
addHeaderContextMenus(nameColumn);
addHeaderContextMenus(colorsColumn);
addHeaderContextMenus(color1Column);
addHeaderContextMenus(color2Column);
//Add the columns to the table
table.getColumns().addAll(nameColumn, colorsColumn);
colorsColumn.getColumns().addAll(color1Column, color2Column);
//Put the table inside a container
StackPane root = new StackPane();
AnchorPane anchor = new AnchorPane();
root.getChildren().add(anchor);
anchor.getChildren().add(table);
//anchor the table to the AnchorPane
AnchorPane.setTopAnchor(table, 1.0);
AnchorPane.setBottomAnchor(table, 1.0);
AnchorPane.setLeftAnchor(table, 1.0);
AnchorPane.setRightAnchor(table, 1.0);
//show the stage
primaryStage.setTitle("Hello World!");
primaryStage.setScene(new Scene(root, 300, 300));
primaryStage.show();
//Add the data to the table (after everything is shown)
table.setItems(data);
}
//Start the application
public static void main(String[] args) {
launch(args);
}
//Add context menus to the headers.
private void addHeaderContextMenus(TableColumn column) {
//create the menu and attach the items
ContextMenu menu = new ContextMenu();
MenuItem hideItem = new MenuItem("hide");
MenuItem unhideAllItem = new MenuItem("unhide all");
menu.getItems().addAll(hideItem, unhideAllItem);
//Set behavior for hide/unhide
hideItem.setOnAction((event) -> {
hideColumn(column);
});
unhideAllItem.setOnAction((event) -> {
unhideAllColumns();
});
//attach the menu to the column (header)
column.setContextMenu(menu);
}
private void hideColumn(TableColumn column) {
column.setMaxWidth(column.getWidth());
column.setPrefWidth(column.getWidth());
column.setVisible(false);
}
private void unhideAllColumns() {
table.getColumns().forEach(column -> {
unhideColumnsRecursively((TableColumn)column);
});
}
private void unhideColumnsRecursively(TableColumn column) {
column.getColumns().forEach(childColumn -> {
unhideColumnsRecursively((TableColumn)childColumn);
});
if(column.visibleProperty().get() == false) {
column.setVisible(true);
double width = column.getWidth();
column.setMaxWidth(9999999); //arbitrarily large big number
column.setPrefWidth(width);
System.out.println("width to set to: " + width);
System.out.println("current prefwidth: " + column.getPrefWidth());
System.out.println("current actual width: " + column.getWidth());
}
}
}
</code></pre>
<p><strong>DataContainer.java</strong></p>
<pre><code>package testexample;
import javafx.beans.property.SimpleStringProperty;
public class DataContainer {
private final SimpleStringProperty name = new SimpleStringProperty();
private final SimpleStringProperty color1 = new SimpleStringProperty();
private final SimpleStringProperty color2 = new SimpleStringProperty();
public DataContainer(String name, String color1, String color2) {
this.name.set(name);
this.color1.set(color1);
this.color2.set(color2);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getColor1() {
return color1.get();
}
public void setColor1(String color1) {
this.color1.set(color1);
}
public String getColor2() {
return color2.get();
}
public void setColor2(String color2) {
this.color2.set(color2);
}
}
</code></pre>
<p>Here's what the happens when I hide/unhide the name column: <a href="https://i.stack.imgur.com/3M9C4.gif" rel="nofollow noreferrer">example (animated gif)</a></p>
<p>Here's the output:</p>
<pre><code>width to set to: 80.0
current prefwidth: 80.0
current actual width: 80.0
</code></pre>
<p>...which is of course not what the seems to shown, as the width is clearly longer than 80.0 after un-hiding! This happens for all of the columns, including the "colors" parent column (in that case both color1 and color2 columns extend to the width of the longest cell value string).</p>
<p>Another twist: the code actually does work <em>if the user makes sure to resize the column they're hiding before they hide it</em>. <a href="https://i.stack.imgur.com/XKl3j.gif" rel="nofollow noreferrer">Example (animated gif)</a>.</p>
<p><strong>So, what's going on? Obviously the application is extending the columns to fit the longest data after the visibility is set to true. How can I make sure that the columns maintain their former lengths? Why does it only work after the user has resized that column (if it's setting a flag somewhere maybe I can set that flag manually?)</strong></p>
| 3 | 2,882 |
ImageView inside listview getting changed on search refresh
|
<p>I have a <code>listview</code> which contains <code>TextView</code> and <code>ImageView</code>.</p>
<p>Here it is: </p>
<p><img src="https://i.stack.imgur.com/T3BCA.png" alt="enter image description here"> </p>
<p><code>OnClick</code> of <code>ImageView</code> changes opens an <code>alertdialog</code> with buttons Yes and No.</p>
<p><img src="https://i.stack.imgur.com/szd7m.png" alt="enter image description here"></p>
<p>if press Yes</p>
<p><code>imageView</code> changes its background to blue, </p>
<p>if press no, </p>
<p><code>imageView</code> background changes to red.</p>
<p><img src="https://i.stack.imgur.com/t933S.png" alt="enter image description here"></p>
<p>Till now it is working fine. </p>
<p>I have a search <code>edittext</code> above the <code>listview</code>, which searches based on the <code>textview</code> in the <code>listview</code>. </p>
<p>Now on searching, the <code>imageview</code> is not showing the changed background, but the default background only. See this:</p>
<p><img src="https://i.stack.imgur.com/sIooM.png" alt="enter image description here"></p>
<p>What should I do to make the <code>imageview</code> show the image which was selected in the alert dialog.</p>
<p><strong>Code</strong></p>
<pre><code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.custom_lay, null);
}else{
v=convertView;
}
holder = new ViewHolder();
holder.code = (TextView) v.findViewById(R.id.DealerName);
holder.btnName = (ImageView) v.findViewById(R.id.BtnStreet);
holder.btnName.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View vi) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("select any one?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// holder.btnName.setBackgroundResource(R.drawable.green_icon);
vi.setBackgroundResource(R.drawable.blue_icon);
// notifyDataSetChanged();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
holder.btnName.setImageResource(R.drawable.blue_icon);
//vi.setBackgroundResource(R.drawable.green_icon);
// notifyDataSetChanged();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
v.setTag(holder);
ViewHolder hold = (ViewHolder) v.getTag();
String lb = DisplayedValues.get(position);
hold.code.setText(getItem(position));
// hold.btnName.setBackgroundResource(getSelectedItemPosition());
return v;
}
</code></pre>
| 3 | 1,054 |
Python Pandas fill missing column with left join
|
<p>I have following two data-frames.</p>
<p>df_1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>AA</th>
<th>BB</th>
<th>CC</th>
<th>DD</th>
</tr>
</thead>
<tbody>
<tr>
<td>"Apple"</td>
<td>XYZ1</td>
<td>XYZ2</td>
<td></td>
</tr>
<tr>
<td>"Apple"</td>
<td>PQR1</td>
<td>PQR2</td>
<td></td>
</tr>
<tr>
<td>"Apple"</td>
<td>XYZ4</td>
<td>PRR9</td>
<td></td>
</tr>
<tr>
<td>"Banana"</td>
<td>XYZ1</td>
<td></td>
<td>416</td>
</tr>
<tr>
<td>"Banana"</td>
<td>XYZ1</td>
<td></td>
<td>416</td>
</tr>
<tr>
<td>"Apple"</td>
<td>XYZ4</td>
<td>PRR9</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>df_lookup</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>AA</th>
<th>XX</th>
<th>YY</th>
<th>ZZ</th>
</tr>
</thead>
<tbody>
<tr>
<td>"Apple"</td>
<td>XYZ1</td>
<td>XYZ2</td>
<td>429</td>
</tr>
<tr>
<td>"Apple"</td>
<td>XYZ4</td>
<td>PRR9</td>
<td>97</td>
</tr>
<tr>
<td>"Apple"</td>
<td>PQR1</td>
<td>PQR2</td>
<td>108</td>
</tr>
<tr>
<td>"Banana"</td>
<td>XYZ1</td>
<td>PQR1</td>
<td>416</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Expected result:</strong></p>
<p>My objective is to fill out the empty values in df_1. In other words:</p>
<pre><code>if AA == "Apple" then
df_1.DD = SELECT df_lookup.ZZ
FROM df_lookup
LFET JOIN df_1
ON df_1.BB = df_lookup.XX, df_1.CC = df_lookup.YY
</code></pre>
<p>on the contrary ...</p>
<pre><code>if AA == "Banana" then
df_1.CC = SELECT df_lookup.YY
FROM df_lookup
LFET JOIN df_1
ON df_1.BB = df_lookup.XX, df_1.DD = df_lookup.ZZ
</code></pre>
<p>df_1 (filled/modified)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>AA</th>
<th>BB</th>
<th>CC</th>
<th>DD</th>
</tr>
</thead>
<tbody>
<tr>
<td>"Apple"</td>
<td>XYZ1</td>
<td>XYZ2</td>
<td>429</td>
</tr>
<tr>
<td>"Apple"</td>
<td>PQR1</td>
<td>PQR2</td>
<td>108</td>
</tr>
<tr>
<td>"Apple"</td>
<td>XYZ4</td>
<td>PRR9</td>
<td>97</td>
</tr>
<tr>
<td>"Banana"</td>
<td>XYZ1</td>
<td>PQR1</td>
<td>416</td>
</tr>
<tr>
<td>"Banana"</td>
<td>XYZ1</td>
<td>PQR1</td>
<td>416</td>
</tr>
<tr>
<td>"Apple"</td>
<td>XYZ4</td>
<td>PRR9</td>
<td>97</td>
</tr>
</tbody>
</table>
</div>
<p>I tried the following so far</p>
<pre><code>apple_merged = pd.merged(df_1, df_lookup, left_on = ["BB", "CC"], right_on = ["XX", "YY"])
df_1[(df_1["AA"] == "Apple")]["DD"] = apple_merged[(apple_merged.AA == "Apple")]["ZZ"].values
</code></pre>
<p>I got the following error in my actual code:</p>
<blockquote>
<p>ValueError: Length of values (501) does not match length of index
(602)</p>
</blockquote>
<p>Which seems to suggest that the shape of the data is different on the opposite side of the assignment, 501 v/s 602. But if I really did left join, should the row counts not be the same for me in this case?</p>
| 3 | 1,650 |
Running chrome extension process while popup is closed
|
<p>Basically I am trying to create an Auto Visitor Extension for Chrome to open a website's URL after some specific time. When I open the popup everything works fine but when the popup is close nothing works. I am trying to find out a method to run that Auto Visitor Extension even when the popup is close I have read multiple questions regarding this phenomena on Stack Overflow but none of them clarifies what I am looking for.</p>
<p>Here is my manifest file:</p>
<p><strong>manifest.json</strong></p>
<pre><code>{
"manifest_version": 2,
"name": "Auto Visitor",
"description": "This extension will visit multiple pages you saved in extension",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"activeTab",
"storage",
"tabs",
"http://*/",
"https://*/"
]
}
</code></pre>
<p>The background file that i want to run even when popup is close :</p>
<p><strong>background.js</strong></p>
<pre><code>// this will work only when you denie the background script in manifest
chrome.runtime.onInstalled.addListener(function(details) {
var initTime = 5;
chrome.storage.local.set({"avtime": initTime}, function() {});
});
reloadMainTab();
function reloadMainTab() {
chrome.storage.local.get('avurl', function (result) {
var urlsToLoad = result.avurl;
console.log(urlsToLoad);
if(urlsToLoad==undefined){
// do nothing
}else{
var urlsArr = urlsToLoad.split(",");
chrome.storage.local.get('avtime', function (result) {
var thisTime = result.avtime;
/*
setting it to -1 because it gets incremented by 1
when it goes into getSelected method
*/
var index=-1;
setInterval(function(){
if(index < urlsArr.length-1){
chrome.tabs.getSelected(function (tab) {
// console.log('index in get selected'+index)
chrome.tabs.update(tab.id,{url: urlsArr[index]});
});
index++;
}else{
index=-1;
}
}, thisTime+"000");
});
}
});
}
</code></pre>
<p>any help would be really appreciated</p>
| 3 | 1,100 |
My onActivityResult() is never called
|
<p>I have 2 Activities, Parent Activity starts Child Activity. When we are in Child Activity, the User closes it via the "Up"-Button in the menu and is returned to Parent Activity.</p>
<p>Essential code snippets:</p>
<p><strong>Parent (Main) Activity:</strong></p>
<pre class="lang-java prettyprint-override"><code>protected static final int TIMERCHOOSER_REQUEST = 1;
</code></pre>
<p>starting new Activity (called from a menu button):</p>
<pre class="lang-java prettyprint-override"><code>private void openTimerChooser() {
Intent intent = new Intent(this, TimerChooserActivity.class);
startActivityForResult(intent,TIMERCHOOSER_REQUEST);
}
</code></pre>
<p>and for fetching the result:</p>
<pre class="lang-java prettyprint-override"><code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
Log.d("Main", "called onActivityResult"); //this and below is never executed
if (requestCode == TIMERCHOOSER_REQUEST) {
switch(resultCode) {
case RESULT_CANCELED:
Log.d("Main", "Intent result was canceled by TIMERCHOOSER");
case RESULT_OK:
//code to handle data from TIMERCHOOSER_REQUEST
Log.d("Main", "accepted resultCode. value: "+resultCode);
String result = data.getStringExtra("result");
Toast toast = Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT);
toast.show();
default:
Log.d("Main", "invalid/unhandled resultCode? value: "+resultCode);
}
}
else
Log.d("Main", "invalid/unhandled requestCode? value: "+requestCode);
}
</code></pre>
<p><strong>Child Activity ("TimerChooserActivity"):</strong></p>
<pre class="lang-java prettyprint-override"><code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id) {
case R.id.action_settings:
return true;
case android.R.id.home:
Log.d("TimerChooser", "finishing intent");
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "Some result");
/*if(result == "User activated textview")
setResult(RESULT_OK,returnIntent);
else
setResult(RESULT_CANCELED,returnIntent);*/
setResult(RESULT_OK,returnIntent);
finish();
default:
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>You get back to the Parent(Maint) Activity via the home/up button in the menu / action bar. This works. But <code>onActivityResult()</code> is never called, no matter what kind of result I set.</p>
<p>There's no weird tag in my manifest, too. Just standard stuff:</p>
<pre><code>android:allowBackup
android:icon
android:label
android:theme
android:name
android:parentActivityName
android:value
</code></pre>
<p>What's going on?</p>
| 3 | 1,246 |
RestKit 0.20 NSArray serialization problems
|
<p>I'm trying to serialize an NSArray of objects.</p>
<p>The object serializes as:</p>
<pre><code>{"age":1,"name":"Foo"}
</code></pre>
<p>If I have an NSArray Containing these objects, it should serialize as:</p>
<pre><code>[{"age":1,"name":"Bob"},{"age":4,"name":"Sally"},{"age":2,"name":"Jill"}]
</code></pre>
<p>However, when I serialize it directly via RestKit, I get the following:</p>
<pre><code>{"age":[1,3,2],"name":["Sally","Jack","Bob"]}
</code></pre>
<p>When I inspect the RKMIMETypeSerialization, I see the following: (which would match the json output)</p>
<pre><code>Parameters: {
age = (
1,
3,
2
);
name = (
Sally,
Jack,
Bob
);
}
</code></pre>
<p>I'm sure that I'm just doing something really silly, I have been playing with it can't figure it out.</p>
<p>Here is my mapping logic</p>
<pre><code>+ (RKObjectMapping *)mapping {
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Item class]];
[mapping addAttributeMappingsFromDictionary:@{
@"name" : @"name",
@"age" : @"age"
}];
return mapping;
}
</code></pre>
<p>And here is the logic doing the array serialization:</p>
<pre><code>+ (NSString *)JSONStringFromArray:(NSArray *)array {
RKObjectMapping *mapping = [Item mapping];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping.inverseMapping objectClass:[Item class] rootKeyPath:nil];
NSError *error;
NSDictionary *parameters = [RKObjectParameterization parametersWithObject:array requestDescriptor:requestDescriptor error:&error];
// Serialize the object to JSON
NSData *JSON = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error];
NSString *jsonString = [[NSString alloc] initWithBytes:[JSON bytes]
length:[JSON length] encoding:NSUTF8StringEncoding];
return jsonString;
}
</code></pre>
<p>Here are test classes:
<strong>Item.h</strong></p>
<pre><code>#import <Foundation/Foundation.h>
@interface Item : NSObject
@property(nonatomic, strong) NSString *name;
@property(nonatomic) int age;
+ (void)testJsonSerialization;
+ (void)testJsonArraySerialization;
+ (Item *)itemWithName:(NSString *)string age:(int)age;
@end
</code></pre>
<p><strong>Item.m</strong></p>
<pre><code>#import "Item.h"
#import <RestKit.h>
@implementation Item
+ (RKObjectMapping *)mapping {
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Item class]];
[mapping addAttributeMappingsFromDictionary:@{
@"name" : @"name",
@"age" : @"age"
}];
return mapping;
}
- (NSString *)JSONString {
RKObjectMapping *mapping = [Item mapping];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping.inverseMapping objectClass:[Item class] rootKeyPath:nil];
NSError *error;
NSDictionary *parameters = [RKObjectParameterization parametersWithObject:self requestDescriptor:requestDescriptor error:&error];
// Serialize the object to JSON
NSData *JSON = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error];
NSString *jsonString = [[NSString alloc] initWithBytes:[JSON bytes]
length:[JSON length] encoding:NSUTF8StringEncoding];
return jsonString;
}
+ (NSString *)JSONStringFromArray:(NSArray *)array {
RKObjectMapping *mapping = [Item mapping];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping.inverseMapping objectClass:[Item class] rootKeyPath:nil];
NSError *error;
NSDictionary *parameters = [RKObjectParameterization parametersWithObject:array requestDescriptor:requestDescriptor error:&error];
// Serialize the object to JSON
NSData *JSON = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error];
NSString *jsonString = [[NSString alloc] initWithBytes:[JSON bytes]
length:[JSON length] encoding:NSUTF8StringEncoding];
return jsonString;
}
+ (void)testJsonSerialization {
Item *item = [Item itemWithName:@"Foo" age:1];
NSString *itemJSON = [item JSONString];
NSLog(@"ItemJSON:\n%@\n\n", itemJSON);
}
+ (void)testJsonArraySerialization {
NSArray *items = @[[Item itemWithName:@"Sally" age:1], [Item itemWithName:@"Jack" age:3], [Item itemWithName:@"Bob" age:2]];
NSString *itemJSON = [Item JSONStringFromArray:items];
NSLog(@"ItemArrayJSON:\n%@\n\n", itemJSON);
}
+ (Item *)itemWithName:(NSString *)name age:(int)age {
Item *item = [[Item alloc] init];
item.name = name;
item.age = age;
return item;
}
@end
</code></pre>
<p><strong>To execute</strong>
Have RestKit pod installed and then issue the following:</p>
<pre><code> [Item testJsonSerialization];
[Item testJsonArraySerialization];
</code></pre>
<p>Note, maybe I'm not configuring the mapping correctly for the array serialization. Though this mapper works perfectly for deserializing the targeted json text up above.</p>
| 3 | 2,027 |
Starting a Service in an AlertDialog and have an outside Activity bound to it
|
<p>First of all I've tried searching for this ans was unsuccessful. If my question is out there already answered could someone please point me to it? Thank you very much for either helping me here by looking at this, or even by skimming this and pointing me in the right direction. I really do appreciate it!</p>
<p><strong>My dilemma:</strong> I have an activity, and in that activity there is listview. The listview has multiple items inside it that most need to call an AlertDialog. The AlertDialog calls a service that says, "Hey, you need to update some data." The Service listens and does the update successfully. </p>
<p>The problem that comes into play is that my activity doesn't acknowledge the service. What I'm wondering about is that I'm don't fully understand how a Service operates, and if you can have the same service spun up / running more than once.</p>
<p>Note, my example ties somewhat to the idea on <a href="http://developer.android.com/reference/android/app/Service.html" rel="nofollow">The Android Dev Reference for Service</a>.</p>
<p>The Example:</p>
<pre><code> public class MyActivity extends Activity implements IMainActivity
{
ListView _list;
private RefreshConnector _serviceConnector;
private boolean _isBound;
public MyActivity () {}
public fillList()
{
//this won't trigger within the service
}
private void doBindService()
{
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
getApplicationContext().bindService(new Intent(this, UpdateScheduleService.class), _serviceConnector, BIND_AUTO_CREATE);
_isBound= true;
}
private void doUnbindService()
{
if (_isScheduleBound)
{
// Detach our existing connection.
getApplicationContext().unbindService(_serviceConnector);
_isBound= false;
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
doUnbindService();
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
_isBound= false;
_list = (ListView) findViewById(R.id.TheList);
_list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
{
if (view != null)
{
CheckBox selectedFlag = (CheckBox) view.findViewById(R.id.selectedItem);
selectedFlag.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
doBindService();
Bundle extras = new Bundle();
extras.putBoolean(BundleLocations.BUNDLE_ENABLED, ((CheckBox) view).isChecked());
extras.putLong(BundleLocations.BUNDLE_SCHEDULE_ID, 123); //123 is an example of an id being passed
extras.putString(BundleLocations.ACTION, BundleLocations.ACTION_SELECTED);
Intent updateSelection = new Intent("ChangeItems");
updateSelection.putExtras(extras);
view.getContext().startService(updateSelection);
}
});
TextView description = (TextView) view.findViewById(R.id.description);
description.setText(s.getDescription());
description.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
doBindService();
ChangeDescriptionDialog dia = new ChangeDescriptionDialog(view.getContext());
dia.setTitle(view.getContext().getResources().getString(R.string.DESCRIPTION_TITLE));
dia.setAction(BundleLocations.ACTION_DESCRIPTION);
dia.setDescription("something new"); //simplified for example...
dia.create();
dia.show();
}
});
}
}
};
}
</code></pre>
<p>RefreshConnector :</p>
<pre><code>public class RefreshConnector implements ServiceConnection
{
private UpdateService service;
public IMainActivity getActivity()
{
return activity;
}
public void setActivity(IMainActivity value)
{
this.activity = value;
}
public UpdateScheduleService getService()
{
return service;
}
private IMainActivity activity;
public void onServiceConnected(ComponentName componentName, IBinder iBinder)
{
service = ((UpdateService.UpdateBinder)iBinder).getService();
if(activity != null)
activity.fillList();
}
public void onServiceDisconnected(ComponentName componentName)
{
service = null;
}
}
</code></pre>
<p>The UpdateService</p>
<pre><code>public class UpdateService extends Service
{
final public IBinder binder = new UpdateBinder();
@Override
public IBinder onBind(Intent intent)
{
return binder;
}
public class UpdateBinderextends Binder
{
public UpdateService getService()
{
return UpdateService .this;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent == null)
{
stopSelf();
return START_STICKY;
}
if(action.equals(BundleLocations.ACTION_SELECTED))
{
long id = intent.getExtras().getLong(BundleLocations.BUNDLE_ID);
boolean enabled = intent.getExtras().getBoolean(BundleLocations.BUNDLE_ENABLED);
if(id < 0 )
{
return START_STICKY;
}
String item = intent.getExtras().getString(BundleLocations.BUNDLE_ITEM);
if (item == null || action.equals("")) return START_STICKY;
//do some work with saving the description, which it does
return START_STICKY;
}
return START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
}
}
</code></pre>
<p>DescriptionDialog truncated (constructor), Also, this is extended from the AlertDialog.Builder class. I also have a class that is common in all dialogs where basically I store the _context. So in the case here, the context is saved in the super. The _context is protected ...</p>
<pre><code>public ChangeDescriptionDialog(Context context)
{
super(context);
DialogInterface.OnClickListener onClickListenerPositive = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
//dispatch change
Intent ChangeItems = new Intent("ChangeItems");
Bundle extras = new Bundle();
extras.putParcelable(BundleLocations.BUNDLE_ITEM, _description);
extras.putString(BundleLocations.ACTION, _action);
ChangeItems.putExtras(extras);
//
// my question is partly here
// I start this service...
//
// How would my activity see it... right now it doesn't seem that way even though I do the binding before this call
//
_context.startService(ChangeItems);
}
};
this.setPositiveButton(context.getResources().getString(R.string.DIALOG_POS), onClickListenerPositive);
}
</code></pre>
<p>Again, notice the binding that takes place before the popup occurs. 2nd, notice me starting the service in the binding. What am I doing wrong or just not getting?</p>
<p>Thank you all again,
Kelly</p>
| 3 | 4,930 |
NullPointerException while trying hilt injections in JUnit5/Jupiter test cases
|
<p>I'm trying to inject an JUnit5/Jupiter test case with hilt injection but getting a null pointer exception. Using JUnit4 everything works.</p>
<p>To reproduce a simple test case is sufficient.</p>
<p>my project gradle file</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.5.20-M1'
ext.hilt_version = '2.35'
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath("de.mannodermaus.gradle.plugins:android-junit5:1.7.1.1")
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>my module gradle file</p>
<pre><code>plugins {
id 'com.android.application'
id("dagger.hilt.android.plugin")
id("de.mannodermaus.android-junit5")
}
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "de.negosa.myhilttestingapplication"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "de.negosa.myhilttestingapplication.HiltTestRunner"
// 2) Connect JUnit 5 to the runner
testInstrumentationRunnerArgument("runnerBuilder", "de.mannodermaus.junit5.AndroidJUnit5Builder")
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
// Kotlin
implementation "androidx.core:core-ktx:1.5.0"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// Hilt
implementation("com.google.dagger:hilt-android:$hilt_version")
kapt("com.google.dagger:hilt-android-compiler:$hilt_version")
//
// Local Testing
// (Required) Writing and executing Unit Tests on the JUnit Platform
testImplementation("org.junit.jupiter:junit-jupiter-api:5.7.1")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.7.1")
// (Optional) If you also have JUnit 4-based tests
testImplementation 'junit:junit:4.13.2'
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.7.1")
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
//
// Instrumented Testing
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
// hilt testing
androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
// ...with Kotlin.
kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
// 4) Jupiter API & Test Runner, if you don't have it already
androidTestImplementation("androidx.test:runner:1.3.0")
androidTestImplementation("org.junit.jupiter:junit-jupiter-api:5.7.1")
// 5) The instrumentation test companion libraries
androidTestImplementation("de.mannodermaus.junit5:android-test-core:1.2.2")
androidTestRuntimeOnly("de.mannodermaus.junit5:android-test-runner:1.2.2")
}
repositories {
mavenCentral()
}
</code></pre>
<p>my <code>HiltTestRunner</code></p>
<pre><code>package de.negosa.myhilttestingapplication
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import dagger.hilt.android.testing.HiltTestApplication
class HiltTestRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
}
</code></pre>
<p>and my test case file</p>
<pre><code>package de.negosa.myhilttestingapplication
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Rule
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
@HiltAndroidTest
class HiltTestingTest {
@get: Rule
var hiltRule = HiltAndroidRule(this)
@BeforeEach
fun setup() {
hiltRule.inject()
}
@Test
fun simpleTest() {
}
}
</code></pre>
<p>The error message is</p>
<pre><code>java.lang.NullPointerException
at dagger.hilt.internal.Preconditions.checkNotNull(Preconditions.java:34)
at dagger.hilt.android.internal.testing.TestApplicationComponentManager.inject(TestApplicationComponentManager.java:250)
at dagger.hilt.android.internal.testing.MarkThatRulesRanRule.inject(MarkThatRulesRanRule.java:81)
at dagger.hilt.android.testing.HiltAndroidRule.inject(HiltAndroidRule.java:49)
at de.negosa.myhilttestingapplication.HiltTestingTest.setup(HiltTestingTest.kt:18)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptLifecycleMethod(TimeoutExtension.java:126)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptBeforeEachMethod(TimeoutExtension.java:76)
at org.junit.jupiter.engine.descriptor.-$$Lambda$bFHzkK-Gyd2nGL9G6f3WT3eZ7lM.apply(Unknown Source:0)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.-$$Lambda$ExecutableInvoker$ReflectiveInterceptorCall$AfiRfaQW5MFAa8lovVwndaKa8l0.apply(Unknown Source:2)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.-$$Lambda$ExecutableInvoker$hmdF2IKSQSF2OJBv_amWUUg0sS8.apply(Unknown Source:6)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeMethodInExtensionContext(ClassBasedTestDescriptor.java:490)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$synthesizeBeforeEachMethodAdapter$19$ClassBasedTestDescriptor(ClassBasedTestDescriptor.java:475)
at org.junit.jupiter.engine.descriptor.-$$Lambda$ClassBasedTestDescriptor$tNV5uTg6yzrSAyoR9_LyHRWjPVk.invokeBeforeEachMethod(Unknown Source:4)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachMethods$2$TestMethodTestDescriptor(TestMethodTestDescriptor.java:167)
at org.junit.jupiter.engine.descriptor.-$$Lambda$TestMethodTestDescriptor$pK5fUoWT43xVHP3Wk-jdF7k0URU.invoke(Unknown Source:6)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$5(TestMethodTestDescriptor.java:195)
at org.junit.jupiter.engine.descriptor.-$$Lambda$TestMethodTestDescriptor$Y4hAX5bQnGBfYTu_BFBCUC1ErL0.execute(Unknown Source:6)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:195)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachMethods(TestMethodTestDescriptor.java:164)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:127)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5$NodeTestTask(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$oEtjVUBr1dzvAyO4rHrqPrrp8iU.execute(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7$NodeTestTask(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$sIF-wJyqQcSlbWMGWi7dBYWbuCo.invoke(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8$NodeTestTask(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$EAUqZA5CfD8zbN3AlxhbCoS66eU.execute(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$04TgCUAyYTiSsbqaEl88v4bsMqI.accept(Unknown Source:2)
at java.util.ArrayList.forEach(ArrayList.java:1262)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5$NodeTestTask(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$oEtjVUBr1dzvAyO4rHrqPrrp8iU.execute(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7$NodeTestTask(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$sIF-wJyqQcSlbWMGWi7dBYWbuCo.invoke(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8$NodeTestTask(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$EAUqZA5CfD8zbN3AlxhbCoS66eU.execute(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$04TgCUAyYTiSsbqaEl88v4bsMqI.accept(Unknown Source:2)
at java.util.ArrayList.forEach(ArrayList.java:1262)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5$NodeTestTask(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$oEtjVUBr1dzvAyO4rHrqPrrp8iU.execute(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7$NodeTestTask(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$sIF-wJyqQcSlbWMGWi7dBYWbuCo.invoke(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8$NodeTestTask(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.-$$Lambda$NodeTestTask$EAUqZA5CfD8zbN3AlxhbCoS66eU.execute(Unknown Source:2)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0$EngineExecutionOrchestrator(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.-$$Lambda$EngineExecutionOrchestrator$eWp5Nw-Kiu1gM4ryu2PhdSQR8rg.accept(Unknown Source:8)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)
at de.mannodermaus.junit5.AndroidJUnit5.run(AndroidJUnit5.java:126)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:395)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2205)
</code></pre>
<p>It seems to me that the <code>HiltAndroidRule</code> isn't initialized, but I don't know why.</p>
<p>Does somebody has any idea?</p>
| 3 | 6,223 |
i want to make change my container color when i pressed the container
|
<p>**
i am making the quiz app. consider each questions have four options(each option is a container in code). what i want is when i select the wrong option it need to show to selection container as red and also the correct answer as green. and when i press the right option it need to show selected container as green.</p>
<p>here is my container code</p>
<p>**</p>
<pre><code>
SizedBox(height: 20),
Expanded(
child: Container(
margin: EdgeInsets.only(bottom: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(25.0),
), //boxdecoration
child: Column(
children: [
SizedBox(height: 10),
Container(
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(15),
), //decoration
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Answer 1', style: TextStyle(color: Colors.grey, fontSize: 16), //textStyle
), //text
Container(
height: 26,
width: 26,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(color: Colors.grey),
), //boxdecoration
), //container
], //widget
), //row
), //container
</code></pre>
<p>**
and here is my full code
**</p>
<pre><code>
import 'package:flutter/material.dart';
import '../HomePage.dart';
class UsaTwo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
appBar: AppBar(
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios_rounded,
color: Colors.black,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
));
},
),
backgroundColor: Colors.transparent,
elevation: 0.0,
), //appbar
body: Column(
children: <Widget>[
Container(
margin: EdgeInsets.symmetric(horizontal: 10),
padding: EdgeInsets.all(8.0),
height: 200.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20),
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
color: Colors.white,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'1/10',
style: TextStyle(color: Colors.grey[800], fontWeight: FontWeight.bold, fontSize: 20), //textstyle
), //text
SizedBox(height: 10),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Text(
'Question iehfueufbueo bfe bfue bfbuhfih fbeh bfehf bfuwe bfueh fbueh fbeu bfuebi eefojbeb', maxLines: 5, style: TextStyle(color: Colors.black87, fontWeight: FontWeight.bold, fontSize: 20), //textstyle
),
),
),
],
), //text
],
), //column
), //container
SizedBox(height: 20),
Expanded(
child: Container(
margin: EdgeInsets.only(bottom: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(25.0),
), //boxdecoration
child: Column(
children: [
SizedBox(height: 10),
Container(
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(15),
), //decoration
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Answer 1', style: TextStyle(color: Colors.grey, fontSize: 16), //textStyle
), //text
Container(
height: 26,
width: 26,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(color: Colors.grey),
), //boxdecoration
), //container
], //widget
), //row
), //container
SizedBox(height: 10),
Container(
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(15),
), //decoration
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Answer 1', style: TextStyle(color: Colors.grey, fontSize: 16), //textStyle
), //text
Container(
height: 26,
width: 26,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(color: Colors.grey),
), //boxdecoration
), //container
], //widget
), //row
), //container
SizedBox(height: 10),
Container(
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(15),
), //decoration
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Answer 1', style: TextStyle(color: Colors.grey, fontSize: 16), //textStyle
), //text
Container(
height: 26,
width: 26,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(color: Colors.grey),
), //boxdecoration
), //container
], //widget
), //row
), //container
SizedBox(height: 10),
Container(
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(15),
), //decoration
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Answer 1', style: TextStyle(color: Colors.grey, fontSize: 16), //textStyle
), //text
Container(
height: 26,
width: 26,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(color: Colors.grey),
), //boxdecoration
), //container
], //widget
), //row
), //container
SizedBox(height: 20),
Expanded(
child: Container(
height: 100,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: RaisedButton.icon(
onPressed: () {},
color: Colors.blueAccent,
icon: Icon(Icons.arrow_back_ios_rounded, color: Colors.white),
label: Text(
'Back',
style: TextStyle(color: Colors.white, fontSize: 20),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20.0))),
),
),
), //raisedbutton
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: RaisedButton.icon(
onPressed: () {},
color: Colors.blueAccent,
icon: Icon(Icons.arrow_back_ios_rounded, color: Colors.white),
label: Text('Next', style: TextStyle(color: Colors.white, fontSize: 20)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20.0))),
),
),
), //raisedbutton
], //widget
), //row
),
), //container
], //children
), //column
), //container
), //expanded
], //children
), //column
); //scaffold
}
}
</code></pre>
| 3 | 7,063 |
I am getting a "TypeError: form is undefined" when I first load my page
|
<p>I am developing a form that i can transmit new hire data to our recruiting with JSON. I just started this but am also kinda new with Node.js and am testing as i go. Can you please let me know how i can stop this error from coming up.</p>
<p>Error:
TypeError: form is undefined <a href="http://localhost:63342/VAP_FORM/index.html:32:11" rel="nofollow noreferrer">http://localhost:63342/VAP_FORM/index.html:32:11</a></p>
<p>Browser: firefox</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/**
* Retrieves input data from a form and returns it as a JSON object.
* @param {HTMLFormControlsCollection} elements the form elements
* @return {Object} form data as an object literal
*/
const formToJSON = elements => [].reduce.call(elements, (data, element) => {
data[element.name] = element.value;
return data;
}, {});
/**
* A handler function to prevent default submission and run our custom script.
* @param {Event} event the submit event triggered by the user
* @return {void}
*/
const handleFormSubmit = event => {
event.preventDefault();
const data = formToJSON(form.elements);
const dataContainer = document.getElementsByClassName('results__display')[0];
dataContainer.textContent = JSON.stringify(data, null, " ");
console.log(dataContainer);
};
/* We find the form element using its class name, then attach the
* `handleFormSubmit()` function to the
* `submit` event.
*/
const form = document.getElementsByClassName('contact-form')[0];
form.addEventListener('submit', handleFormSubmit);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
.column {
float: left;
padding: 10px;
height: 300px; /* Should be removed. Only for demonstration */
}
.left{
width: 10%;
}
.right {
width: 30%;
}
.middle {
width: 60%;
min-width: 300px;
height: 100%;
}
.row:after {
content: "";
display: table;
clear: both;
}
#vapheading {
color: black;
font-family: Avenir;
}
#form{
color: white;
background-color: navy;
padding: 16px;
border-radius: 25px;
}
@media only screen and (max-width: 1026px) {
#left,#right {
display: none;
}
}
input {
border: 4px solid whitesmoke;
border-radius: 25px;
background-color: whitesmoke;
}
select {
border: 4px solid whitesmoke;
border-radius: 25px;
background-color: whitesmoke;
}
body{
background-color: lightgrey;
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="vap_css.css"/>
<script src="vap_script.js"></script>
<script>
function validateForm() {
var x = document.forms["myForm"]["ssn1"].value;
var y = document.forms["myForm"]["ssn2"].value;
if (x !== y ){
alert("Social Security number does not match");
return false;
}
}
</script>
</head>
<body>
<div class="row">
<div class="column left" id="left"></div>
<div class="column middle" id="middle">
<h2 id = "vapheading">Please fill out the Following Form</h2>
<div id = "form">
<form class="contact-form__label" name="myForm" onsubmit="return validateForm()">
<table id = "table">
<tr>
<td>First Name:* <br/><input type="text" name="firstname" id="fname" required/></td>
<td>Middle Name: <br/><input type="text" name="middlename" id="mname" /></td>
<td>Last Name:* <br/><input type="text" name="lastname" id="lname" required/></td>
</tr>
<tr>
<td>Suffix: <br/><input type="text" name="suffix" id="suffix" /></td>
</tr>
</table>
<table>
<tr>
<td>SSN:* <br/><input class="required-input" id="ssn1" maxlength="9" type="password" name="ssn1" required/></td>
<td>Verify SSN:* <br/><input class="required-input" id="ssn2" maxlength="9" type="password" name="ssn2" required/></td>
<td>Date of Birth:* <br/><input type="date" name="birthday" id="bday" required/></td>
</tr>
</table>
<table>
<tr>
<td>Place of Birth - City:* <br/><input type="text" name="city" id="city" required/></td>
<td>Place of Birth - State: <br/><input type="text" name="state" id="state" ></td>
<td>Place of Birth - Country:* <br/><select name="country" id="country" required>
<option value="">Choose Here</option>
<option value="Afghanistan">Afghanistan</option><option value="Albania">Albania</option><option value="Algeria">Algeria</option><option value="Andorra">Andorra</option>
<option value="Angola">Angola</option><option value="Antigua & Deps">Antigua & Deps</option><option value="Argentina">Argentina</option>
<option value="Armenia">Armenia</option><option value="Australia">Australia</option><option value="Austria">Austria</option>
<option value="Azerbaijan">Azerbaijan</option><option value="Bahamas">Bahamas</option><option value="Bahrain">Bahrain</option>
<option value="Bangladesh">Bangladesh</option><option value="Barbados">Barbados</option><option value="Belarus">Belarus</option>
<option value="Belgium">Belgium</option><option value="Belize">Belize</option><option value="Benin">Benin</option>
<option value="Bhutan">Bhutan</option><option value="Bolivia">Bolivia</option><option value="Bosnia Herzegovina">Bosnia Herzegovina</option>
<option value="Botswana">Botswana</option><option value="Brazil">Brazil</option><option value="Brunei">Brunei</option>
<option value="Bulgaria">Bulgaria</option><option value="Burkina">Burkina</option><option value="Burundi">Burundi</option>
<option value="Cambodia">Cambodia</option><option value="Cameroon">Cameroon</option><option value="Canada">Canada</option>
<option value="Cape Verde">Cape Verde</option><option value="Central African Rep">Central African Rep</option><option value="Chad">Chad</option>
<option value="Chile">Chile</option><option value="China">China</option><option value="Colombia">Colombia</option>
<option value="Comoros">Comoros</option><option value="Congo">Congo</option><option value="Congo {Democratic Rep}">Congo {Democratic Rep}</option>
<option value="Costa Rica">Costa Rica</option><option value="Croatia">Croatia</option><option value="Cuba">Cuba</option>
<option value="Cyprus">Cyprus</option><option value="Czech Republic">Czech Republic</option><option value="Denmark">Denmark</option>
<option value="Djibouti">Djibouti</option><option value="Dominica">Dominica</option><option value="Dominican Republic">Dominican Republic</option>
<option value="East Timor">East Timor</option><option value="Ecuador">Ecuador</option><option value="Egypt">Egypt</option>
<option value="El Salvador">El Salvador</option><option value="Equatorial Guinea">Equatorial Guinea</option><option value="Eritrea">Eritrea</option>
<option value="Estonia">Estonia</option><option value="Ethiopia">Ethiopia</option><option value="Fiji">Fiji</option>
<option value="Finland">Finland</option><option value="France">France</option><option value="Gabon">Gabon</option>
<option value="Gambia">Gambia</option><option value="Georgia">Georgia</option><option value="Germany">Germany</option>
<option value="Ghana">Ghana</option><option value="Greece">Greece</option><option value="Grenada">Grenada</option>
<option value="Guatemala">Guatemala</option><option value="Guinea">Guinea</option><option value="Guinea-Bissau">Guinea-Bissau</option>
<option value="Guyana">Guyana</option><option value="Haiti">Haiti</option><option value="Honduras">Honduras</option>
<option value="Hungary">Hungary</option><option value="Iceland">Iceland</option><option value="India">India</option>
<option value="Indonesia">Indonesia</option><option value="Iran">Iran</option><option value="Iraq">Iraq</option>
<option value="Ireland {Republic}">Ireland {Republic}</option><option value="Israel">Israel</option><option value="Italy">Italy</option>
<option value="Ivory Coast">Ivory Coast</option><option value="Jamaica">Jamaica</option><option value="Japan">Japan</option>
<option value="Jordan">Jordan</option><option value="Kazakhstan">Kazakhstan</option><option value="Kenya">Kenya</option>
<option value="Kiribati">Kiribati</option><option value="Korea North">Korea North</option><option value="Korea South">Korea South</option>
<option value="Kosovo">Kosovo</option><option value="Kuwait">Kuwait</option><option value="Kyrgyzstan">Kyrgyzstan</option>
<option value="Laos">Laos</option><option value="Latvia">Latvia</option><option value="Lebanon">Lebanon</option>
<option value="Lesotho">Lesotho</option><option value="Liberia">Liberia</option><option value="Libya">Libya</option>
<option value="Liechtenstein">Liechtenstein</option><option value="Lithuania">Lithuania</option><option value="Luxembourg">Luxembourg</option>
<option value="Macedonia">Macedonia</option><option value="Madagascar">Madagascar</option><option value="Malawi">Malawi</option>
<option value="Malaysia">Malaysia</option><option value="Maldives">Maldives</option><option value="Mali">Mali</option>
<option value="Malta">Malta</option><option value="Marshall Islands">Marshall Islands</option><option value="Mauritania">Mauritania</option>
<option value="Mauritius">Mauritius</option><option value="Mexico">Mexico</option><option value="Micronesia">Micronesia</option>
<option value="Moldova">Moldova</option><option value="Monaco">Monaco</option><option value="Mongolia">Mongolia</option>
<option value="Montenegro">Montenegro</option><option value="Morocco">Morocco</option><option value="Mozambique">Mozambique</option>
<option value="Myanmar, {Burma}">Myanmar, {Burma}</option><option value="Namibia">Namibia</option><option value="Nauru">Nauru</option>
<option value="Nepal">Nepal</option><option value="Netherlands">Netherlands</option><option value="New Zealand">New Zealand</option>
<option value="Nicaragua">Nicaragua</option><option value="Niger">Niger</option><option value="Nigeria">Nigeria</option>
<option value="Norway">Norway</option><option value="Oman">Oman</option><option value="Pakistan">Pakistan</option>
<option value="Palau">Palau</option><option value="Panama">Panama</option><option value="Papua New Guinea">Papua New Guinea</option>
<option value="Paraguay">Paraguay</option><option value="Peru">Peru</option><option value="Philippines">Philippines</option>
<option value="Poland">Poland</option><option value="Portugal">Portugal</option><option value="Qatar">Qatar</option>
<option value="Romania">Romania</option><option value="Russian Federation">Russian Federation</option><option value="Rwanda">Rwanda</option>
<option value="St Kitts & Nevis">St Kitts & Nevis</option><option value="St Lucia">St Lucia</option><option value="Saint Vincent & the Grenadines">Saint Vincent & the Grenadines</option>
<option value="Samoa">Samoa</option><option value="San Marino">San Marino</option><option value="Sao Tome & Principe">Sao Tome & Principe</option>
<option value="Saudi Arabia">Saudi Arabia</option><option value="Senegal">Senegal</option><option value="Serbia">Serbia</option>
<option value="Seychelles">Seychelles</option><option value="Sierra Leone">Sierra Leone</option><option value="Singapore">Singapore</option>
<option value="Slovakia">Slovakia</option><option value="Slovenia">Slovenia</option><option value="Solomon Islands">Solomon Islands</option>
<option value="Somalia">Somalia</option><option value="South Africa">South Africa</option><option value="South Sudan">South Sudan</option>
<option value="Spain">Spain</option><option value="Sri Lanka">Sri Lanka</option><option value="Sudan">Sudan</option>
<option value="Suriname">Suriname</option><option value="Swaziland">Swaziland</option><option value="Sweden">Sweden</option>
<option value="Switzerland">Switzerland</option><option value="Syria">Syria</option><option value="Taiwan">Taiwan</option>
<option value="Tajikistan">Tajikistan</option><option value="Tanzania">Tanzania</option><option value="Thailand">Thailand</option>
<option value="Togo">Togo</option><option value="Tonga">Tonga</option><option value="Trinidad & Tobago">Trinidad & Tobago</option>
<option value="Tunisia">Tunisia</option><option value="Turkey">Turkey</option><option value="Turkmenistan">Turkmenistan</option>
<option value="Tuvalu">Tuvalu</option><option value="Uganda">Uganda</option><option value="Ukraine">Ukraine</option>
<option value="United Arab Emirates">United Arab Emirates</option><option value="United Kingdom">United Kingdom</option><option value="United States">United States</option>
<option value="Uruguay">Uruguay</option><option value="Uzbekistan">Uzbekistan</option><option value="Vanuatu">Vanuatu</option>
<option value="Vatican City">Vatican City</option><option value="Venezuela">Venezuela</option><option value="Vietnam">Vietnam</option>
<option value="Yemen">Yemen</option><option value="Zambia">Zambia</option><option value="Zimbabwe">Zimbabwe</option>
</select></td>
</tr>
<tr>
<td>Citizenship:* <br/><select name="citizenship" id="citixen" default required>
<option value="">Choose Here</option>
<option value="USCitizen">US Citizen</option>
<option value="greencard">Green Card</option>
<option value="H1B">H1B</option>
<option value="EAD">EAD</option>
<option value="Other">Other</option>
</select></td>
</tr>
</table>
<br/><br/><button type="submit">Submit</button>
</form>
</div>
</div>
<div class="column right" id="right"></div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| 3 | 8,809 |
Heroku Scheduler: undefined local variable or method `params' for CreditsController:Class
|
<p>I am trying to automate a task with Heroku Scheduler. I tested the task in local and it works. I created a temporary route for testing, and it works everytime I hit the route:</p>
<pre><code>get 'create_expired_credit_lines' to: 'credits#create_expired_lines'
</code></pre>
<p>credits.controller.rb</p>
<pre><code>class CreditsController < ApplicationController
...
def self.create_expired_lines
...
@new_credit = Credit.new(params[:credit])
...
end
</code></pre>
<p>I then created a file </p>
<pre><code>app/lib/tasks/scheduler.rake
desc "This task is called by the Heroku scheduler add-on"
task :create_expired_credit_lines => :environment do
puts "Creating expired credit lines..."
CreditsController.create_expired_lines
puts "done."
end
</code></pre>
<p>When the tasks get executed, I get the following error:</p>
<pre><code>2014-03-20T21:42:11.190318+00:00 app[scheduler.4496]: undefined local variable or method `params' for CreditsController:Class
</code></pre>
<p>Full log:</p>
<pre><code>2014-03-20T21:42:06.228208+00:00 heroku[scheduler.4496]: Starting process with command `bundle exec rake create_expired_credit_lines`
2014-03-20T21:42:08.725450+00:00 heroku[scheduler.4496]: State changed from starting to up
2014-03-20T21:42:09.410565+00:00 app[scheduler.4496]: DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/Rakefile:7)
2014-03-20T21:42:09.410565+00:00 app[scheduler.4496]: DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/Rakefile:7)
2014-03-20T21:42:10.274625+00:00 app[scheduler.4496]: Connecting to database specified by DATABASE_URL
2014-03-20T21:42:10.563939+00:00 app[scheduler.4496]: [deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
2014-03-20T21:42:10.852664+00:00 app[scheduler.4496]: Creating expired credit lines...
2014-03-20T21:42:11.190030+00:00 app[scheduler.4496]: rake aborted!
2014-03-20T21:42:11.191365+00:00 app[scheduler.4496]: /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.11/lib/active_record/relation/delegation.rb:6:in `each'
2014-03-20T21:42:11.191365+00:00 app[scheduler.4496]: /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.11/lib/active_record/relation/delegation.rb:6:in `each'
2014-03-20T21:42:11.191365+00:00 app[scheduler.4496]: /app/app/controllers/credits_controller.rb:147:in `create_expired_lines'
2014-03-20T21:42:11.191569+00:00 app[scheduler.4496]: (See full trace by running task with --trace)
2014-03-20T21:42:11.191365+00:00 app[scheduler.4496]: /app/app/controllers/credits_controller.rb:158:in `block in create_expired_lines'
2014-03-20T21:42:11.190318+00:00 app[scheduler.4496]: undefined local variable or method `params' for CreditsController:Class
2014-03-20T21:42:11.191478+00:00 app[scheduler.4496]: Tasks: TOP => create_expired_credit_lines
2014-03-20T21:42:11.191365+00:00 app[scheduler.4496]: /app/lib/tasks/scheduler.rake:4:in `block in <top (required)>'
2014-03-20T21:42:12.567208+00:00 heroku[scheduler.4496]: Process exited with status 1
2014-03-20T21:42:12.576344+00:00 heroku[scheduler.4496]: State changed from up to complete
</code></pre>
<p>===========</p>
<p>UPDATE:
I removed the arguments from the method Credit.new(params[:credit]) and it now looks like this:</p>
<p>credits.controller.rb</p>
<pre><code>class CreditsController < ApplicationController
...
def new
...
@credit = Credit.new
@credit.user_id = params[:id]
...
end
def self.create_expired_lines
...
@new_credit = Credit.new(params[:credit])
...
end
</code></pre>
<p>When I run the command </p>
<pre><code>$ heroku run rake create_expired_credit_lines
</code></pre>
<p>I get the following errors:</p>
<pre><code>Running `rake create_expired_credit_lines` attached to terminal... up, run.3757
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/Rakefile:7)
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/Rakefile:7)
Connecting to database specified by DATABASE_URL
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
Creating expired credit lines...
rake aborted!
undefined local variable or method `params' for CreditsController:Class
/app/app/controllers/credits_controller.rb:177:in `block in create_expired_lines'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord- 3.2.11/lib/active_record/relation/delegation.rb:6:in `each'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.11/lib/active_record/relation/delegation.rb:6:in `each'
/app/app/controllers/credits_controller.rb:154:in `create_expired_lines'
/app/lib/tasks/scheduler.rake:4:in `block in <top (required)>'
Tasks: TOP => create_expired_credit_lines
(See full trace by running task with --trace)
</code></pre>
| 3 | 2,316 |
Excel mql4 mismatch
|
<p>This is an indicator I am working on. The problem I am having is it doesn't match the same output as my excel file, and I am pretty sure my excel file is correct. If you would like to help me solve this issue just email me at thetfordjw@gmail.com Subject: Excel mql4 please and I will send you the excel file. Otherwise if you have something to add on this web page as to something I am doing wrong would be happy to hear from you. Thanks !</p>
<pre><code>
//+------------------------------------------------------------------+
//| JT-Statistics Close GT LT Terminated.mq4 |
//| Copyright 2021,Jon W. Thetford |
//| Email: thetfordjw@gmail.com |
//+------------------------------------------------------------------+
#property version "1.00"
#property strict
#property indicator_chart_window
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int i;
float a,b,c,d,e,f,g,h,j,k;
float aa,bb,cc,dd,ee,ff,gg,hh,jj,kk,ll,mm,nn,oo;
//input float BarsBack = "1000";
input bool FrequencyNumber = True;
input bool FrequencyPercentage = False;
input bool CumulativePercentageOfAllBars = False;
//input bool PercentageOfCustomBarsBack = False;
int OnInit()
{
//--- indicator buffers mapping
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
for(i=0;i<Bars; i++)
{
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]<Close[i+4])
{
a=a+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]<Close[i+5])
{
b=b+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]<Close[i+6])
{
c=c+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]<Close[i+7])
{
d=d+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]<Close[i+8])
{
e=e+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]<Close[i+9])
{
f=f+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]<Close[i+10])
{
g=g+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]<Close[i+11])
{
h=h+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]>Close[i+11]&&Close[i+11]<Close[i+12])
{
j=j+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]>Close[i+11]&&Close[i+11]>Close[i+12]&&Close[i+12]<Close[i+13])
{
k=k+1;
}
//LESS THAN Close[1]<Close[2]
//1
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]>Close[i+4])
{
aa=aa+1;
}
//2
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]>Close[i+5])
{
bb=bb+1;
}
//3
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]>Close[i+6])
{
cc=cc+1;
}
//4
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]>Close[i+7])
{
dd=dd+1;
}
//5
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]>Close[i+8])
{
ee=ee+1;
}
//6
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]>Close[i+9])
{
ff=ff+1;
}
//7
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]>Close[i+10])
{
gg=gg+1;
}
//8
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]>Close[i+11])
{
hh=hh+1;
}
//9
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]>Close[i+12])
{
jj=jj+1;
}
//10
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]>Close[i+13])
{
kk=kk+1;
}
//11
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]>Close[i+14])
{
ll=ll+1;
}
//12
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]<Close[i+14]&&Close[i+14]>Close[i+15])
{
mm=mm+1;
}
//13
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]<Close[i+14]&&Close[i+14]<Close[i+15]&&Close[i+15]>Close[i+16])
{
nn=nn+1;
}
//=
if(Close[i+1]==Close[i+2])
{
oo=oo+1;
}
//OUTPUT > <
//Frequency NUMBER of consecutive closes greater than and less than the previous.
if(FrequencyNumber) Comment("FrequencyNumber\n# Close[1]>Close[2]\n\n1: "+a+"\n2: "+b+"\n3: "+c+"\n4: "+d+"\n5: "+e+"\n6: "+f+"\n7: "+g+"\n8: "+h+"\n9: "+j+"\n10: "+k
+"\n\n# Close[1]<Close[2]\n\n1: "+aa+"\n2: "+bb+"\n3: "+cc+"\n4: "+dd+"\n5: "+ee+"\n6: "+ff+"\n7: "+gg+"\n8: "+hh+"\n9: "+jj+"\n10: "+kk+"\n11: "+ll+"\n12: "+mm+"\n13: "+nn+"\n==: "+oo+"\n\n Total bars: "+Bars);
}
</code></pre>
| 3 | 6,001 |
SAPUI5 Reusable Table Fragment Data Binding
|
<p>I am starting to develop SAPUI5, trying to apply concepts and best practices from other web dev toolkits I know so far, please be kind as my knowledge is still fairly limited.</p>
<p>I want to re-structure a project and replace copy-paste code with reusable parts. Custom controls are not the right way as far as I checked, basically it is purely standard functionality of a SAPUI5 control with different data binding.
The data binding and propagation should be done via XML as it fits the project architecture best, my initial idea was to use fragments.</p>
<p>Sample:
An identical table should be used multiple times in the same view and in different views, single model with different object arrays.</p>
<p>Fragment:</p>
<pre><code> <Table items="{???}">
<columns>
<Column >
<Text text="Name"/>
</Column>
<Column>
<Text text="Amount"/>
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<ObjectIdentifier title="{dataModel>name}"/>
<Text text="{dataModel>amount}"/>
</cells>
</ColumnListItem>
</items>
</Table>
</core:FragmentDefinition>
</code></pre>
<p>Model:</p>
<pre><code>let oTemp = new JSONModel({
data: {
a: [{
name: "Product 1 Entry 1",
amount: "Product 1 Amount 1"
}, {
name: "Product 1 Entry 2",
amount: "Product 1 Amount 2"
}],
b: [{
name: "Product 2 Entry 1",
amount: "Product 2 Amount 1"
}, {
name: "Product 2 Entry 2",
amount: "Product 2 Amount 2"
}]
}
});
this.getView().setModel(oTemp, "dataModel");
</code></pre>
<p>XML View Usage:</p>
<pre><code><core:Fragment objectBindings="dataModel>/data/a" type="XML" fragmentName="...view.ReusableTable"></core:Fragment>
<core:Fragment objectBindings="dataModel>/data/b" type="XML" fragmentName="...view.ReusableTable"></core:Fragment>
</code></pre>
<p>I tried various ways to bind the item aggregation in the table or the fragment itself, without success.
As hopefully shown in this sample, I want to pass a specific model property to the fragment and its table to display a different set of items (a or b) without the use of javascript in the view controller.</p>
<p>Desired Output:</p>
<p>2 Tables, identical header (Name, Amount column) with 2 rows each using data from datamodel, property a [] and b []</p>
<p>From what I saw in the SAPUI5 library offering regarding code reuse, fragments should be the best way to achieve this result as no additional controller logic is required to display | interact. I would appreciate any suggestions how to approach this, or maybe change the approach in general if necessary? Thank you lots!</p>
| 3 | 1,330 |
Apache Solr atomic update results in NullPointerException
|
<p>Im trying to partially update a document via an atomic update, when I do so, the web sever responds with a 500 status with the stacktrace of</p>
<pre><code>{
"responseHeader":{
"status":500,
"QTime":1},
"error":{
"trace":"java.lang.NullPointerException\r\n\tat org.apache.solr.update.processor.AtomicUpdateDocumentMerger.getFieldFromHierarchy(AtomicUpdateDocumentMerger.java:301)\r\n\tat org.apache.solr.update.processor.AtomicUpdateDocumentMerger.mergeChildDoc(AtomicUpdateDocumentMerger.java:398)\r\n\tat org.apache.solr.update.processor.DistributedUpdateProcessor.getUpdatedDocument(DistributedUpdateProcessor.java:697)\r\n\tat org.apache.solr.update.processor.DistributedUpdateProcessor.doVersionAdd(DistributedUpdateProcessor.java:372)\r\n\tat org.apache.solr.update.processor.DistributedUpdateProcessor.lambda$versionAdd$0(DistributedUpdateProcessor.java:337)\r\n\tat org.apache.solr.update.VersionBucket.runWithLock(VersionBucket.java:50)\r\n\tat org.apache.solr.update.processor.DistributedUpdateProcessor.versionAdd(DistributedUpdateProcessor.java:337)\r\n\tat org.apache.solr.update.processor.DistributedUpdateProcessor.processAdd(DistributedUpdateProcessor.java:223)\r\n\tat org.apache.solr.update.processor.LogUpdateProcessorFactory$LogUpdateProcessor.processAdd(LogUpdateProcessorFactory.java:103)\r\n\tat org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:55)\r\n\tat org.apache.solr.update.processor.AddSchemaFieldsUpdateProcessorFactory$AddSchemaFieldsUpdateProcessor.processAdd(AddSchemaFieldsUpdateProcessorFactory.java:475)\r\n\tat org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:55)\r\n\tat org.apache.solr.update.processor.FieldMutatingUpdateProcessor.processAdd(FieldMutatingUpdateProcessor.java:118)\r\n\tat org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:55)\r\n\tat org.apache.solr.update.processor.FieldMutatingUpdateProcessor.processAdd(FieldMutatingUpdateProcessor.java:118)\r\n\tat org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:55)\r\n\tat org.apache.solr.update.processor.FieldMutatingUpdateProcessor.processAdd(FieldMutatingUpdateProcessor.java:118)\r\n\tat org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:55)\r\n\tat org.apache.solr.update.processor.FieldMutatingUpdateProcessor.processAdd(FieldMutatingUpdateProcessor.java:118)\r\n\tat org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:55)\r\n\tat org.apache.solr.update.processor.FieldNameMutatingUpdateProcessorFactory$1.processAdd(FieldNameMutatingUpdateProcessorFactory.java:75)\r\n\tat org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:55)\r\n\tat org.apache.solr.update.processor.FieldMutatingUpdateProcessor.processAdd(FieldMutatingUpdateProcessor.java:118)\r\n\tat org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:55)\r\n\tat org.apache.solr.update.processor.AbstractDefaultValueUpdateProcessorFactory$DefaultValueUpdateProcessor.processAdd(AbstractDefaultValueUpdateProcessorFactory.java:92)\r\n\tat org.apache.solr.handler.loader.JsonLoader$SingleThreadedJsonLoader.handleAdds(JsonLoader.java:507)\r\n\tat org.apache.solr.handler.loader.JsonLoader$SingleThreadedJsonLoader.processUpdate(JsonLoader.java:145)\r\n\tat org.apache.solr.handler.loader.JsonLoader$SingleThreadedJsonLoader.load(JsonLoader.java:121)\r\n\tat org.apache.solr.handler.loader.JsonLoader.load(JsonLoader.java:84)\r\n\tat org.apache.solr.handler.UpdateRequestHandler$1.load(UpdateRequestHandler.java:97)\r\n\tat org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:68)\r\n\tat org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:199)\r\n\tat org.apache.solr.core.SolrCore.execute(SolrCore.java:2566)\r\n\tat org.apache.solr.servlet.HttpSolrCall.execute(HttpSolrCall.java:756)\r\n\tat org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:542)\r\n\tat org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:397)\r\n\tat org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:343)\r\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1602)\r\n\tat org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:540)\r\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)\r\n\tat org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)\r\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\r\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)\r\n\tat org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1588)\r\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)\r\n\tat org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1345)\r\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)\r\n\tat org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480)\r\n\tat org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1557)\r\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)\r\n\tat org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1247)\r\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)\r\n\tat org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:220)\r\n\tat org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:126)\r\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\r\n\tat org.eclipse.jetty.rewrite.handler.RewriteHandler.handle(RewriteHandler.java:335)\r\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\r\n\tat org.eclipse.jetty.server.Server.handle(Server.java:502)\r\n\tat org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:364)\r\n\tat org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:260)\r\n\tat org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)\r\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)\r\n\tat org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:118)\r\n\tat org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:333)\r\n\tat org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:310)\r\n\tat org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:168)\r\n\tat org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:126)\r\n\tat org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:366)\r\n\tat org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765)\r\n\tat org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683)\r\n\tat java.base/java.lang.Thread.run(Thread.java:834)\r\n",
"code":500}}
</code></pre>
<p>Steps to reproduce:</p>
<ol>
<li><p>Start a new clean instance of apache solr</p>
</li>
<li><p>Create a new core</p>
</li>
<li><p>Add a new document with the following data (in development mode Solr should create fields automatically) using Solr Admin's document upload tool.</p>
<p><code>{ "id": "1", "network_s": "original value" }</code>
<a href="https://i.stack.imgur.com/XUBrk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XUBrk.png" alt="example of adding a new document" /></a></p>
</li>
<li><p>Then proceed to upload a new JSON command to update the previously uploaded document.</p>
</li>
</ol>
<p><code>[{"id": "1", "network_s": {"set":"Something else"}}]</code></p>
<p><a href="https://i.stack.imgur.com/Xn1RW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xn1RW.png" alt="example of updating a document" /></a></p>
<p>I have a feeling I'm doing something wrong but I'm following the documentation exactly. Im using Solr version <code>8.1.1</code> and reading the <em>latest</em> documentation of 7.7.</p>
| 3 | 3,066 |
symfony contact form is submitted but emails dont arrive
|
<p>I need some help regarding sending emails in symfony 4.</p>
<p>I made a contact form in symfony 4.
where i use formbuilder and swiftmailer. The contact form works, it validates and i can submit. but emails don't arrive plus i don't get a confirmation message on the contactpage itself after sending.
i use mailer with host of the website itself. The website is in production mode.</p>
<p>See below the code i used. Maybe i missed some settings? thanks in advance!</p>
<p>ContactType.php</p>
<pre><code><?php
// your-path-to-types/ContactType.php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name',TextType::class);
$builder->add('email',EmailType::class);
$builder->add('subject',TextType::class);
$builder->add('body',TextareaType::class);
}
public function getBlockPrefix()
{
return 'contact';
}
}
</code></pre>
<p>Contact.php my entity </p>
<pre><code><?php
// src/Entity/Contact.php
namespace App\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Doctrine\Common\Collections\ArrayCollection;
class Contact
{
protected $name;
protected $email;
protected $subject;
protected $body;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getSubject()
{
return $this->subject;
}
public function setSubject($subject)
{
$this->subject = $subject;
}
public function getBody()
{
return $this->body;
}
public function setBody($body)
{
$this->body = $body;
}
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('name', new NotBlank());
$metadata->addPropertyConstraint('email', new Email());
$metadata->addPropertyConstraint('subject', new NotBlank());
$metadata->addPropertyConstraint('subject', new Length(array('max'=> 50)));
$metadata->addPropertyConstraint('body', new Length(array('min'=> 5)));
}
}
</code></pre>
<p>and my controller</p>
<pre><code><?php
namespace App\Controller;
use App\Entity\Contact;
use App\Form\ContactType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
final class PagesController extends DefaultController
{
/**
* @Route("/contact", name="contact")
* @Method("GET|POST")
*/
public function contact(Request $request, \Swift_Mailer $mailer)
{
$enquiry = new Contact();
$form = $this->createForm(ContactType::class, $enquiry);
$this->request = $request;
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$message = (new \Swift_Message('Hello Email'))
->setFrom('contact@example.com')
->setTo('xxxxxxx@gmail.com')
->setBody($this->renderView('contact/contactEmail.txt.twig', array('enquiry' => $enquiry)));
$mailer->send($message);
$this->get('session')->getFlashbag('blog-notice', 'Your contact enquiry was successfully sent. Thank you!');
// Redirect - This is important to prevent users re-posting
// the form if they refresh the page
return $this->redirect($this->generateUrl('contact'));
}
}
return $this->render('pages/contact.html.twig', array(
'form' => $form->createView(),
));
}
}
</code></pre>
<p>and in my <em>main.env</em> file i have this</p>
<pre><code>MAILER_URL=smtp://localhost:25?encryption=ssl&auth_mode=login&username=xxx&password=xxxx
</code></pre>
<p>So email does not get delivered. After submit I am transferred back to contact page, and no flash message either :/
Have I missed anything else for this to work?</p>
<p><strong><em>example:</em></strong> </p>
<ul>
<li>does my username have to be a whole email address that I also need to decode, etc?</li>
<li>do I need to change something on the server also? please advise.</li>
</ul>
| 3 | 2,112 |
Update 1.7 class to 1.12.2 spigot
|
<p>i am trying to update a 1.7 class to 1.12.2. i fixed some errors but i dont know how to fix the other errors. if anyone have a suggestion, i would be very very happy...</p>
<p>The Class:</p>
<pre><code>package de.beastsoup.utils.spigot.bo2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import de.beastsoup.utils.spigot.BeastUtils;
import net.minecraft.server.v1_12_R1.TileEntity;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_12_R1.CraftWorld;
import org.bukkit.scheduler.BukkitRunnable;
public class BO2 {
private Arena arena;
public BO2() {
this.arena = new Arena(this);
}
public Arena getArena() {
return arena;
}
private static HashSet<Location> blocksForUpdate = new HashSet<>();
public void addBlockUpdate(Location location) {
blocksForUpdate.add(location);
}
public void startUpdate() {
new BukkitRunnable() {
@Override
public void run() {
if (!blocksForUpdate.isEmpty()) {
net.minecraft.server.v1_12_R1.World world = ((CraftWorld) Bukkit.getWorlds().get(0)).getHandle();
for (Location location : blocksForUpdate) {
world.notify(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
blocksForUpdate.clear();
}
}
}.runTaskTimer(BeastUtils.getPlugin(BeastUtils.class), 1, 1);
}
/* Spawn BO2 */
public List<Block> spawn(Location location, File file) {
long time = System.currentTimeMillis();
BufferedReader reader;
ArrayList<Block> blocks = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.contains(",") || !line.contains(":")) {
continue;
}
String[] parts = line.split(":");
String[] coordinates = parts[0].split(",");
String[] blockData = parts[1].split("\\.");
setBlockFast(location.getWorld(), location.getBlockX() + Integer.valueOf(coordinates[0]), location.getBlockY() + Integer.valueOf(coordinates[2]), location.getBlockZ() + Integer.valueOf(coordinates[1]), Integer.valueOf(blockData[0]), blockData.length > 1 ? Byte.valueOf(blockData[1]) : 0);
blocks.add(location.getWorld().getBlockAt(location.getBlockX() + Integer.valueOf(coordinates[0]), location.getBlockY() + Integer.valueOf(coordinates[2]), location.getBlockZ() + Integer.valueOf(coordinates[1])));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("BO2 spawnada em " + (time - System.currentTimeMillis()) + "ms");
return blocks;
}
/* Load BO2 file */
public List<FutureBlock> load(Location location, File file) {
BufferedReader reader;
ArrayList<FutureBlock> blocks = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.contains(",") || !line.contains(":")) {
continue;
}
String[] parts = line.split(":");
String[] coordinates = parts[0].split(",");
String[] blockData = parts[1].split("\\.");
blocks.add(new FutureBlock(location.clone().add(Integer.valueOf(coordinates[0]), Integer.valueOf(coordinates[2]), Integer.valueOf(coordinates[1])), Integer.valueOf(blockData[0]), blockData.length > 1 ? Byte.valueOf(blockData[1]) : 0));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return blocks;
}
/* Set methods */
public boolean setBlockFast(World world, int x, int y, int z, int blockId, byte data) {
if (y >= 255 || y < 0) {
return false;
}
net.minecraft.server.v1_12_R1.World w = ((CraftWorld) world).getHandle();
net.minecraft.server.v1_12_R1.Chunk chunk = w.getChunkAt(x >> 4, z >> 4);
boolean b = data(chunk, x & 0x0f, y, z & 0x0f, net.minecraft.server.v1_12_R1.Block.getById(blockId), data);
addBlockUpdate(new Location(Bukkit.getWorlds().get(0), x, y, z));
return b;
}
@SuppressWarnings("deprecation")
public boolean setBlockFast(Location location, Material material, byte data) {
return setBlockFast(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), material.getId(), data);
}
private boolean data(net.minecraft.server.v1_12_R1.Chunk that, int i, int j, int k, net.minecraft.server.v1_12_R1.Block block, int l) {
int i1 = k << 4 | i;
if (j >= that.b[i1] - 1) {
that.b[i1] = -999;
}
int j1 = that.heightMap[i1];
net.minecraft.server.v1_12_R1.Block block1 = that.getType(i, j, k);
int k1 = that.getData(i, j, k);
if (block1 == block && k1 == l) {
return false;
} else {
boolean flag = false;
net.minecraft.server.v1_12_R1.ChunkSection chunksection = that.getSections()[j >> 4];
if (chunksection == null) {
if (block == net.minecraft.server.v1_12_R1.Blocks.AIR) {
return false;
}
chunksection = that.getSections()[j >> 4] = new net.minecraft.server.v1_12_R1.ChunkSection(j >> 4 << 4, !that.world.worldProvider.g);
flag = j >= j1;
}
int l1 = that.locX * 16 + i;
int i2 = that.locZ * 16 + k;
if (!that.world.isStatic) {
block1.f(that.world, l1, j, i2, k1);
}
if (!(block1 instanceof IContainer)) {
chunksection.setTypeId(i, j & 15, k, block);
}
if (!that.world.isStatic) {
block1.remove(that.world, l1, j, i2, block1, k1);
} else if (block1 instanceof IContainer && block1 != block) {
that.world.p(l1, j, i2);
}
if (block1 instanceof IContainer) {
chunksection.setTypeId(i, j & 15, k, block);
}
if (chunksection.getTypeId(i, j & 15, k) != block) {
return false;
} else {
chunksection.setData(i, j & 15, k, l);
if (flag) {
that.initLighting();
}
TileEntity tileentity;
if (block1 instanceof IContainer) {
tileentity = that.e(i, j, k);
if (tileentity != null) {
tileentity.u();
}
}
if (!that.world.isStatic && (!that.world.captureBlockStates || (block instanceof net.minecraft.server.v1_7_R4.BlockContainer))) {
block.onPlace(that.world, l1, j, i2);
}
if (block instanceof IContainer) {
if (that.getType(i, j, k) != block) {
return false;
}
tileentity = that.e(i, j, k);
if (tileentity == null) {
tileentity = ((IContainer) block).a(that.world, l);
that.world.setTileEntity(l1, j, i2, tileentity);
}
if (tileentity != null) {
tileentity.u();
}
}
that.n = true;
return true;
}
}
}
/* FutureBlock Utils */
public class FutureBlock {
private Location location;
private int id;
private byte data;
public FutureBlock(Location location, int id, byte data) {
this.location = location;
this.id = id;
this.data = data;
}
public byte getData() {
return data;
}
public Location getLocation() {
return location;
}
public int getId() {
return id;
}
@SuppressWarnings("deprecation")
public void place() {
location.getBlock().setTypeIdAndData(id, data, true);
}
}
}
</code></pre>
<p>This Error i need fix now: <a href="https://gyazo.com/cb3176c9d879532adddfc5ce1edad2eb" rel="nofollow noreferrer">https://gyazo.com/cb3176c9d879532adddfc5ce1edad2eb</a> , <a href="https://gyazo.com/014047f5103fd1eaace121bc121fa8dc" rel="nofollow noreferrer">https://gyazo.com/014047f5103fd1eaace121bc121fa8dc</a> , <a href="https://gyazo.com/6b546cd147037a9deffad42e3b1ce1ef" rel="nofollow noreferrer">https://gyazo.com/6b546cd147037a9deffad42e3b1ce1ef</a></p>
<p>if anyone know nms spigot 1.12.2 or something i would be happy</p>
| 3 | 4,005 |
jQuery fullcalendar doesn't update database after resizing
|
<p>Ola,</p>
<p>I got some events stored in a database and i'm showing these in my jquery fullcalendar. Now i also got it working so that i can change the day of an event by draging and dropping. Changing the time by resizing a event i can't get working tho.</p>
<p>I guess it has something to do with me not giving a time here:</p>
<pre><code>start = moment(start, 'DD.MM.YYYY').format('YYYY-MM-DD')
end = moment(end, 'DD.MM.YYYY').format('YYYY-MM-DD')
</code></pre>
<p>But all the formats i tried (for instance: YYYY-MM-DDThh:mm:ss) give this error:</p>
<pre><code>Uncaught ReferenceError: start is not defined
</code></pre>
<p>Now with my current code i <strong>can</strong> resize elements, it only doesn't save them in my database. This is the code:</p>
<pre><code>$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
editable: true,
events: "http://localhost/plann/events.php",
defaultView: 'agendaWeek',
selectable: true,
editable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
start = moment(start, 'DD.MM.YYYY').format('YYYY-MM-DD')
end = moment(end, 'DD.MM.YYYY').format('YYYY-MM-DD')
$.ajax({
url: 'http://localhost/plann/add_events.php',
data: 'title='+ title+'&start='+ start +'&end='+ end ,
type: "POST",
success: function(json) {
alert('OK');
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
eventDrop: function(event, delta) {
start = moment(event.start, 'DD.MM.YYYY').format('YYYY-MM-DD')
end = moment(event.end, 'DD.MM.YYYY').format('YYYY-MM-DD')
$.ajax({
url: 'http://localhost/plann/update_events.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
success: function(json) {
alert("OK");
}
});
},
eventResize: function(event) {
start = moment(event.start, 'DD.MM.YYYY').format('YYYY-MM-DD')
end = moment(event.end, 'DD.MM.YYYY').format('YYYY-MM-DD')
$.ajax({
url: 'http://localhost/plann/update_events.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
success: function(json) {
alert("OK");
}
});
}
});
});
</code></pre>
| 3 | 1,613 |
Fix RegEx to properly capture text inside parenthesis
|
<h2>SCENARIO</h2>
<hr>
<p>Time ago I asked a question to format music filenames in certain conditions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/32807698/regex-pattern-to-limit-dashes-in-these-circumstances">RegEx pattern to limit dashes in these circumstances</a></li>
</ul>
<p>However, I noticed too late that the accepted answer is wrong, because it can capture any word starting with "F". But this is not a problem/question, I solved it just by restoring the <code>ft|feat|featuring</code> OR group.</p>
<p>So finally from que question linked above, I ended up using this expression:</p>
<pre><code>pattern := '^(.+)\s+-\s+(.+?)\s+(ft|feat|featuring)[\.\s]*([^([\])]+)(.+)?$'
replace := '$1 Feat. $4 - $2$5'
</code></pre>
<p>Well, now, having these filenames to test:</p>
<ol>
<li>Black Coast - Trndsttr</li>
<li>Black Coast - Trndsttr (Feather)</li>
<li>Black Coast - Trndsttr (Lucian Remix)</li>
<li>Black Coast - Trndsttr (Feather) (Lucian Remix)</li>
<li>Black Coast - Trndsttr Feat. M. Maggie</li>
<li>Black Coast - Trndsttr (Feat. M. Maggie)</li>
<li>Black Coast - Trndsttr Feat. M. Maggie (Lucian Remix)</li>
<li>Black Coast - Trndsttr (Feat. M. Maggie) (Lucian Remix)</li>
<li>Black Coast - Trndsttr (Lucian Remix) Feat. M. Maggie</li>
<li>Black Coast - Trndsttr (Lucian Remix) (Feat. M. Maggie)</li>
<li>Black Coast - Trndsttr (Feather) (Lucian Remix) Feat. M. Maggie</li>
<li>Black Coast - Trndsttr (Feather) (Lucian Remix) (Feat. M. Maggie)</li>
<li>Black Coast - Trndsttr (Feather) Feat. M. Maggie (Lucian Remix)</li>
<li>Black Coast - Trndsttr (Feather) (Feat. M. Maggie) (Lucian Remix) </li>
<li>Black Coast - Trndsttr (Feather) (Feat. M. Maggie) Lucian Remix</li>
<li>Black Coast - Trndsttr (Feather) Feat. M. Maggie Lucian Remix</li>
</ol>
<p>The expected results are these:</p>
<p>(from 1 to 4 no changes, and 16 is an assumable false positive, it is in essence the same as 5, 9 and 11.)</p>
<ol>
<li>Black Coast - Trndsttr</li>
<li>Black Coast - Trndsttr (Feather)</li>
<li>Black Coast - Trndsttr (Lucian Remix)</li>
<li>Black Coast - Trndsttr (Feather) (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr</li>
<li>Black Coast Feat. M. Maggie - Trndsttr</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Feather) (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Feather) (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Feather) (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Feather) (Lucian Remix)</li>
<li>Black Coast Feat. M. Maggie - Trndsttr (Feather) Lucian Remix</li>
<li>Black Coast Feat. M. Maggie Lucian Remix - Trndsttr (Feather) </li>
</ol>
<h2>PROBLEM</h2>
<hr>
<p>The expression that I mentioned works perfect for all the filenames except for the cases where the <strong>Feat...</strong> part is grouped inside parenthesis (or brackets, whatever).</p>
<p>Then I tried to adapt the RegEx for the aggrupations condition:</p>
<pre><code>pattern := '^(.+)\s+-\s+(.+?)\s+([\[\(\{])?\s*(ft|feat|featuring([\.])?\s+)((.+)[^\]\)\}])?\s*(.+)?$'
</code></pre>
<p>But I ended messing my head and missing things, because it also captures the first parenthesis enclosure and the following characters till the end.</p>
<p>I need some help with this.</p>
<h2>Question</h2>
<hr>
<p>How I could fix/improve my expression to treat the mentioned filenames to get the expected results above?.</p>
<p>Or in other words, I need to maintain the "structure" of the expression but adding the capability to capture the <strong>Feat...</strong> part when it is inside parenthesis/brackets to properly format the filename.</p>
<p>PS: Please remember that I'm under pascal-script's RegEx syntax and their limitations (which I'm not sure about them).</p>
<h2>IMPORTANT EDIT:</h2>
<p>I discovered that the author of the software that has this limitations it has support to run an external app from its pascal-script editor, so I can launch a CLI app written in .Net to perform the regex replacement, then I'm now under C#/Vb.Net RegEx motor improvements, nice!.</p>
| 3 | 1,571 |
Call a PHP File with AJAX
|
<p>I have been looking at other questions and based my code out of the corresponding answers, but I can't seem to make this work. I would appreciate if someone more experienced than me can help me see clearer on this one.</p>
<p><strong>jQuery:</strong></p>
<pre><code>$(function () {
$(".going-decision").click(function () {
var clickBtnValue = $(this).val();
alert('clicked');
$.ajax({
type: "POST",
url: "http://localhost/townbuddies/public_html/event_going_ajax.php",
data: {'btn-clicked': clickBtnValue},
success: function () {
alert('success');
}
});
});
});
</code></pre>
<p><strong>event_going_ajax.php:</strong></p>
<pre><code>if (isset($_POST['btn-clicked'])) {
$decision = $_POST['btn-clicked'];
//Logic that writes to database
}
</code></pre>
<p>My HTML buttons do have the class 'going-decision'. jQuery library is included.</p>
<p><strong>Result:</strong> The 'clicked' alert is displaying, along with the 'success' one. However, the database is not updated.</p>
<p>Anyone has a hint on what's going on here? Thanks.</p>
<p><strong>EDIT, here's my PHP code. I know it's non-secure code, i'm currently learning PHP.</strong></p>
<pre><code><?php
session_start();
$user_id = $_SESSION['user'];
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'townbuddies');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['btn-clicked'])) {
//Value will be in this format: 'decision.event_id'
$value = $_POST['btn-clicked'];
$length = strlen($value);
$findme = '.';
$pos = strpos($value, $findme);
//Separating the decision (going/not going) and the event_id
$decision = substr($value, 0, $pos);
$event_id = substr($value, $pos + 1);
//Verify if user is already 'going' to the event
$result = verifyDatabase($con, $user_id, $event_id);
//Depending on user decision
switch ($decision) {
case 'going':
going($con, $result, $user_id, $event_id);
break;
case 'not_going':
notGoing($con, $result, $user_id, $event_id);
break;
}
}
function verifyDatabase($con, $user_id, $event_id) {
//Verify if already in database
$sql = "SELECT * "
. "FROM user_events "
. "WHERE event_id = "
. "'$event_id'"
. "AND user_id = "
. "'$user_id'";
$result = mysqli_query($con, $sql);
return $result;
}
function going($con, $result, $user_id, $event_id) {
//If already in database as 'going', then do not duplicate. Do nothing.
if (!empty($result)) {
header("Location: http://localhost/townbuddies/public_html/event.php?event=" . $event_id);
exit;
}
//Not in database as 'going', so add it.
else {
$sql = "INSERT INTO user_events (user_id,event_id) "
. "VALUES ("
. "'$user_id'"
. ","
. "'$event_id'"
. ")";
if (!mysqli_query($con, $sql)) {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
//Update amount of people going.
$sql =
mysqli_close($con);
}
exit;
}
function notGoing($con, $result, $user_id, $event_id) {
//If already in database as 'going', then delete
if (!empty($result)) {
$sql = "DELETE FROM user_events "
. "WHERE user_id = "
. "'$user_id'"
. "AND event_id = "
. "'$event_id'";
if (!mysqli_query($con, $sql)) {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
mysqli_close($con);
}
exit;
}
?>
</code></pre>
<p><strong>EDIT#2: FORM</strong></p>
<pre><code><!DOCTYPE html>
<html lang = "en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Event</title>
<link href = "css/main.css" rel = "stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<script src="js/event.js"></script>
</head>
<body>
<button type = "submit" id = "go-btn" class = "going-decision" value="going.' . $event_id . '">Going</button>
<button type = "submit" id = "no-go-btn" class = "going-decision" value="not_going.' . $event_id . '">Not Going</button>
</body>
</code></pre>
<p></p>
<p><strong>EDIT#3: Solution</strong></p>
<p>The issue is, indeed, from my PHP script. In the functions going(), and notGoing(), the statement </p>
<pre><code>if (!empty($result))
</code></pre>
<p>will not work as expected... If I interchange the if and the else statements, everything works fine...</p>
<p>Why would an empty result from mySQL would not be empty for that statement?</p>
| 3 | 2,060 |
android : calling class from onResume()
|
<p>I am trying to call a class from onResume() of my activity. But evrytime i am getting class not found error. </p>
<p>Here is the code for the onResume():</p>
<pre class="lang-java prettyprint-override"><code> @Override
protected void onResume() {
super.onResume();
try {
sendHiddenMail sender = new sendHiddenMail("sidh*****@gmail.com", "pass");
sender.sendMail("This is Subject",
"This is Body",
"sid*****@gmail.com",
"sid*****@gmail.com");
} catch (Exception e) {
Log.e("SendMailsdfsdfsd", e.getMessage(), e);
}
}
</code></pre>
<p>Here is the class whom I want to call:</p>
<pre class="lang-java prettyprint-override"><code>public class sendHiddenMail extends javax.mail.Authenticator{
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new com.provider.JSSEProvider());
}
public sendHiddenMail(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
</code></pre>
<p>Here is the logcat:</p>
<pre><code>06-03 03:22:57.331: W/dalvikvm(4934): Unable to resolve superclass of Lcom/example/calllist/sendHiddenMail; (67)
06-03 03:22:57.331: W/dalvikvm(4934): Link of class 'Lcom/example/calllist/sendHiddenMail;' failed
06-03 03:22:57.331: E/dalvikvm(4934): Could not find class 'com.example.calllist.sendHiddenMail', referenced from method com.example.calllist.MainActivity.sendMail
06-03 03:22:57.331: W/dalvikvm(4934): VFY: unable to resolve new-instance 34 (Lcom/example/calllist/sendHiddenMail;) in Lcom/example/calllist/MainActivity;
06-03 03:22:57.331: D/dalvikvm(4934): VFY: replacing opcode 0x22 at 0x0000
06-03 03:22:57.341: W/dalvikvm(4934): Unable to resolve superclass of Lcom/example/calllist/sendHiddenMail; (67)
06-03 03:22:57.341: W/dalvikvm(4934): Link of class 'Lcom/example/calllist/sendHiddenMail;' failed
06-03 03:22:57.401: D/dalvikvm(4934): DexOpt: unable to opt direct call 0x0039 at 0x06 in Lcom/example/calllist/MainActivity;.sendMail
06-03 03:22:57.791: D/AndroidRuntime(4934): Shutting down VM
06-03 03:22:57.791: W/dalvikvm(4934): threadid=1: thread exiting with uncaught exception (group=0xb1af6b90)
06-03 03:22:57.811: E/AndroidRuntime(4934): FATAL EXCEPTION: main
06-03 03:22:57.811: E/AndroidRuntime(4934): Process: com.example.calllist, PID: 4934
06-03 03:22:57.811: E/AndroidRuntime(4934): java.lang.NoClassDefFoundError: com.example.calllist.sendHiddenMail
06-03 03:22:57.811: E/AndroidRuntime(4934): at com.example.calllist.MainActivity.sendMail(MainActivity.java:102)
06-03 03:22:57.811: E/AndroidRuntime(4934): at com.example.calllist.MainActivity.getCallDetails(MainActivity.java:81)
06-03 03:22:57.811: E/AndroidRuntime(4934): at com.example.calllist.MainActivity.onResume(MainActivity.java:35)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.app.Activity.performResume(Activity.java:5322)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2759)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2798)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2231)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.app.ActivityThread.access$700(ActivityThread.java:135)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.os.Handler.dispatchMessage(Handler.java:102)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.os.Looper.loop(Looper.java:137)
06-03 03:22:57.811: E/AndroidRuntime(4934): at android.app.ActivityThread.main(ActivityThread.java:4998)
06-03 03:22:57.811: E/AndroidRuntime(4934): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 03:22:57.811: E/AndroidRuntime(4934): at java.lang.reflect.Method.invoke(Method.java:515)
06-03 03:22:57.811: E/AndroidRuntime(4934): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
06-03 03:22:57.811: E/AndroidRuntime(4934): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
06-03 03:22:57.811: E/AndroidRuntime(4934): at dalvik.system.NativeStart.main(Native Method)
06-03 03:27:58.391: I/Process(4934): Sending signal. PID: 4934 SIG: 9
</code></pre>
<p>I have not added any information about sendHiddenMail class in mainfest.xml</p>
<p>I have no idea where I am going wrong.</p>
| 3 | 3,173 |
Why is my browser preventing me from submitting empty fields ? Symfony
|
<p>I made a form that allows users to register.</p>
<p>There is one question that asks what language they want to learn. In order to make the question optional I created the new field type to my User entity in Terminal and I specified that it can be <strong>null</strong>.</p>
<p>But, when I validate the form without answering the optional question, I have this displayed error message : <strong>Please select a valid language.</strong></p>
<p>Thank you for your help.</p>
<p><strong>register.html.twig</strong></p>
<pre><code>{% extends 'base.html.twig' %}
{% block title %}Incris-toi !{% endblock %}
{% block main %}
{{ form_start(userform) }}
<div class="form container">
{{ form_errors(userform.email) }}
{{ form_errors(userform.password) }}
{{ form_errors(userform.gender) }}
{{ form_errors(userform.firstname) }}
{{ form_errors(userform.lastname) }}
{{ form_errors(userform.birthdate) }}
{{ form_errors(userform.occupation) }}
{{ form_errors(userform.nationality) }}
{{ form_errors(userform.nativelanguage) }}
{{ form_errors(userform.wishedlanguages) }}
<div class="formpage">
<div class="form-floating mb-3">
{{ form_widget(userform.email, {'attr' : {'placeholder' : 'Mon adresse e-mail', 'class' : 'form-control'}}) }}
{{ form_label(userform.email, 'Mon adresse e-mail', {'label_attr' : {'class' : 'label'}}) }}
</div>
<div class="form-floating mb-3">
{{ form_widget(userform.password.first, {'attr' : {'placeholder' : 'Mon mot de passe', 'class' : 'form-control'}}) }}
{{ form_label(userform.password.first, 'Mon mot de passe', {'label_attr' : {'class' : 'label'}}) }}
</div>
<div class="form-floating">
{{ form_widget(userform.password.second, {'attr' : {'placeholder' : 'Confirmation de mon mot de passe', 'class' : 'form-control'}}) }}
{{ form_label(userform.password.second, 'Confirmation de mon mot de passe', {'label_attr' : {'class' : 'label'}}) }}
</div>
<div class="form-checkbox">
{{ form_widget(userform.roles) }}
<span class="checkbox"></span>
<span class="checkmark"></span>
</div>
<div>
<button type="button" class="next btn btn-lg btn-outline-primary mt-4 d-flex mx-auto">Je m'inscris</button>
</div>
</div>
<div class="formpage">
<div class="mb-3">
<p>Es-tu un homme ou une femme ?</p>
{{ form_widget(userform.gender, {'attr' : {'placeholder' : 'Es-tu un homme ou une femme ?', 'class' : 'form-control'}}) }}
</div>
<div class="form-floating mb-3">
{{ form_widget(userform.firstname, {'attr' : {'placeholder' : 'Quel est ton prénom ?', 'class' : 'form-control'}}) }}
{{ form_label(userform.firstname, 'Quel est ton prénom ?', {'label_attr' : {'class' : 'label'}}) }}
</div>
<div class="form-floating mb-3">
{{ form_widget(userform.lastname, {'attr' : {'placeholder' : 'Quel est ton nom de famille ?', 'class' : 'form-control'}}) }}
{{ form_label(userform.lastname, 'Quel est ton nom de famille ?', {'label_attr' : {'class' : 'label'}}) }}
</div>
<div class="form-floating mb-3">
<p>Quelle est ta date de naissance ?</p>
{{ form_widget(userform.birthdate) }}
</div>
<div class="d-flex">
<button type="button" class="prev btn btn-lg btn-outline-secondary mt-4 d-flex align-items-center me-auto">&lt;<span class="previous">Précédent</span></button>
<button type="button" class="next btn btn-lg btn-outline-primary mt-4 d-flex ms-auto">Suivant</button>
</div>
</div>
<div class="formpage">
<div class="form-floating mb-3">
{{ form_widget(userform.occupation, {'attr' : {'placeholder' : 'Quelle est ton occupation (ton métier, tes études…) ?', 'class' : 'form-control'}}) }}
{{ form_label(userform.occupation, 'Quelle est ton occupation (ton métier, tes études…) ?', {'label_attr' : {'class' : 'label'}}) }}
</div>
<div class="mb-3">
<p>De quel pays es-tu originaire ?</p>
{{ form_widget(userform.nationality) }}
</div>
<div class="mb-3">
<p>Quelle est ta langue maternelle ?</p>
{{ form_widget(userform.nativelanguage) }}
</div>
<div class="d-flex">
<button type="button" class="prev btn btn-lg btn-outline-secondary mt-4 d-flex align-items-center me-auto">&lt;<span class="previous">Précédent</span></button>
<button type="button" class="next optional btn btn-lg btn-outline-primary mt-4 d-flex ms-auto">Suivant</button>
<button class="btn optional-validation btn-lg btn-outline-primary mt-4 d-flex ms-auto">Je valide</button>
</div>
</div>
<div class="formpage">
<div class="mb-3">
<p>Quelle langue souhaites-tu pratiquer ?</p>
<div class="wishedlanguagelist">
{{ form_widget(userform.wishedlanguages, {'attr' : {'class' : 'form-control mb-3'}}) }}
</div>
<div class="d-flex justify-content-between">
<button type="button" class="question-button btn btn-outline-secondary" id="addwishedlanguage">+ Ajouter une langue</button>
<button type="button" class="question-button btn btn-outline-secondary" id="removewishedlanguage">- Supprimer la dernière langue</button>
</div>
</div>
<div class="d-flex">
<button type="button" class="prev btn btn-lg btn-outline-secondary mt-4 d-flex align-items-center me-auto">&lt;<span class="previous">Précédent</span></button>
{{ form_row(userform.save, {'attr' : {'class' : 'btn btn-lg btn-outline-primary mt-4 d-flex ms-auto'}}) }}
</div>
</div>
</div>
{{ form_end(userform) }}
{% endblock %}
{% block js %}
<script src="../assets/js/scripts.js"></script>
{% endblock %}
</code></pre>
<p><strong>UserType.php</strong></p>
<pre><code><?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\LanguageType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('gender', ChoiceType::class, [
'choices' => [
'Je suis ...' => '',
'un homme' => 'male',
'une femme' =>'female',
'non-binaire' => 'non-binary'
]
])
->add('lastname')
->add('firstname')
->add('birthdate', BirthdayType::class, [
'placeholder' => [
'year' => 'Année', 'month' => 'Mois', 'day' => 'Jour',
],
'choice_translation_domain' => true
])
->add('occupation')
->add('nationality', CountryType::class, [
'placeholder' => 'Je choisis un pays',
])
->add('nativelanguage', LanguageType::class, [
'placeholder' => 'Je choisis ta langue maternelle',
])
->add('wishedlanguages', LanguageType::class, [
'placeholder' => 'Je choisis une langue étrangère',
'empty_data' => [],
'required' => false,
'compound' => true,
])
->add(
$builder
->get('wishedlanguages')
->setRequired(false)
)
->add('email')
->add('password', PasswordType::class, [
'mapped' => false
])
->add('password', RepeatedType::class, [
'type' => PasswordType::class,
'invalid_message' => 'Les deux mots de passe doivent être identiques.',
'options' => ['attr' => ['class' => 'password-field']],
'required' => true,
'first_options' => ['label' => 'Password'],
'second_options' => ['label' => 'Repeat Password'],
])
->add('roles', CheckboxType::class, [
'label' => 'Je m\'inscris uniquement en tant qu\'organisateur.',
'required' => false,
'compound' => true,
])
->add(
$builder
->get('roles')
->addModelTransformer(new CallbackTransformer(
function ($arrayAsBool) {
return in_array("ROLE_ADMIN", $arrayAsBool);
},
function ($boolAsArray) {
return $boolAsArray ? ["ROLE_ADMIN"] : ["ROLE_USER"];
}))
)
->add('save', SubmitType::class, [
'label' => 'Je valide',
])
;
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => User::class,
'translation_domain' => 'forms'
]);
}
}
</code></pre>
| 3 | 5,984 |
Error - model sent to the view is incorrect
|
<p>I am getting following error message.Could somebody tell me why I am getting the following error message. My model is getting initialized with values when I debug the controller.</p>
<pre><code>The model item passed into the dictionary is of type 'AngularJSMvcExample.Models.RegistrationVm', but this dictionary requires a model item of type 'System.String'.
</code></pre>
<p>My model code</p>
<pre><code>namespace AngularJSMvcExample.Models
{
public class RegistrationVm
{
public string Courses { get; set; }
public string Instructors { get; set; }
}
}
</code></pre>
<p>My Controller code</p>
<pre><code>namespace AngularJSMvcExample.Controllers
{
public class RegistrationController : Controller
{
private RegistrationVmBuilder _registrationVmBuilder = new RegistrationVmBuilder();
// GET: Registration
public ActionResult Index()
{
return View(_registrationVmBuilder.BuildRegistrationVm());
}
}
}
</code></pre>
<p>My ViewCode</p>
<pre><code>@model AngularJSMvcExample.Models.RegistrationVm
@{
ViewBag.Title = "Registration";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container" ng-controller="RegistrationController">
<div class="row">
<div class="navbar navbar-default">
<div class="navbar-header">
<ul class="nav navbar-nav">
<li>
<span class="navbar-brand">Registration</span>
</li>
</ul>
</div>
<div class="navbar-collapse collapse">
<ul class="nav nav-bar">
<li ><a href="/Courses">Browse Catalog</a></li>
<li><a href="/Instructors">Browse Instructors</a></li>
</ul>
</div>
</div>
</div>
</div>
</code></pre>
<p>My RegistrationVmBuilder code</p>
<pre><code>namespace AngularJSMvcExample.Models
{
public class RegistrationVmBuilder
{
public RegistrationVm BuildRegistrationVm()
{
var registrationVm = new RegistrationVm
{
Courses = GetSerialisedCourse(),
Instructors = GetSerialisedInstructors()
};
return registrationVm;
}
public string GetSerialisedCourse()
{
var courses = new[]
{
new CourseVm {Number= "100", Name= "Physis", Instructor = "Jan"},
new CourseVm {Number= "101", Name= "Chemistry", Instructor = "Sal"},
new CourseVm {Number= "102", Name= "Biology", Instructor = "San"},
new CourseVm {Number= "103", Name= "History", Instructor = "Jack"},
new CourseVm {Number= "104", Name= "Maths", Instructor = "Rahul"}
};
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var serializeCourses = JsonConvert.SerializeObject(courses, settings);
return serializeCourses;
}
public string GetSerialisedInstructors()
{
var instructors = new[]
{
new InstructorsVm {Name= "Jan", Email= "jan.test@test.com", Roomno = "10"},
new InstructorsVm {Name= "Pal", Email= "pal.test@test.com", Roomno = "9"},
new InstructorsVm {Name= "San", Email= "san@test.com", Roomno = "11"},
new InstructorsVm {Name= "Jack", Email= "jack@test@test.com", Roomno = "12"},
new InstructorsVm {Name= "Rahul", Email= "rahul@test@test.com", Roomno = "15"}
};
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var serializeInstructors = JsonConvert.SerializeObject(instructors, settings);
return serializeInstructors;
}
}
}
</code></pre>
| 3 | 1,883 |
python mysql query not displaying correct result
|
<p>I have a code here and it's supposed to show all results where the selection from combobox like id = the value in the entry box. But when the code is executed I get a empty set "[]", it skips to the if statement which gives me a messagebox, despite the fact that the database is populated and it's displaying properly with the other function that I have defined before. Is there a mistake in my code or am I doing anything wrong here?</p>
<p>Thanks in advance :)</p>
<p>Take a look at the code :</p>
<pre><code>def sp_patient():
#Creating window
sp_pat = Toplevel(update)
sp_pat.title('Choose Patient')
def search():
#Assigning variable to .get()
a = drops.get()
if a == 'id' or a == 'emirate_id' or a == 'email_adress' or a == 'gender' or a == 'DOB' or a == 'blood_grp' or a == 'COVID_test':
#Establishing connection
con = mysql.connect(host='', user='',
password='', database='')
# Making SQL command
sql_command = "SELECT * FROM patient_infos where %s = %s ;"
values = a , e_1.get()
c = con.cursor()
c.execute(sql_command, values)
# Executing and saving SQL command
records = c.fetchall()
print(records)
if records == []:
messagebox.showinfo('Does not exist!','Sorry such patient does not exist')
else:
#Creating window
result_win = Toplevel(sp_pat)
result_win.title('Search result')
index=0
for index,x in enumerate(records):
num=0
for y in x:
lookup_label = Label(result_win,text=y)
lookup_label.grid(row=index+1,column=num)
num += 1
#Closing connection
con.close()
#Creating column header and exit button
l_1 = Label(result_win,text='ID',font=font_text)
l_2 = Label(result_win,text='Full Name',font=font_text)
l_3 = Label(result_win,text='Phone no.',font=font_text)
l_4 = Label(result_win,text='Emirates ID',font=font_text)
l_5 = Label(result_win,text='Email addr.',font=font_text)
l_6 = Label(result_win,text='Gender',font=font_text)
l_7 = Label(result_win,text='DOB',font=font_text)
l_8 = Label(result_win,text='Nationality',font=font_text)
l_9 = Label(result_win,text='Blood group',font=font_text)
l_10 = Label(result_win,text='COVID test',font=font_text)
l_11 = Label(result_win,text='Emergency no.',font=font_text)
btn_ext = Button(result_win,text='Exit',font=font_text,command=result_win.destroy,borderwidth=2,fg='#eb4d4b')
#Placing it in screen
l_1.grid(row=0,column=0,padx=20)
l_2.grid(row=0,column=1,padx=20)
l_3.grid(row=0,column=2,padx=20)
l_4.grid(row=0,column=3,padx=20)
l_5.grid(row=0,column=4,padx=20)
l_6.grid(row=0,column=5,padx=20)
l_7.grid(row=0,column=6,padx=20)
l_8.grid(row=0,column=7,padx=20)
l_9.grid(row=0,column=8,padx=20)
l_10.grid(row=0,column=9,padx=20)
l_11.grid(row=0,column=10,padx=20)
btn_ext.grid(row=index+2,columnspan=11,ipadx=240,sticky=E+W)
</code></pre>
| 3 | 2,095 |
How To Apply Regex in Shiny App Filter/Button?
|
<p>I'm super new to Shiny Apps and to R. How would I add a button that allows me to filter the passed-in dataset using this regex? The uploaded dataset would all contain the same column names, and the column I want to apply the regex to is "close_notes". I want to first <strong>convert this column to a string, uppercase everything, then apply the regex</strong>. Thank you so much for your help in advance!</p>
<p>The Regular Expression:</p>
<p><code>"\\bMASTER DATA\\b|\\bSOURCE LIST\\b|\\bVALIDITY DATES\\b|\\bMRP CONTROLLER\\b|\\bPSV\\b|\\bELIGIBILITY\\b|\\bCOST\\b|\\bMARKETING EXCLUSION\\b|\\bEFFECTIVITY\\b|\\bMISSING\\b|\bbBLANK\\b"</code></p>
<p>The code below is for the Shiny App. Please let me know if anything looks wrong or like it should be modified. Thank you!</p>
<pre><code>library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
tags$hr(),
checkboxInput("header", "Header", TRUE),
# Button
downloadButton("downloadData", "Download")
),
mainPanel(
dataTableOutput("contents")
)
)
)
server <- function(input, output) {
datasetInput <- reactive({
req(input$file1)
# input$file1 will be NULL initially. After the user selects
# and uploads a file, it will be a data frame with 'name',
# 'size', 'type', and 'datapath' columns. The 'datapath'
# column will contain the local filenames where the data can
# be found.
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath, header = input$header)
})
output$contents <- renderDataTable({
datasetInput()
})
output$downloadData <- downloadHandler(
filename = function() {
paste("myfile",Sys.Date(), ".csv", sep = "")
},
content = function(file) {
write.csv(datasetInput(), file, row.names = FALSE)
}
)
}
shinyApp(ui, server)
</code></pre>
| 3 | 1,165 |
Recursive custom thumbnail for embedded YouTube API won't replay
|
<p>I have an embedded YouTube video, but I want to use my own custom image for the face (thumbnail) of the video before <strong>and after</strong> the video plays. I have it working successfully up to where it shows the custom image in place of the video, and when the image is clicked, the image is removed and the video is loaded and played. Once the video is complete, the image is restored back to what appears to be the video's ready-to-play state. </p>
<p>However, once the image is clicked again to replay the video, the video won't play again. I was hoping that every time my playYouTubeVideo() function is called from the click event listener, that the YT.Player object would reset and load again, but this isn't working. </p>
<p>Any help you can give would be appreciated.</p>
<p>The stackoverflow snippet I created as a demo doesn't actually play the YouTube embed, and you kind of need to be able to see the video end to know what I mean, so I've included and link to a fiddle as well:</p>
<p><a href="https://jsfiddle.net/MichaelVanEs/otq74r3w/3/" rel="nofollow noreferrer">https://jsfiddle.net/MichaelVanEs/otq74r3w/3/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
handleYouTubePlayer();
});
//
function handleYouTubePlayer() {
// YouTube iPlayer API
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//
var player;
var playerContainer = document.getElementById("player");
var iFrameVideo = document.getElementById("iFrameVideo");
var thumbnailWrap = document.getElementById("thumbnailWrap");
//
thumbnailWrap.addEventListener("click", playYouTubeVideo, false);
//
function playYouTubeVideo() {
console.log("Comes into playYouTubeVideo");
iFrameVideo.style.display = "block";
thumbnailWrap.style.display = "none";
//
player = null;
//
player = new YT.Player("iFrameVideo", {
playerVars: {
mute: 1,
autoplay: 1,
},
events: {
"onReady": onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
//
function onPlayerReady(event) {
console.log("Comes into onPlayerReady");
event.target.mute();
event.target.playVideo();
}
//
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) { // Video has finished playing
console.log("Comes into PlayerState.ENDED");
thumbnailWrap.style.display = "block";
iFrameVideo.style.display = "none";
//
event.target.pauseVideo();
event.target.seekTo(0, true);
}
}
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.imgBrd {
box-shadow: 0 0 0 1px #ccc;
}
.vid {
display: block;
width: 550px;
height: 309px;
margin: 0 auto;
}
#player {
position: relative;
}
#iFrameVideo {
display: none;
}
#thumbnailWrap {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#thumbnail {
position: absolute;
top: 0;
left: 0;
}
#youtubeBtn {
position: absolute;
top: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
font-size: 70px;
color: rgba(40, 40, 40, 0.95);
height: 100%;
width: 100%;
z-index: 2;
}
#youtubeBtn:hover {
cursor: pointer;
color: rgba(255, 0, 0, 0.95);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div id="player" class="vid">
<div id="thumbnailWrap">
<img id="thumbnail" class="vid imgBrd" src="https://libapps-au.s3-ap-southeast-2.amazonaws.com/customers/4753/images/dragArticleToGroup-thumb.png" alt="Video thumbnail" />
<div id="youtubeBtn">
<i class="fa fa-youtube-play" aria-hidden="true"></i>
</div>
</div>
<iframe id="iFrameVideo" class="vid" src="https://www.youtube-nocookie.com/embed/tgbNymZ7vqY?rel=0&vq=hd720&enablejsapi=1" frameborder="0" allow="accelerometer; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></code></pre>
</div>
</div>
</p>
| 3 | 1,739 |
How do I get this banner to show up using bootstrap?
|
<p>I'm trying to get an image to take up the width of the page but for some reason it wont show up. I think I've set up the path to the banner correctly i did
background-image:url('/images/banner.png');</p>
<p>HTML</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel=stylesheet type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<title>Page Title</title>
</head>
<nav>
</nav>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Shiny Leaf Studio</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Username</a></li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
<div class="wide">
<div class="col-xs-5 line">
<hr>
</div>
<div class="col-xs-2 logo">Logo</div>
<div class="col-xs-5 line">
<hr>
</div>
</div>
</body>
</html>
</code></pre>
<p>CSS</p>
<pre><code>body,html {
height: 100%;
}
body {
padding-top: 50px;
}
.wide {
width:100%;
height:100%;
height:calc(100% - 1px);
background-image:url('/images/banner.png');
background-size:cover;
}
.wide img {
width:100%;
}
.logo {
color:#fff;
font-weight:800;
font-size:14pt;
padding:25px;
text-align:center;
}
.line {
padding-top:20px;
white-space:no-wrap;
overflow:hidden;
text-align:center;
}
</code></pre>
| 3 | 1,383 |
Socket connection to ftp not receiving answers
|
<p>I'm using C#, Visual Studio 2008, Framework 2.0 for embedded device.</p>
<p>I'm having trouble with the use of a Socket connection to communicate with FTPs.</p>
<p>In the purpose of you guys to help me, I wrote a snippet to explain my troubles...</p>
<pre><code> IPEndPoint endpoint;
Socket cmdsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address = IPAddress.Parse(args[0]);
endpoint = new IPEndPoint(address, int.Parse(args[1]));
// Connection
cmdsocket.Connect(endpoint);
if (cmdsocket.Connected)
{
do
{
Console.WriteLine("Type the command to send : ");
string l_sCommandToSend = Console.ReadLine();
Console.WriteLine("Do you want a timeout to receive ? (Y/N (default))");
string l_sReceiveTimeout = Console.ReadLine();
// Sending
byte[] bytes = Encoding.ASCII.GetBytes((l_sCommandToSend + "\r\n").ToCharArray());
cmdsocket.Send(bytes, bytes.Length, 0);
if (l_sReceiveTimeout == "Y")
{
Thread.Sleep(1000);
}
// Receiving
byte[] bufferToRead = new byte[512];
string l_sResponsetext = "";
int l_iByteReceivedCount = 0;
while (cmdsocket.Available > 0)
{
Console.WriteLine("Receiving...");
l_iByteReceivedCount = cmdsocket.Receive(bufferToRead, SocketFlags.None);
l_sResponsetext += Encoding.ASCII.GetString(bufferToRead, 0, l_iByteReceivedCount);
Console.WriteLine("Bytes Received : " + l_iByteReceivedCount);
Console.WriteLine("l_sResponsetext : " + l_sResponsetext);
}
Console.WriteLine("This is the answer : " + l_sResponsetext);
} while (true);
}
Console.WriteLine("Job done.");
Console.ReadLine();
// Fermeture du socket
cmdsocket.Close();
cmdsocket = null;
</code></pre>
<p>Above is a snippet that :</p>
<ul>
<li>Connect to a FTP (I'm using FileZilla Server for tests purposes on my server side)</li>
<li>Asks the user which command he wants to send</li>
<li>Asks the user if he wants a Sleep between send and receive (More details later)</li>
<li>Reads and displays the answer.</li>
</ul>
<p>I noticed that if I do not use a Sleep between a FTP command and the response, sometimes I don't get a correct response (empty string).
For example, sending the command "USER Andy" will result in the response "" when no Sleep is set. When the sleep is set to 1 second, I do get the proper answer which is "331 Password required for Andy".</p>
<p>I tried to debug my Socket without talking to a FTP and chose a software like Hercules. Everything is working as expected, my Receive method call just hangs 'til it receives an answer.</p>
<p>What am I doing wrong here ?</p>
| 3 | 1,322 |
How do I use a ListView tool to list my activity classes in Eclipse (Android) within an activity?
|
<p>I am making an app that shows a list of campfire songs, and currently all I can see on my app is a list of all the songs and when clicked on, they open up another activity. The next activity that is opened looks how I want it to, but the list of songs on the first activity (menu) only shows a list with no formatting around it or any images or buttons that I have specified in the XML. - I haven't linked these up in the code as they stop the list from appearing at all.</p>
<p>Here is my Java file for Menu.java:</p>
<pre><code>package com.lmarshall1995.scoutsongs;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity{
String classes[] = {"......"};
String items[] = {"......"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, items));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String song_activity = classes[position];
try{
Class<?> ourClass = Class.forName("com.lmarshall1995.scoutsongs." + song_activity);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
</code></pre>
<p>And here is my XML file for menu.xml that I would like the list to be put in (@+id/list):</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" xmlns:app="http://schemas.android.com/apk/lib/com.google.ads">
<TextView
android:id="@+id/SelectSong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@android:id/list"
android:layout_alignTop="@+id/ic_launcher"
android:text="@string/SelectSong"
android:textSize="20sp" />
<ListView
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="320dp"
android:layout_below="@+id/ic_launcher"
tools:listitem="@android:layout/simple_list_item_1" >
</ListView>
<ImageView
android:id="@+id/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:contentDescription="@string/ic_launcher"
android:src="@drawable/ic_launcher" />
<ImageButton
android:id="@+id/settings_button"
android:src="@drawable/settings_button_selected"
android:contentDescription="@string/action_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<ImageButton
android:id="@+id/exit_button"
android:src="@drawable/exit_button_selected"
android:contentDescription="@string/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
</code></pre>
<p>I was wondering if someone could help me turn what I think is the android.R.layout.simple_list_item_1 into my list (@+id/list) from my menu.xml file. Any suggestions?
Thanks,
From
Laurence =]</p>
| 3 | 1,605 |
Retain fragment data on screen rotation
|
<p>I have 3 fragments where 1 fragment makes changes to the other 2.</p>
<p>The problem is: When I rotate the screen background color and places of fragments 2 and 3 are restored.
I want to keep them without modifying <code>AndroidManifest.xml</code>.
Is it best to use onSaveInstanceState or setRetainInstance or both?</p>
<p>I found some other answers about retaining fragments but none of them were beneficial for my case.</p>
<p><strong>FirstFragment</strong></p>
<pre><code>public class FirstFragment extends Fragment
{
private OnFragmentInteractionListener mListener;
private ChangeColorListener mCallBack;
private boolean clickCheck = false;
public FirstFragment() { }
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
Button buttonOk = v.findViewById(R.id.button_ok);
Button btn = v.findViewById(R.id.button_replace);
buttonOk.setOnClickListener(v1 -> mCallBack.changeColor(R.color.black));
btn.setOnClickListener(v12 -> {
clickCheck = !clickCheck;
mListener.changeFragment(clickCheck);
});
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState!=null) {
mCallBack =(MainActivity)getActivity();
mListener = (MainActivity)getActivity();
}
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof ChangeColorListener) {
mCallBack = (ChangeColorListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement ChangeColorListener");
}
try {
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
</code></pre>
<p><strong>SecondFragment</strong></p>
<pre><code>public class SecondFragment extends Fragment
{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_second, container, false);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
public void change(int color){
getView().setBackgroundColor(color);
}
}
</code></pre>
<p><strong>ThirdFragment</strong></p>
<pre><code>public class ThirdFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_third, container, false);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
public void change(int color){
getView().setBackgroundColor(color);
}
}
</code></pre>
| 3 | 1,504 |
Construct count array in better than O(n^2) time complexity
|
<p>Given an array <code>A[]</code> of size <code>n</code>, construct two arrays <code>C_min[]</code> and <code>C_max[]</code> such that<br>
<code>C_min[i]</code> represents number of elements smaller than <code>A[i]</code> in <code>A[0 to i]</code> and<br>
<code>C_max[i]</code> represents number of elements greater than <code>A[i]</code> in <code>A[i to n-1]</code> </p>
<p>For example <code>A[5] = {1,2,4,3,6}</code> then <code>C_min[]</code> and <code>C_max[]</code> would be<br>
<code>C_min[5] = {0,1,2,2,4}</code><br>
<code>C_max[5] = {4,3,1,1,0}</code></p>
<p>I am not able to think of an algorithm better than O(n^2) but <a href="http://www.geeksforgeeks.org/counting-inversions/" rel="nofollow">this post</a> motivates me to think of some better way of doing this, but am not able to able apply similar kind of logic(which is mentioned in the post) here. </p>
<p>In the given post, problem given is to find no of inversion in an array. if array[i] > array[j] and j>i then it forms a inversion. for example The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).<br>
idea used to solve this problem is a merge sort algorithm.<br></p>
<blockquote>
<p>In merge process, let i is used for indexing left sub-array(L[]) and j
for right sub-array(R[]). At any step in merge(), if L[i] is greater
than R[j], then there are (mid – i+1) inversions,where mid is the
middle index passed to the merge function of merge sort. because left
and right subarrays are sorted, so all the remaining elements in
left-subarray (L[i+1], L[i+2] … L[mid]) will be greater than R[j]</p>
</blockquote>
<p>code for this logic is given below:</p>
<pre><code>#include <bits/stdc++.h>
int _mergeSort(int arr[], int temp[], int left, int right);
int merge(int arr[], int temp[], int left, int mid, int right);
/* This function sorts the input array and returns the
number of inversions in the array */
int mergeSort(int arr[], int array_size)
{
int *temp = (int *)malloc(sizeof(int)*array_size);
return _mergeSort(arr, temp, 0, array_size - 1);
}
/* An auxiliary recursive function that sorts the input array and
returns the number of inversions in the array. */
int _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left)
{
/* Divide the array into two parts and call _mergeSortAndCountInv()
for each of the parts */
mid = (right + left)/2;
/* Inversion count will be sum of inversions in left-part, right-part
and number of inversions in merging */
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid+1, right);
}
return inv_count;
}
/* This funt merges two sorted arrays and returns inversion count in
the arrays.*/
int merge(int arr[], int temp[], int left, int mid, int right)
{
int i, j, k;
int inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* i is index for right subarray*/
k = left; /* i is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right))
{
if (arr[i] <= arr[j])
{
temp[k++] = arr[i++];
}
else
{
temp[k++] = arr[j++];
/*this is tricky -- see above explanation/diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray
(if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements to original array*/
for (i=left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
/* Driver progra to test above functions */
int main(int argv, char** args)
{
int arr[] = {1, 20, 6, 4, 5};
printf(" Number of inversions are %d \n", mergeSort(arr, 5));
getchar();
return 0;
}
</code></pre>
<p>so can this count array problem be done on similar lines.</p>
<blockquote>
<p>Is it possible to construct count array in better than O(n^2)-time?</p>
</blockquote>
| 3 | 1,572 |
How to make my menu items do something?
|
<p>I am new in Android world. I have followed <a href="http://developer.android.com/training/implementing-navigation/nav-drawer.html" rel="nofollow noreferrer">this tutorial</a> to create a swipe menu but the items of this menu just show an image. I want to link every single one to a new activity, is this possible?</p>
<p>My main activity: </p>
<pre><code>public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
</code></pre>
| 3 | 2,298 |
Getting information out of a listbox windows phone 8
|
<p>i'm currently developing an app for windows phone 8, that grabs JSON data from the internet, parses it into a collection, binds this collection to a listbox and shows it. This works fine, and i do it like this:</p>
<pre><code>void downloadData()
{
// Instance of a WebClient object
WebClient downloader = new WebClient();
// EventHandler for download String completed
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(downloaded);
// AsyncDownloading of the Websitecontent and Encoding in UTF8
downloader.Encoding = Encoding.UTF8;
downloader.DownloadStringAsync(new Uri("http://scm1.hensgen.net:8181/cxf/plugins/mandantenmonitor/rs/list", UriKind.Absolute));
}
void downloaded(object sender, DownloadStringCompletedEventArgs e)
{
// tests wheter string is empty or not downloaded completely
if (e.Result == null || e.Error != null)
{
MessageBox.Show("Error occured while downloading JSON-file from server");
}
else
{
// Deserialize if downloaded succeedes
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MandantenListeRoot));
// Reads the e.Result string and writes it in UTF8 encoded into a MemoryStream and Cast it from type object to MandantenListeRoot
MandantenListeRoot root = serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(e.Result))) as MandantenListeRoot;
MandantenListe mandListe = root.mandantenListeDataMember;
// Bind the downloaded Collection to our MandantenListBox-control Panel
mandantenListeBox.ItemsSource = mandListe.MandantenCollection;
}
}
</code></pre>
<p>I want to parse and ID attribute of this collection to the next page in my up when i click on one list entry.
Now i read about this a bunch on the tubes and if i understand it correctly i should simply be able to cast the sender object in the MouseButtonDown method and pass it onto the next page like this</p>
<pre><code> private void MandantenStackPanel_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//MandantenListeMandant mandant = (sender as Button).DataContext as MandantenListeMandant
// PhoneApplicationService.Current.State["MandantenNummer"] = mandant.MandantenNummer;
NavigationService.Navigate(new Uri("/Vorlagen.xaml", UriKind.Relative));
}
</code></pre>
<p>This does not seem work and if i read the debug information i get correctly the sender object is -1. The relevant XAML for my page looks like this:</p>
<pre><code> <ListBox x:Name="mandantenListeBox" Margin="0,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Margin="0,10,0,10" Width="455" MouseLeftButtonDown="MandantenStackPanel_MouseLeftButtonDown">
<TextBlock Text="{Binding MandantenNummer}" FontSize="24" TextWrapping="Wrap"/>
<TextBlock Text="{Binding MandantenBezeichnung}" FontSize="24" TextWrapping="Wrap"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>Thank you for your help, i really appreciate it.</p>
| 3 | 1,224 |
Latest compiler versions and GLIBC_2.32 dependency
|
<ul>
<li><p>When I compile my library with <strong>GCC 11</strong> or <strong>Clang 12</strong> I get a GLIBC_2.32 dependency.</p>
</li>
<li><p>When I compile the same library with the same arguments but with older version compilers (<strong>GCC 10</strong>, <strong>Clang 11</strong>) I don't get the GLIBC_2.32 dependency.</p>
</li>
</ul>
<p>Is there a way to get rid of this dependency on newer versions of compilers?</p>
<pre><code>readelf -s mylib.so | grep GLIBC
4: 00000000 0 FUNC WEAK DEFAULT UND [...]@GLIBC_2.1.3 (2)
5: 00000000 0 FUNC GLOBAL DEFAULT UND sn[...]@GLIBC_2.0 (3)
6: 00000000 0 FUNC GLOBAL DEFAULT UND strlen@GLIBC_2.0 (3)
7: 00000000 0 FUNC GLOBAL DEFAULT UND getcwd@GLIBC_2.0 (3)
8: 00000000 0 FUNC GLOBAL DEFAULT UND dlopen@GLIBC_2.1 (4)
9: 00000000 0 FUNC GLOBAL DEFAULT UND strcmp@GLIBC_2.0 (3)
10: 00000000 0 FUNC GLOBAL DEFAULT UND dlsym@GLIBC_2.0 (5)
11: 00000000 0 FUNC GLOBAL DEFAULT UND st[...]@GLIBC_2.0 (3)
12: 00000000 0 FUNC GLOBAL DEFAULT UND fopen@GLIBC_2.1 (6)
13: 00000000 0 FUNC GLOBAL DEFAULT UND fgets@GLIBC_2.0 (3)
14: 00000000 0 FUNC GLOBAL DEFAULT UND fclose@GLIBC_2.1 (6)
15: 00000000 0 FUNC GLOBAL DEFAULT UND isspace@GLIBC_2.0 (3)
16: 00000000 0 FUNC GLOBAL DEFAULT UND memchr@GLIBC_2.0 (3)
17: 00000000 0 FUNC GLOBAL DEFAULT UND printf@GLIBC_2.0 (3)
18: 00000000 0 FUNC GLOBAL DEFAULT UND puts@GLIBC_2.0 (3)
19: 00000000 0 FUNC GLOBAL DEFAULT UND bcmp@GLIBC_2.0 (3)
20: 00000000 0 FUNC GLOBAL DEFAULT UND __[...]@GLIBC_2.0 (3)
21: 00000000 0 FUNC GLOBAL DEFAULT UND strtol@GLIBC_2.0 (3)
22: 00000000 0 FUNC GLOBAL DEFAULT UND abort@GLIBC_2.0 (3)
23: 00000000 0 OBJECT GLOBAL DEFAULT UND _[...]@GLIBC_2.32 (7) << WHAT IS THIS?
24: 00000000 0 FUNC GLOBAL DEFAULT UND sprintf@GLIBC_2.0 (3)
25: 00000000 0 FUNC GLOBAL DEFAULT UND strncmp@GLIBC_2.0 (3)
26: 00000000 0 FUNC GLOBAL DEFAULT UND gettext@GLIBC_2.0 (3)
27: 00000000 0 FUNC GLOBAL DEFAULT UND __[...]@GLIBC_2.4 (8)
28: 00000000 0 FUNC WEAK DEFAULT UND pt[...]@GLIBC_2.0 (3)
29: 00000000 0 FUNC GLOBAL DEFAULT UND realloc@GLIBC_2.0 (3)
30: 00000000 0 FUNC GLOBAL DEFAULT UND memset@GLIBC_2.0 (3)
31: 00000000 0 FUNC GLOBAL DEFAULT UND read@GLIBC_2.0 (3)
32: 00000000 0 FUNC GLOBAL DEFAULT UND memcmp@GLIBC_2.0 (3)
34: 00000000 0 FUNC WEAK DEFAULT UND pt[...]@GLIBC_2.0 (3)
35: 00000000 0 FUNC GLOBAL DEFAULT UND fputc@GLIBC_2.0 (3)
36: 00000000 0 FUNC GLOBAL DEFAULT UND fputs@GLIBC_2.0 (3)
37: 00000000 0 FUNC GLOBAL DEFAULT UND memcpy@GLIBC_2.0 (3)
38: 00000000 0 FUNC GLOBAL DEFAULT UND malloc@GLIBC_2.0 (3)
39: 00000000 0 OBJECT GLOBAL DEFAULT UND stderr@GLIBC_2.0 (3)
40: 00000000 0 FUNC GLOBAL DEFAULT UND ioctl@GLIBC_2.0 (3)
41: 00000000 0 FUNC GLOBAL DEFAULT UND fwrite@GLIBC_2.0 (3)
42: 00000000 0 FUNC GLOBAL DEFAULT UND close@GLIBC_2.0 (3)
43: 00000000 0 FUNC GLOBAL DEFAULT UND open@GLIBC_2.0 (3)
44: 00000000 0 FUNC GLOBAL DEFAULT UND syscall@GLIBC_2.0 (3)
45: 00000000 0 FUNC GLOBAL DEFAULT UND memmove@GLIBC_2.0 (3)
46: 00000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.0 (3)
47: 00000000 0 FUNC GLOBAL DEFAULT UND _[...]@GLIBC_2.3 (10)
</code></pre>
| 3 | 1,745 |
Nodes Title around a Circle
|
<p>I created a force layout around a circle in d3js (<a href="https://stackoverflow.com/questions/22439832/d3-js-how-do-i-arrange-nodes-of-a-force-layout-to-be-on-a-circle">D3.js how do I arrange nodes of a force layout to be on a circle</a>) and now I want to put the labels around like this:</p>
<p><a href="https://i.stack.imgur.com/4Hcw2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Hcw2.png" alt="enter image description here"></a></p>
<p>but right now this is what I'm getting:
You can take a look here too: <a href="https://bl.ocks.org/pierreee1/07eb3b07ba876011419168d60c587090" rel="nofollow noreferrer">https://bl.ocks.org/pierreee1/07eb3b07ba876011419168d60c587090</a></p>
<p><a href="https://i.stack.imgur.com/1Oaq4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Oaq4.png" alt="enter image description here"></a></p>
<p>What could I do to get the results I want? I searched some questions but none of the solutions have helped me.</p>
<p>Here's my code:</p>
<pre><code>// width y height
var w = 1350;
var h = 600;
// declarar la fuerza y la union de los nodos por id, ahora sin charge ni centro porque no se van a correr
var fuerza = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d){
return d.id;
}))
;
// insertar los datos y ponerlos en consola
d3.json("actores_v5.json", function(error, data){
if (error) throw error;
//verificar los datos
console.log("Número de Nodos: " + data.nodes.length)
console.log(data.nodes)
console.log("Número de Links: " + data.edges.length)
console.log(data.edges)
//svg en donde dibujar
var svg = d3.selectAll("body")
.append("svg")
.attr('width', w)
.attr('height', h)
;
//circulo invisible para dibujar los nodos
// it's actually two arcs so we can use the getPointAtLength() and getTotalLength() methods
var dim = w/2;
var circle = svg.append("circle")
//.attr("d", "M 40, "+(dim/2+40)+" a "+dim/2+","+dim/2+" 0 1,0 "+dim+",0 a "+dim/2+","+dim/2+" 0 1,0 "+dim*-1+",0")
.attr('cx', w/2)
.attr('cy', h/2)
.attr('r', 250)
.style("fill", "#ffffff")
;
//crea las lineas con un svg y los datos de "edges"
var lineas = svg.append('g')
.selectAll("line")
.data(data.edges)
.enter()
.append("path")
.attr("class", function(d) {
return "link " + d.tipo;
})
;
//crea los nodos de acuerdo a los nombres
var nodos = svg.append("g")
.selectAll("circle")
.data(data.nodes)
.enter()
.append("circle")
.attr('class', function(d){
if (d.categoria == "gobierno"){
return "nodos " + d.categoria;
}
if (d.categoria == "patrimonio"){
return "nodos " + d.categoria;
}
if (d.categoria == "planeacion"){
return "nodos " + d.categoria;
}
if (d.categoria == "ong"){
return "nodos " + d.categoria;
}
if (d.categoria == "gremios"){
return "nodos " + d.categoria;
}
if (d.categoria == "academia"){
return "nodos " + d.categoria;
}
if (d.categoria == "comunidad"){
return "nodos " + d.categoria;
}
if (d.categoria == "privado"){
return "nodos " + d.categoria;
}
if (d.categoria == "medios"){
return "nodos " + d.categoria;
}
if (d.categoria == "otros"){
return "nodos " + d.categoria;
}
})
.on("mouseover", mouseEncima)
.on("mouseout", mouseAfuera)
.attr('r', 5)
;
nodos
.filter(function(d){
return d.categoria == "gobierno"
|| d.categoria == "patrimonio"
|| d.categoria == "planeacion"
|| d.categoria == "ong"
|| d.categoria == "gremios"
|| d.categoria == "academia"
|| d.categoria == "comunidad"
|| d.categoria == "privado"
|| d.categoria == "medios"
|| d.categoria == "otros"
;
})
.style("opacity", 1)
;
//titulos de los nodos
nodos.append("title")
.text(function(d){
return d.id;
})
;
var text = svg.append("g").selectAll("text")
.data(data.nodes)
.attr('class', "text")
.enter().append("text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) {
return d.id;
})
;
//define los nodos y los links de la simulacion
fuerza.nodes(data.nodes);
fuerza.force("link").links(data.edges);
// calcula los espacios de los circulos en el circulo
var circleCoord = function(node, index, num_nodes){
var circumference = circle.node().getTotalLength();
var pointAtLength = function(l){
return circle.node().getPointAtLength(l)};
var sectionLength = (circumference)/num_nodes;
var position = sectionLength*index+sectionLength/2;
return pointAtLength(circumference-position)
}
// define la posicion de los nodos segun el calculo anterior
data.nodes.forEach(function(d, i) {
var coord = circleCoord(d, i, data.nodes.length)
d.fx = coord.x
d.fy = coord.y
});
for (i = 0; i < data.nodes.length; i++) {
var angle = (i / (data.nodes.length / 2)) * Math.PI;
//data.nodes.push({ 'angle': angle });
}
//simulación y actualizacion de la posicion de los nodos en cada "tick"
fuerza.on("tick", function(){
lineas.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
nodos.attr("cx", function(d){
return d.x = d.fx;
})
.attr('cy', function(d){
return dy = d.fy;
})
;
text.attr("x", function(d){
return dx = d.fx;
})
.attr('y', function(d){
return dy = d.fy;
})
.style("text-anchor", "start")
});
//saber si las conexiones se ven o no
var toggle = 0;
//Create an array logging what is connected to what
var linkedByIndex = {};
for (i = 0; i < data.nodes.length; i++) {
linkedByIndex[i + "," + i] = 1;
};
data.edges.forEach(function (d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
//This function looks up whether a pair are neighbours
function neighboring(a, b) {
return linkedByIndex[a.index + "," + b.index];
}
function mouseEncima() {
if (toggle == 0) {
//Reduce the opacity of all but the neighbouring nodes
d = d3.select(this).node().__data__;
nodos
.transition()
.style("opacity", function (o) {
return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
})
.attr('r', function(o){
return neighboring(d, o) | neighboring(o, d) ? 10 : 5;
})
;
lineas
.transition()
.style("stroke-opacity", function (o) {
return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
})
;
// text
// .transition()
// .style("opacity", function (o) {
// return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
// })
// ;
//Reduce the opacity
toggle = 1;
}
}
function mouseAfuera() {
nodos
.filter(function(d){
return d.categoria == "gobierno"
|| d.categoria == "patrimonio"
|| d.categoria == "planeacion"
|| d.categoria == "ong"
|| d.categoria == "gremios"
|| d.categoria == "academia"
|| d.categoria == "comunidad"
|| d.categoria == "privado"
|| d.categoria == "medios"
|| d.categoria == "otros"
;
})
.transition()
.style("opacity", 1)
.attr('r', 5)
;
// y las lineas a 0
lineas
.transition()
.style("stroke-opacity", 0.1)
;
// text
// .transition()
// .style("opacity", 0.1)
// ;
toggle = 0;
}
});
</code></pre>
| 3 | 5,097 |
ActiveRecord::AssociationTypeMismatch in Controller#create Error in my Project
|
<p>Can I get some assistance with my code which is throwing an <code>ActiveRecord::AssociationTypeMistach</code> in my JobsController#create. </p>
<pre><code>ActiveRecord::AssociationTypeMismatch (JobCategory(#70843392) expected, got "At Home" which is an instance of String(#20478408)):
app/controllers/jobs_controller.rb:46:in `create'
</code></pre>
<p>I am posting data through the form </p>
<pre><code><%= form_for @job do |f| %>
<div class="row">
<div class="col-md-4 select">
<div class="form-group">
<label>Job Category</label>
<%= f.collection_select :job_category, JobCategory.order(:job_category),
:job_category, :job_category, include_blank: false, id: "job_category",
prompt: "Select...", class: "form-control" %>
</div>
</div>
<div class="col-md-4 select">
<div class="form-group">
<label>Job Type</label>
<%= f.grouped_collection_select :job_type, JobCategory.order(:job_category),
:job_types, :job_category, :job_type_id, :job_type, id: "job_type",
prompt: "Select...", class: "form-control" %>
</div>
</div>
<div class="col-md-4 select">
<div class="form-group">
<label>Frequency</label>
<%= f.select :recurrence, [["One Off", "One Off"], ["Daily", "Daily"],
["Weekly", "Weekly"], ["Bi-Monthly", "Bi-Monthly"],
["Once-Monthly", "Once-Monthly"]],
id: "recurrence", prompt: "Select...", class: "form-control" %>
</div>
</div>
</div>
<div><%= f.submit "Post My Job", class: "btn btn-normal" %></div>
<% end %>
</code></pre>
<p>Schema for Job Model</p>
<pre><code> create_table "jobs", primary_key: "job_id", force: :cascade do |t|
t.string "job_title"
t.text "job_description"
t.text "key_instructions"
t.integer "budget"
t.datetime "booking_date"
t.string "recurrence"
t.boolean "is_flexible"
t.string "address"
t.boolean "active"
t.integer "user_id"
t.datetime "date_posted"
t.datetime "date_ending"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "featured"
t.boolean "premium"
t.integer "job_category_id"
t.integer "job_type_id"
t.string "job_category"
t.string "job_type"
t.index ["job_category_id"], name: "index_jobs_on_job_category_id"
t.index ["job_type_id"], name: "index_jobs_on_job_type_id"
t.index ["user_id"], name: "index_jobs_on_user_id"
end
</code></pre>
<p>I am posting the data from my form into my job.rb model but in the process using job_category.rb models and job_type.rb associations for additional info. The three models are related as follows</p>
<pre><code>class Job < ApplicationRecord
belongs_to :user
belongs_to :job_category
belongs_to :job_type
has_many_attached :images
validates :job_category, presence: true
validates :job_type, presence: true
validates :recurrence, presence: true
end
class JobType < ApplicationRecord
has_many :job_categories
has_many :jobs
#attr_accessible :job_type
#validates :job_type, :presence => true
end
class JobCategory < ApplicationRecord
has_many :job_types
has_many :jobs
#attr_accessible :job_category
#validates :job_category, :presence => true
end
</code></pre>
<p>Any tips on where I am going wrong would be useful. Thanks</p>
| 3 | 1,517 |
Bug with a certain SECRET_KEY, when trying to handle filebrowser, on settings
|
<p>I encounter this message :
I don't use widgy for information, just Mezzanine at 3.1.10 and Django 1.6.11</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\olive\git\MezzanineRoxdev\MezzWidgy\manage.py", line 10, in <module>
from MezzWidgy.settings import PROJECT_ROOT, PROJECT_DIRNAME
File "C:\Users\olive\git\MezzanineRoxdev\MezzWidgy\MezzWidgy\settings.py", line 3, in <module>
from filebrowser import settings
File "C:\DjangoMezzaEnvironnement\lib\site-packages\filebrowser\settings.py", line 15, in <module>
MEDIA_ROOT = getattr(settings, "FILEBROWSER_MEDIA_ROOT", settings.MEDIA_ROOT)
File "C:\DjangoMezzaEnvironnement\lib\site-packages\django\conf\__init__.py", line 54, in __getattr__
self._setup(name)
File "C:\DjangoMezzaEnvironnement\lib\site-packages\django\conf\__init__.py", line 49, in _setup
self._wrapped = Settings(settings_module)
File "C:\DjangoMezzaEnvironnement\lib\site-packages\django\conf\__init__.py", line 151, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
</code></pre>
<p>django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.</p>
<p>And my settings are : </p>
<pre><code>from __future__ import absolute_import, unicode_literals
#from django.conf import settings
from filebrowser import settings
from filebrowser.sites import site
from base import *
######################
# MEZZANINE SETTINGS #
######################
# The following settings are already defined with default values in
# the ``defaults.py`` module within each of Mezzanine's apps, but are
# common enough to be put here, commented out, for convenient
# overriding. Please consult the settings documentation for a full list
# of settings Mezzanine implements:
# http://mezzanine.jupo.org/docs/configuration.html#default-settings
# Controls the ordering and grouping of the admin menu.
#
ADMIN_MENU_ORDER = (
("Content", ("pages.Page", "blog.BlogPost",
"generic.ThreadedComment", ("Media Library", "fb_browse"),)),
("Site", ("sites.Site", "redirects.Redirect", "conf.Setting")),
("Users", ("auth.User", "auth.Group",)),
)
# A three item sequence, each containing a sequence of template tags
# used to render the admin dashboard.
#
# DASHBOARD_TAGS = (
# ("blog_tags.quick_blog", "mezzanine_tags.app_list"),
# ("comment_tags.recent_comments",),
# ("mezzanine_tags.recent_actions",),
# )
# A sequence of templates used by the ``page_menu`` template tag. Each
# item in the sequence is a three item sequence, containing a unique ID
# for the template, a label for the template, and the template path.
# These templates are then available for selection when editing which
# menus a page should appear in. Note that if a menu template is used
# that doesn't appear in this setting, all pages will appear in it.
# EXTRA_MODEL_FIELDS = (
# (
# # Dotted path to field.
# "mezzanine.blog.models.BlogPost.image",
# # Dotted path to field class.
# "somelib.fields.ImageField",
# # Positional args for field class.
# ("Image",),
# # Keyword args for field class.
# {"blank": True, "upload_to": "blog"},
# ),
# # Example of adding a field to *all* of Mezzanine's content types:
# (
# "mezzanine.pages.models.Page.another_field",
# "IntegerField", # 'django.db.models.' is implied if path is omitted.
# ("Another name",),
# {"blank": True, "default": 1},
# ),
# )
# Setting to turn on featured images for blog posts. Defaults to False.
#
# BLOG_USE_FEATURED_IMAGE = True
# If True, the south application will be automatically added to the
# INSTALLED_APPS setting.
USE_SOUTH = True
########################
# MAIN DJANGO SETTINGS #
########################
# People who get code error notifications.
# In the format (('Full Name', 'email@example.com'),
# ('Full Name', 'anotheremail@example.com'))
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = "Europe/Paris"
# If you set this to True, Django will use timezone-aware datetimes.
USE_TZ = True
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "fr-FR"
# Supported languages
_ = lambda s: s
LANGUAGES = (
('en', _('English')),
)
# A boolean that turns on/off debug mode. When set to ``True``, stack traces
# are displayed for error pages. Should always be set to ``False`` in
# production. Best set to ``True`` in local_settings.py
DEBUG = True
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False
# Tuple of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS = ("127.0.0.1",)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
)
AUTHENTICATION_BACKENDS = ("mezzanine.core.auth_backends.MezzanineBackend",)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
'compressor.finders.CompressorFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# The numeric mode to set newly-uploaded files to. The value should be
# a mode you'd pass directly to os.chmod.
FILE_UPLOAD_PERMISSIONS = 0o644
#############
# DATABASES #
#############
DATABASES = {
"default": {
# Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle".
"ENGINE": "django.db.backends.sqlite3",
# DB name or path to database file if using sqlite3.
"NAME": os.path.join(BASE_DIR, 'db.sqlite3'),
# Not used with sqlite3.
"USER": "",
# Not used with sqlite3.
"PASSWORD": "",
# Set to empty string for localhost. Not used with sqlite3.
"HOST": "",
# Set to empty string for default. Not used with sqlite3.
"PORT": "",
}
}
#########
# PATHS #
#########
import os
# Full filesystem path to the project.
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Name of the directory for the project.
PROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1]
# Every cache key will get prefixed with this value - here we set it to
# the name of the directory the project is in to try and use something
# project specific.
CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_DIRNAME
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = "/static/"
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/"))
# Put strings here, like "/home/html/django_templates"
# or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),)
TEMPLATE_DEBUG = True
################
# APPLICATIONS #
################
COMPRESS_ENABLED = True
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
COMPRESS_URL = STATIC_URL
COMPRESS_ROOT = STATIC_ROOT
GRAPPELLI_INSTALLED = True
# Store these package names here as they may change in the future since
# at the moment we are using custom forks of them.
PACKAGE_NAME_FILEBROWSER = "filebrowser_safe"
PACKAGE_NAME_GRAPPELLI = "grappelli_safe"
#########################
# OPTIONAL APPLICATIONS #
#########################
# These will be added to ``INSTALLED_APPS``, only if available.
OPTIONAL_APPS = (
"debug_toolbar",
"django_extensions",
"compressor",
PACKAGE_NAME_FILEBROWSER,
PACKAGE_NAME_GRAPPELLI,
)
INSTALLED_APPS = (
#'grappelli',
#'filebrowser',
#PACKAGE_NAME_GRAPPELLI,
#PACKAGE_NAME_FILEBROWSER,
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.redirects",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.sitemaps",
"django.contrib.staticfiles",
"django.contrib.comments",
"mezzanine.boot",
"mezzanine.conf",
"mezzanine.core",
"mezzanine.generic",
"mezzanine.blog",
"mezzanine.forms",
"mezzanine.pages",
"mezzanine.galleries",
"mezzanine.twitter",
"mezzanine_slides",
'photologue',
'sortedm2m',
'south',
'sorl.thumbnail',
#"django_libsass",
#"mezzanine.accounts",
#"mezzanine.mobile",
)
TESTING = ""
# List of processors used by RequestContext to populate the context.
# Each one should be a callable that takes the request object as its
# only parameter and returns a dictionary to add to the context.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.static",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.core.context_processors.tz",
"mezzanine.conf.context_processors.settings",
"mezzanine.pages.context_processors.page",
)
# List of middleware classes to use. Order is important; in the request phase,
# these middleware classes will be applied in the order given, and in the
# response phase the middleware will be applied in reverse order.
MIDDLEWARE_CLASSES = (
"mezzanine.core.middleware.UpdateCacheMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"mezzanine.core.request.CurrentRequestMiddleware",
"mezzanine.core.middleware.RedirectFallbackMiddleware",
"mezzanine.core.middleware.TemplateForDeviceMiddleware",
"mezzanine.core.middleware.TemplateForHostMiddleware",
"mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware",
"mezzanine.core.middleware.SitePermissionMiddleware",
# Uncomment the following if using any of the SSL settings:
# "mezzanine.core.middleware.SSLRedirectMiddleware",
"mezzanine.pages.middleware.PageMiddleware",
"mezzanine.core.middleware.FetchFromCacheMiddleware",
)
# Package/module name to import the root urlpatterns from for the project.
ROOT_URLCONF = "%s.urls" % PROJECT_DIRNAME
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = STATIC_URL + "media/"
# Configuration filebrowser
site.directory = "uploads/"
MEDIA_URL = getattr(settings, "FILEBROWSER_MEDIA_URL", settings.MEDIA_URL)
MEDIA_ROOT = getattr(settings, "FILEBROWSER_MEDIA_ROOT", settings.MEDIA_ROOT)
DIRECTORY = getattr(settings, "FILEBROWSER_DIRECTORY", 'uploads/')
#Fin de Configuration filebrowser
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
#MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/"))
SECRET_KEY = "ec6b7f1a-6f61-4b6a-85b7-8851649baa041f90c4b8-65ff-4455-b5c5"
###################
# DEPLOY SETTINGS #
###################
# These settings are used by the default fabfile.py provided.
# Check fabfile.py for defaults.
# FABRIC = {
# "SSH_USER": "", # SSH username for host deploying to
# "HOSTS": ALLOWED_HOSTS[:1], # List of hosts to deploy to (eg, first host)
# "DOMAINS": ALLOWED_HOSTS, # Domains for public site
# "REPO_URL": "ssh://hg@bitbucket.org/user/project", # Project's repo URL
# "VIRTUALENV_HOME": "", # Absolute remote path for virtualenvs
# "PROJECT_NAME": "", # Unique identifier for project
# "REQUIREMENTS_PATH": "requirements.txt", # Project's pip requirements
# "GUNICORN_PORT": 8000, # Port gunicorn will listen on
# "LOCALE": "en_US.UTF-8", # Should end with ".UTF-8"
# "DB_PASS": "", # Live database password
# "ADMIN_PASS": "", # Live admin user password
# "SECRET_KEY": SECRET_KEY,
# "NEVERCACHE_KEY": NEVERCACHE_KEY,
# }
##################
# LOCAL SETTINGS #
##################
# Allow any settings to be defined in local_settings.py which should be
# ignored in your version control system allowing for settings to be
# defined per machine.
try:
from local_settings import *
except ImportError as e:
if "local_settings" not in str(e):
raise e
####################
# DYNAMIC SETTINGS #
####################
# set_dynamic_settings() will rewrite globals based on what has been
# defined so far, in order to provide some better defaults where
# applicable. We also allow this settings module to be imported
# without Mezzanine installed, as the case may be when using the
# fabfile, where setting the dynamic settings below isn't strictly
# required.
try:
from mezzanine.ut
<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> from __future__ import absolute_import, unicode_literals
#from django.conf import settings
from filebrowser import settings
from filebrowser.sites import site
from base import *
######################
# MEZZANINE SETTINGS #
######################
# The following settings are already defined with default values in
# the ``defaults.py`` module within each of Mezzanine's apps, but are
# common enough to be put here, commented out, for convenient
# overriding. Please consult the settings documentation for a full list
# of settings Mezzanine implements:
# http://mezzanine.jupo.org/docs/configuration.html#default-settings
# Controls the ordering and grouping of the admin menu.
#
ADMIN_MENU_ORDER = (
("Content", ("pages.Page", "blog.BlogPost",
"generic.ThreadedComment", ("Media Library", "fb_browse"),)),
("Site", ("sites.Site", "redirects.Redirect", "conf.Setting")),
("Users", ("auth.User", "auth.Group",)),
)
# A three item sequence, each containing a sequence of template tags
# used to render the admin dashboard.
#
# DASHBOARD_TAGS = (
# ("blog_tags.quick_blog", "mezzanine_tags.app_list"),
# ("comment_tags.recent_comments",),
# ("mezzanine_tags.recent_actions",),
# )
# A sequence of templates used by the ``page_menu`` template tag. Each
# item in the sequence is a three item sequence, containing a unique ID
# for the template, a label for the template, and the template path.
# These templates are then available for selection when editing which
# menus a page should appear in. Note that if a menu template is used
# that doesn't appear in this setting, all pages will appear in it.
# PAGE_MENU_TEMPLATES = (
# (1, "Top navigation bar", "pages/menus/dropdown.html"),
# (2, "Left-hand tree", "pages/menus/tree.html"),
# (3, "Footer", "pages/menus/footer.html"),
# )
USE_SOUTH = True
########################
# MAIN DJANGO SETTINGS #
########################
# People who get code error notifications.
# In the format (('Full Name', 'email@example.com'),
# ('Full Name', 'anotheremail@example.com'))
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
TIME_ZONE = "Europe/Paris"
# If you set this to True, Django will use timezone-aware datetimes.
USE_TZ = True
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "fr-FR"
# Supported languages
_ = lambda s: s
LANGUAGES = (
('en', _('English')),
)
# A boolean that turns on/off debug mode. When set to ``True``, stack traces
# are displayed for error pages. Should always be set to ``False`` in
# production. Best set to ``True`` in local_settings.py
DEBUG = True
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False
# Tuple of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS = ("127.0.0.1",)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
)
AUTHENTICATION_BACKENDS = ("mezzanine.core.auth_backends.MezzanineBackend",)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
'compressor.finders.CompressorFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# The numeric mode to set newly-uploaded files to. The value should be
# a mode you'd pass directly to os.chmod.
FILE_UPLOAD_PERMISSIONS = 0o644
#########
# PATHS #
#########
import os
# Full filesystem path to the project.
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Name of the directory for the project.
PROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1]
STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/"))
TEMPLATE_DEBUG = True
################
# APPLICATIONS #
################
COMPRESS_ENABLED = True
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
COMPRESS_URL = STATIC_URL
COMPRESS_ROOT = STATIC_ROOT
GRAPPELLI_INSTALLED = True
# Store these package names here as they may change in the future since
# at the moment we are using custom forks of them.
PACKAGE_NAME_FILEBROWSER = "filebrowser_safe"
PACKAGE_NAME_GRAPPELLI = "grappelli_safe"
#########################
# OPTIONAL APPLICATIONS #
#########################
# These will be added to ``INSTALLED_APPS``, only if available.
OPTIONAL_APPS = (
"debug_toolbar",
"django_extensions",
"compressor",
PACKAGE_NAME_FILEBROWSER,
PACKAGE_NAME_GRAPPELLI,
)
INSTALLED_APPS = (
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.redirects",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.sitemaps",
"django.contrib.staticfiles",
"django.contrib.comments",
"mezzanine.boot",
"mezzanine.conf",
"mezzanine.core",
"mezzanine.generic",
"mezzanine.blog",
"mezzanine.forms",
"mezzanine.pages",
"mezzanine.galleries",
"mezzanine.twitter",
"mezzanine_slides",
'photologue',
'sortedm2m',
'south',
'sorl.thumbnail',
#"django_libsass",
#"mezzanine.accounts",
#"mezzanine.mobile",
)
TESTING = ""
# List of processors used by RequestContext to populate the context.
# Each one should be a callable that takes the request object as its
# only parameter and returns a dictionary to add to the context.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.static",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.core.context_processors.tz",
"mezzanine.conf.context_processors.settings",
"mezzanine.pages.context_processors.page",
)
# List of middleware classes to use. Order is important; in the request phase,
# these middleware classes will be applied in the order given, and in the
# response phase the middleware will be applied in reverse order.
MIDDLEWARE_CLASSES = (
"mezzanine.core.middleware.UpdateCacheMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"mezzanine.core.request.CurrentRequestMiddleware",
"mezzanine.core.middleware.RedirectFallbackMiddleware",
"mezzanine.core.middleware.TemplateForDeviceMiddleware",
"mezzanine.core.middleware.TemplateForHostMiddleware",
"mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware",
"mezzanine.core.middleware.SitePermissionMiddleware",
# Uncomment the following if using any of the SSL settings:
# "mezzanine.core.middleware.SSLRedirectMiddleware",
"mezzanine.pages.middleware.PageMiddleware",
"mezzanine.core.middleware.FetchFromCacheMiddleware",
)
# Package/module name to import the root urlpatterns from for the project.
ROOT_URLCONF = "%s.urls" % PROJECT_DIRNAME
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = STATIC_URL + "media/"
# Configuration filebrowser
site.directory = "uploads/"
MEDIA_URL = getattr(settings, "FILEBROWSER_MEDIA_URL", settings.MEDIA_URL)
MEDIA_ROOT = getattr(settings, "FILEBROWSER_MEDIA_ROOT", settings.MEDIA_ROOT)
DIRECTORY = getattr(settings, "FILEBROWSER_DIRECTORY", 'uploads/')
#Fin de Configuration filebrowser
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
#MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/"))
SECRET_KEY = "ec6b7f1a-6f61-4b6a-85b7-8851649baa041f90c4b8-65ff-4455-b5c5"
##################
# LOCAL SETTINGS #
##################
# Allow any settings to be defined in local_settings.py which should be
# ignored in your version control system allowing for settings to be
# defined per machine.
try:
from local_settings import *
except ImportError as e:
if "local_settings" not in str(e):
raise e
####################
# DYNAMIC SETTINGS #
####################
# set_dynamic_settings() will rewrite globals based on what has been
# defined so far, in order to provide some better defaults where
# applicable. We also allow this settings module to be imported
# without Mezzanine installed, as the case may be when using the
# fabfile, where setting the dynamic settings below isn't strictly
# required.
try:
from mezzanine.utils.conf import set_dynamic_settings
except ImportError:
pass
else:
set_dynamic_settings(globals())</code></pre>
</div>
</div>
ils.conf import set_dynamic_settings
except ImportError:
pass
else:
set_dynamic_settings(globals())
</code></pre>
| 3 | 9,410 |
listview with button and call the previous step after clicking
|
<p>I'm new to android development. I have 2 <code>ListView</code>s. when I click on one item on the first <code>ListView</code>, the new dataset will show in the second one. I have added a <code>Button</code> to the second <code>ListView</code> (<code>onItemClick</code>). Using an <code>Adapter</code>. So when I click on the <code>Button</code> (Read more) it will load a new <code>Activity</code>. So when I click on the <code>Back</code> <code>Button</code> i need to load the same data(listview2) in my previous step.</p>
<pre><code>int images[] ={R.drawable.boc, R.drawable.commercial, R.drawable.nations, R.drawable.popls};
adp = new ItemsAdapter(getActivity(), images);
menu.setAdapter(adp);
menu.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView tv2 = (TextView) v.findViewById(R.id.listViewText);
/*ImageButton imgbtn = (ImageButton) v.findViewById(R.id.AddButton);
ImageButton imgbtn2 = (ImageButton) v.findViewById(R.id.AddInfo);
*/
switch (arg2) {
case 0:
ListAdapter adapter3 = new ListAdapter(getActivity(), boc) ;
menu2.setAdapter(adapter3);
break;
case 1:
// menu2.setAdapter(new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1,subitems2));
ListAdapter adapter4 = new ListAdapter(getActivity(), bankcrcards) ;
menu2.setAdapter(adapter4);
break;
default:
break;
}
}
});
menu2.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ImageView imgbtn1 = (ImageView) arg1.findViewById(R.id.imageView2);
imgbtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "error", Toast.LENGTH_SHORT).show();
expandableListView=new ExpandableListFragment();
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.setCustomAnimations( R.anim.fade_in, R.anim.fade_out);
transaction.replace(R.id.myFragement,expandableListView);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
}
});
}
});
</code></pre>
| 3 | 1,372 |
how to change the display amount of viewpager title?
|
<p>Can i know how to change the specific amount of the view-pager title? Currently, the view-pager only able to show 3 title at once by default. In this case, i intend to change the total display amount into 5. I tried to use tab host and others layout cannot achieve what i want to display. </p>
<p>Actually what i want to display from the view-pager is the icon to be display, i want to display 5 icon on the title there, is there any way to achieve it? </p>
| 3 | 1,237 |
Django Form Date Input Field Not Showing Errors
|
<p>I have a form on a registration page that requires a date to be entered, along with a few other fields. If the user enters non-valid information into the date field (like a string) and submits the form, Django rejects the form as non-valid, but I don't get any error messages on the page - But for the other fields on the form, I do get error messages (ex: Passwords Don't Match, User Already Registered, etc).</p>
<p>Here is what the form looks like:
<a href="https://i.stack.imgur.com/FLWvE.png" rel="nofollow noreferrer">Link to image of registration form</a></p>
<p>Here is my <strong>forms.py</strong> file - I'm using two classes to create the form on the registration page:</p>
<pre class="lang-py prettyprint-override"><code>from django import forms
from users.models import Profile
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta(UserCreationForm.Meta):
model = User
#fields = UserCreationForm.Meta.fields + ("email",)
fields = ['username', 'email', 'password1', 'password2']
class EmployeeForm(forms.ModelForm):
hireDate = forms.DateField(
required=False,
error_messages={'required': 'Please enter a valid date'},
input_formats=[
'%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y'
]) # '10/25/06')
class Meta:
model = Profile
fields = ['hireDate', 'employeeNumber']
</code></pre>
<p>Here is the <strong>models.py</strong> field with the model for the profile:</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
#confirmed = models.BooleanField("Confirmed", default=False)
hireDate = models.DateField(auto_now=False,
auto_now_add=False,
verbose_name='Date of Hire',
null=True)
employeeNumber = models.CharField(max_length=10,
verbose_name='Employee Number',
null=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
</code></pre>
<p>And here is the <strong>views.py</strong> that presents the form - I'm combining two forms into one, and submitting with one button/input. The problem seems to lie with the second form (EmployeeForm), the first form (CustomUserCreationForm) seems to work fine:</p>
<pre class="lang-py prettyprint-override"><code>from django.contrib.auth import login
from django.shortcuts import redirect, render
from django.urls import reverse
from users.forms import CustomUserCreationForm, EmployeeForm
from users.models import User, Profile
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.contrib import messages #import messages
def dashboard(request):
return render(request, "users/dashboard.html")
#@login_required
# @transaction.atomic
def register(request):
if not request.user.is_authenticated:
if request.method == 'POST':
form = CustomUserCreationForm(
request.POST) #, instance=request.user)
e_form = EmployeeForm(
request.POST) #, instance=request.user.profile)
if form.is_valid() and e_form.is_valid():
user = form.save()
user.refresh_from_db(
) # load the profile instance created by the signal
e_form = EmployeeForm(request.POST, instance=user.profile)
e_form.full_clean()
e_form.save()
messages.success(request, f'Your account has been approved!')
return redirect('login')
else:
form = CustomUserCreationForm()
e_form = EmployeeForm()
print(form.errors)
print(e_form.errors)
context = {'form': form, 'e_form': e_form}
return render(request, 'users/register.html', context)
else:
return redirect('dashboard')
</code></pre>
<p>And finally here is the html for the form on the <strong>template</strong> that presents the registration page - as you can see, I've tried a few different ways to get the form to present error messages, but none of them are working for the date field:</p>
<pre class="lang-html prettyprint-override"><code> <form class="text-center" method="post">
{% csrf_token %}
<!--Username-->
<div class="mb-3"><input class="form-control" type="text" name="username" placeholder="Username" required id="{{ field.id_username }}"</div>
<div class="text-danger">
{% for error in form.username.errors %}{{ error }}<br/>{% endfor %}
</div>
<!--Email-->
<div class="mb-3"></div>
<div class="mb-3"><input class="form-control" type="email" name="email" placeholder="Email" required id="{{ field.id_email }}"</div>
<div class="text-danger">
<!-- {% for error in form.register.errors %}{{ error }}<br/>{% endfor %} -->
</div>
<!--Password-->
<div class="mb-3"></div>
<div class="mb-3"><input class="form-control" type="password" name="password1" autocomplete="password" required id="{{ field.id_password1 }}" placeholder="Password"></div>
<div class="text-danger">
{% for error in form.password1.errors %}{{ error }}<br/>{% endfor %}
</div>
<!--Password Confirm-->
<div class="mb-3"></div>
<div class="mb-3"><input class="form-control" type="password" name="password2" autocomplete="password" required id="{{ field.id_password2 }}" placeholder="Confirm Password"></div>
<div class="text-danger">
{% for error in form.password2.errors %}{{ error }}<br/>{% endfor %}
</div>
<!--Date of Hire -->
<div class="mb-3"></div>
<div class="mb-3"><input class="form-control" type="text" name="hireDate" autocomplete="Date of Hire" required id="{{ field.id_hireDate }}" placeholder="Date of Hire"></div>
<div class="text-danger">
{% for error in form.hireDate.errors %}{{ error }}<br/>{% endfor %}
</div>
<!-- Employee Number -->
<div class="mb-3"></div>
<div class="mb-3"><input class="form-control" type="text" name="employeeNumber" autocomplete="Employee Number" required id="{{ field.id_employeeNumber }}" placeholder="Employee Number"></div>
<div class="text-danger">
<!-- {% for error in form.register.errors %}{{ error }}<br/>{% endfor %}-->
</div>
{{ form.non_field_errors }}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p> {{ error }} </p>
{% endfor %}
{% endfor %}
{% endif %}
<input class="btn btn-primary d-block w-100" type="submit" value="Register">
<div class="mb-3"></div>
<a class="text-muted" href="{% url 'login' %}">Back to Login</a>
</form>
</code></pre>
<p>I'm not sure what else I can do to get the Form to offer error message to the user if the date is entered incorrectly.</p>
| 3 | 5,224 |
popup alert - search loop
|
<p>I am a beginner so the question may be strange :)</p>
<p>I want to test the Main Menu of the website "https://tvn24.pl/"</p>
<p>I am looking for elements, I put them into the list and then iterating through it opening each page found - Works fine</p>
<p>Now step two:
On only two pages(<a href="https://kontakt24.tvn24.pl/" rel="nofollow noreferrer">https://kontakt24.tvn24.pl/</a> and <a href="https://tvn24.pl/" rel="nofollow noreferrer">https://tvn24.pl/</a> ) a window pops up in which you should click the "consent" button.</p>
<p>It is a completely different confirmation dialog for each page (different xpath, Id, etc.)</p>
<p>I would like to write functions (loops)
Which will be checked for 5 seconds if the window appeared, if so, click the accept button.
I would like this function to check both cases of "alert".
If a window "A" pops up - Click Accept - end of function
If a "B" window pops up instead of "A" - Click Accept - end of function
If no window pops up, do nothing.</p>
<p>Attention :</p>
<ol>
<li>These popups are elements that cover the entire page.</li>
<li>These are not allerts or frames - ordinary "DIV" so you can't use swith to alert or frame</li>
<li>I know, I can also use a try:</li>
</ol>
<p>Any hints?
Loop while with if, elif?</p>
<p>I tried something like this but it doesn't work</p>
<pre><code>def alert_accept_if_with_Wait_V2(driver):
V1_alert_window_Id = "onetrust-banner-sdk"
V1_accept_button_Id = 'onetrust-accept-btn-handler'
V2_alert_frame_Id = "rodoLayer"
V2_accept_button_Xpath = './/*[@id="rodoLayer"]//a[@class="rodoFooterBtnAccept"]'
wait = WebDriverWait(driver, timeout=5, poll_frequency=0.5)
if wait.until(ec.presence_of_element_located((By.ID, V1_alert_window_Id))):
wait.until(ec.element_to_be_clickable((By.ID, V1_accept_button_Id))).click()
print(f"On page {driver.current_url} onetrust alert accepted")
elif wait.until(ec.presence_of_element_located((By.ID, V2_alert_frame_Id))):
wait.until(ec.element_to_be_clickable((By.ID, V2_accept_button_Xpath))).click()
print(f"On page {driver.current_url} old alert accepted")
else:
print(f"On page {driver.current_url} no alert appeared ")
</code></pre>
<p>Another :</p>
<pre><code>def alert_accept_if_with_Wait_V1(driver, max_seconds_to_wait=5):
V1 = './/*[@id="onetrust-accept-btn-handler"] '
V2 = './/*[@id="rodoLayer"]//a[@class="rodoFooterBtnAccept"]'
seconds = 0
while range(max_seconds_to_wait):
if driver.find_element_by_xpath(V1 or V2):
driver.find_element_by_xpath(V1 or V2).click()
return False
else:
seconds += 1
time.sleep(1)
else:
print(f"On page {driver.current_url} no alert appeared ")
</code></pre>
| 3 | 1,173 |
Pagination did not work on the first page. The current path, &vacancy=2, didn't match any of these
|
<p>I am implementing search with pagination in Django.
When I clicked Next pagination button, received error:</p>
<blockquote>
<p>Page not found (404)
Request Method: GET
Request URL: <a href="http://127.0.0.1:8001/&vacancy%3D2" rel="nofollow noreferrer">http://127.0.0.1:8001/&vacancy%3D2</a></p>
</blockquote>
<p><a href="https://i.stack.imgur.com/znQeO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/znQeO.png" alt="enter image description here"></a></p>
<p>Also, pagination works after search (e.g. I searched something, then clicked pagination and it works)</p>
<p>I think that problem with views.py an urls.py
How can I solve the problem?</p>
<p><strong>models.py</strong></p>
<pre><code>class Company(models.Model):
name = models.CharField(max_length=200)
about = models.TextField()
def __str__(self):
return self.name
class Vacancy(models.Model):
company_key = models.ForeignKey(Company, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
salary = models.CharField(max_length=200, default='40.000')
text = models.TextField(default="The text about vacancy")
city = models.CharField(max_length=200, default='Москва')
date_str = models.CharField(max_length=50, default='12 сентября')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
CHOICES = [
('ALL', 'ALL'),
('IT', 'IT'),
('FINANCE', 'FINANCE'),
('OTHER', 'OTHER'),
]
department = models.CharField(
max_length=20,
choices=CHOICES,
default='ALL',
)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>urlpatterns = [
path('', HomePageView.as_view(), name='vacancy_list'),
path('search/', SearchResultsView.as_view(), name='search_results'),
path('vacancy/<int:pk>/', views.vacancy_detail, name='vacancy_detail'),
path('accounts/login/', BBLoginView.as_view(), name='login'),
path('accounts/profile/', profile, name='profile'),
path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
...
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>class HomePageView(ListView):
model = Vacancy
template_name = 'vacancy_list/vacancy_list.html'
paginate_by = 5
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def vacancy_detail(request, pk):
vacancy = get_object_or_404(Vacancy, pk=pk)
return render(request, 'vacancy_list/vacancy_detail.html', {'vacancy': vacancy})
class SearchResultsView(ListView):
model = Vacancy
template_name = 'vacancy_list/search_results.html'
paginate_by = 5
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['query'] = self.request.GET.get('q')
# added param
context['query2'] = self.request.GET.get('q2')
return context
def get_queryset(self): # new
query = self.request.GET.get('q')
query2 = self.request.GET.get('q2')
object_list = Vacancy.objects.filter(
Q(title__icontains=query) and Q(department__icontains=query2)
)
return object_list
</code></pre>
<p><strong>vacancy_list.html</strong></p>
<pre><code>{% block content %}
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-8">
<h1><a href="{% url 'vacancy_detail' pk=vacancy.pk %}">{{vacancy.title}}</a></h1>
</div>
<div class="col-md-4 text-right">
<p> {{ vacancy.salary}} </p>
</div>
</div>
</div>
<div class="card-body" style="white-space:normal">
<p class="text-secondary">{{vacancy.company_key.name}}</p>
<p> Описание вакансии: Компания Sixhands, занимающаяся разработкой мобильных приложений и веб-порталов в Санкт-Петербурге, ищет Backend-разработчика для создания серверной части мобильных приложений.
<div class="row">
<div class="col-md-8">
<p>{{vacancy.city}} </p>
</div>
<div class="col-md-4 text-right">
<p> {{vacancy.date_str }} </p>
</div>
</div>
</div>
</div>
{% endfor %}
<!-- Paginator -->
<div class="container" style="font-size: 2rem;">
<div class="row justify-content-center">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="{{ request.get_full_path }}?vacancy={{ page_obj.previous_page_number }}">Previous</a></li>
{% else %}
<li class="page-item disabled">
<span class="page-link">Previous</span>
</li>
{% endif %}
<li class="page-item disabled">
<span class="page-link">Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>
</li>
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="{{ request.get_full_path }}?vacancy={{ page_obj.next_page_number }}">Next</a></li>
{% else %}
<li class="page-item disabled">
<span class="page-link">Next</span>
</li>
{% endif %}
</ul>
</div>
</div>
</div> <!-- wrapper end -->
{% endblock %}
</code></pre>
| 3 | 3,765 |
Enabling Logs for AWS WAF WebAcl does not work in CDK
|
<p>My goal is to enable logging for a regional WebAcl via AWS CDK. This <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafv2-loggingconfiguration.html" rel="nofollow noreferrer">seems to be possible</a> over Cloud Formation and there are the appropriate constructs in CDK. But when using the following code to create a Log Group and linking it in a <a href="https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_wafv2.CfnLoggingConfiguration.html" rel="nofollow noreferrer">LoggingConfiguration</a> ...</p>
<pre><code> const webAclLogGroup = new LogGroup(scope, "awsWafLogs", {
logGroupName: `aws-waf-logs`
});
// Create logging configuration with log group as destination
new CfnLoggingConfiguration(scope, "webAclLoggingConfiguration", {
logDestinationConfigs: webAclLogGroup.logGroupArn, // Arn of LogGroup
resourceArn: aclArn // Arn of Acl
});
</code></pre>
<p>... I get an exception during <code>cdk deploy</code>, stating that the string in the LogdestinationConfig is not a correct Arn (some parts of the Arn in the log messages have been removed):</p>
<pre><code>Resource handler returned message: "Error reason: The ARN isn't valid. A valid ARN begins with arn: and includes other information separated by colons or slashes., field: LOG_DESTINATION, parameter: arn:aws:logs:xxx:xxx:xxx-awswaflogsF99ED1BA-PAeH9Lt2Y3fi:* (Service: Wafv2, Status Code: 400, Request ID: xxx, Extended Request ID: null)"
</code></pre>
<p>I cannot see an error in the generated Cloud Formation code after <code>cdk synth</code>:</p>
<pre><code>"webAclLoggingConfiguration": {
"id": "webAclLoggingConfiguration",
"path": "xxx/xxx/webAclLoggingConfiguration",
"attributes": {
"aws:cdk:cloudformation:type": "AWS::WAFv2::LoggingConfiguration",
"aws:cdk:cloudformation:props": {
"logDestinationConfigs": [
{
"Fn::GetAtt": [
{
"Ref": "awsWafLogs58D3FD01"
},
"Arn"
]
}
],
"resourceArn": {
"Fn::GetAtt": [
"webACL",
"Arn"
]
}
}
},
"constructInfo": {
"fqn": "aws-cdk-lib.aws_wafv2.CfnLoggingConfiguration",
"version": "2.37.1"
}
},
</code></pre>
<p>I'm using Cdk with Typescript and the Cdk version is currently set to <code>2.37.1</code> but it also did not work with <code>2.16.0</code>.</p>
| 3 | 1,135 |
SAXParser to parse XML data from CLOB in Java-Hibernate
|
<p>I'm working on a web application that uses Spring MVC and Hibernate,</p>
<p>I want to parse a XML data from CLOB and print it,
I was follow this tutorial <a href="http://thinktibits.blogspot.com/2013/01/read-xmltype-as-clob-java-jdbc-example.html" rel="nofollow">thinktibits</a> and <a href="http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/" rel="nofollow">mkyong</a> but I got stuck from this point,
I can't print the xml element that I want,</p>
<p>this is my code,</p>
<pre><code>@RequestMapping(value="/admin/Detail-BPJS-TK.html")
public ModelAndView listDetailBPJSTK(ModelMap model, HttpServletRequest request, HttpServletResponse response)throws ParserConfigurationException, SAXException, Exception{
if(!((request.getParameter("MESSAGEID")) == null)){
String MESSAGEID = request.getParameter("MESSAGEID");
System.out.println(MESSAGEID);
//140721438362
//DetailBPJS detailbpjs = detailbpjsService.get(MESSAGEID);
//String tes = detailbpjs.getMESSAGEID();
//System.out.println(tes);
Configuration cfg = new Configuration();
cfg.configure("hibernatesoaappbpjstk.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
String pay = "PAYMENT";
String sub = "PROCESSED";
Query query = session.createQuery("from DetailBPJS where TRANSACTION = :tra and SUBTRANSACTION = :sub and MESSAGEID = :mes");
query.setParameter("tra", pay);
query.setParameter("sub", sub);
query.setParameter("mes", MESSAGEID);
@SuppressWarnings("unchecked")
List <DetailBPJS> result = query.list();
if(result.isEmpty()){
System.out.println("Please, check the 'No. Billing' again!!");
System.out.println(MESSAGEID);
model.addAttribute("errorMessageBPJSTK", "true");
}else{
DetailBPJS data = (DetailBPJS)result.get(0);
String nom1 = data.getTRANSACTION();
String nom2 = data.getSUBTRANSACTION();
String nom3 = data.getUUID();
Clob nom4 = data.getRAWDATA();
System.out.println(nom1 + " - " + nom2 + " - " + nom3 + " - " + nom4);
//140721438362
//convert clob to java.io.reader
Reader myclob = nom4.getCharacterStream();
//create InputSource from Reader
InputSource myinput = new InputSource(myclob);
try {
SAXParserFactory factoryz = SAXParserFactory.newInstance();
SAXParser saxParser = factoryz.newSAXParser();
DefaultHandler handler = new DefaultHandler(){
boolean b_krb = false;
boolean b_reqid = false;
boolean b_ch = false;
boolean b_kb = false;
boolean b_tgl = false;
boolean tot = false;
boolean jht = false;
boolean jkk = false;
boolean jkm = false;
@SuppressWarnings("unused")
public void startElements(String uri, String localName, String qName, Attributes attributes) throws SAXException{
if (qName.equalsIgnoreCase("bpjs:kodeRefBank")){
b_krb = true;
System.out.println("yup");
}
if (qName.equalsIgnoreCase("bpjs:reqId")){
b_reqid = true;
}
if (qName.equalsIgnoreCase("bpjs:chId")){
b_ch = true;
}
if (qName.equalsIgnoreCase("bpjs:kodeBank")){
b_kb = true;
}
if (qName.equalsIgnoreCase("bpjs:tglTrx")){
b_tgl = true;
}
if (qName.equalsIgnoreCase("totalAmount")){
tot = true;
}
if (qName.equalsIgnoreCase("amountJHT")){
jht = true;
}
if (qName.equalsIgnoreCase("amountJKK")){
jkk = true;
}
if (qName.equalsIgnoreCase("amountJKM")){
jkm = true;
}
}
@SuppressWarnings("unused")
public void character(char ch[], int start, int length) throws SAXException{
if (b_krb){
System.out.println("(1) Value Of KodeRefBank : " + new String(ch, start, length));
b_krb = false;
}
if (b_reqid){
System.out.println("(2) Value Of ReqId : " + new String(ch, start, length));
b_reqid = false;
}
if (b_ch){
System.out.println("(3) Value Of ChId : " + new String(ch, start, length));
b_ch = false;
}
if (b_kb){
System.out.println("(4) Value Of KodeBank : " + new String(ch, start, length));
b_kb = false;
}
if (b_tgl){
System.out.println("(5) Value Of TglTrx : " + new String(ch, start, length));
b_tgl = false;
}
if (tot){
System.out.println("(6) Value Of Tot : " + new String(ch, start, length));
tot = false;
}
if (jht){
System.out.println("(7) Value Of JHT : " + new String(ch, start, length));
jht = false;
}
if (jkk){
System.out.println("(8) Value Of JKK : " + new String(ch, start, length));
jkk = false;
}
if (jkm){
System.out.println("(9) Value Of JKM : " + new String(ch, start, length));
jkm = false;
}
}
};
saxParser.parse(myinput, handler);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
//SAX Parser to parse this xml
}
session.close();
factory.close();
}else{
System.out.println("Please, check the 'No. Billing' again!!");
String MESSAGEID = request.getParameter("MESSAGEID");
System.out.println(MESSAGEID);
model.addAttribute("errorMessageBPJSTK", "true");
}
return listDetailBPJS(model);
}
</code></pre>
| 3 | 4,140 |
How to read file zip using JSZip in Firefox SDK
|
<p>I want to make addons to work to extract the zip file locally like this (<a href="https://stuk.github.io/jszip/documentation/examples/read-local-file-api.html" rel="nofollow">here</a>). But I have a problem when making use firefox SDK. Which can not be read zip because somethings wrong when get path of <strong>fileinput</strong> and errors unsupported format because <strong>dataType</strong> not ArrayBuffer.</p>
<p><strong>HTML</strong> </p>
<pre><code><input type="file" name="file" id="import" class="hide" />
</code></pre>
<p><strong>myscript.js</strong></p>
<pre><code>var fileInput = document.getElementById('import');
fileInput.addEventListener('change', function(e) {
var zipFileToLoad = fileInput.files[0];
var tampJson = [];
JSZip.loadAsync(zipFileToLoad)
.then(function(zip) {
console.dir(zip);
zip.forEach(function (relativePath, zipEntry) {
if(zipEntry.dosPermissions == null){
alert('Permissions trouble !')
}
if(typeof(zipEntry['_data']['compressedContent']) != 'undefined'){
//var text = String.fromCharCode.apply(null, new Uint8Array(zipEntry['_data']['compressedContent']));
var text = new TextDecoder("utf-8").decode(zipEntry['_data']['compressedContent']);
var dec = text.toString();
var json = JSON.parse(dec);
if(json != null){
var keys = ['name', 'description', 'data', 'created_at', 'updated_at'];
keys.forEach(function(key){
if (key in json){
if(key == keys[keys.length - 1]){
tampJson.push(json);
}
}else{
dialog({
title: "Warning",
description: "<b>Wrong format, </b> are you sure to continue?",
yesButton: "yes",
cancelButton: "No",
yesCallback: function() {
$(this).closest('.overlay').removeClass("active");
},
cancelCallback: function() {
$(this).closest('.overlay').removeClass("active");
return false;
}
});
}
});
}else{
alert('format parse gagal');
}
}
});
if(tampJson.length > 0){
saveByImport(tampJson, 0);
}else{
alert('Oops file empty');
}
}, function (e) {
alert('Oops import fail '+ e);
});
</code></pre>
<p>Can't error in console. I just can not ArrayBuffer from fileinput.
This script can work in chrome extension but not work in firefox sdk.
So please help me for solving this problem.</p>
| 3 | 2,014 |
formSheet never works on iOS
|
<p>I've been trying to integrate "onRequestClose" that basically closes the formSheet on iOS whenever swiped down but it never really seems to work.</p>
<p>Demo Link: <a href="https://snack.expo.dev/aN0gVemPi" rel="nofollow noreferrer">https://snack.expo.dev/aN0gVemPi</a></p>
<p>Or the code:</p>
<pre><code>import React, { useState } from "react";
import { Alert, Modal, StyleSheet, Text, Pressable, View } from "react-native";
const App = () => {
const [modalVisible, setModalVisible] = useState(false);
return (
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
presentationStyle="formSheet"
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View >
<View style={styles.modalView}>
<Text style={styles.modalText}>Hello World!</Text>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</Pressable>
</View>
</View>
</Modal>
<Pressable
style={[styles.button, styles.buttonOpen]}
onPress={() => setModalVisible(true)}
>
<Text style={styles.textStyle}>Show Modal</Text>
</Pressable>
</View>
);
};
const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5
},
button: {
borderRadius: 20,
padding: 10,
elevation: 2
},
buttonOpen: {
backgroundColor: "#F194FF",
},
buttonClose: {
backgroundColor: "#2196F3",
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
modalText: {
marginBottom: 15,
textAlign: "center"
}
});
export default App;
</code></pre>
<p>Try swiping down, it never seem to trigger "onRequestClose" method.</p>
<p><a href="https://i.stack.imgur.com/Eas3G.gif" rel="nofollow noreferrer">This is what happens currently.</a></p>
<p><a href="https://miro.medium.com/max/592/1*dmhbPxreHtPwQbZJ3XplRA.gif" rel="nofollow noreferrer">This is what I'm looking for.</a></p>
<p>P.S. I have tried <a href="https://gist.github.com/ps73/012b8b97bb7866db4b2b4636a8396d98" rel="nofollow noreferrer">some patches</a> but they don't seem to work either.</p>
<p>Is it normal? How would you fix it? Thanks!</p>
| 3 | 1,457 |
Strange output while iterating in Python using While loop and If statement
|
<p>I am trying to iterate over the range (1,10).</p>
<p>For each number in the range, I want to apply the below logic.</p>
<ol>
<li><p>If the number is even at the start or turns even at a subsequent stage, I would like to collect the quotient of the number devided by 2 in a list.</p>
</li>
<li><p>If the number is odd at the start or turns odd at a subsequent stage, I would like to collect - triple the number plus one (3*X+1) - in the same list.</p>
</li>
<li><p>I want to repeat steps 1 & 2 on the newly collcted number, as the case may be, until the quotient is 1.</p>
</li>
<li><p>The list shall start with the original number and end with the last quotient, which is 1.</p>
</li>
</ol>
<p>I have written the below code and it is working fine for all initial values, excepting when the initial value is 3 or 6 (ie., when i is 3 or 6). The output for 3 should have been [3,10,5,16,8,4,2,1] and for 6 shall be [6,3,10,5,16,8,4,2,1]. Instead, I am getting just [3,1] and [6,3,1] respectively. Why is this? Any feedback will be appreciated.</p>
<pre><code>d ={}
for i in range(1,10):
x=i
l=[x]
while (x // 2) != 1:
if (x%2) == 0:
l.append(x//2)
x=x//2
else:
l.append(x*3+1)
x=x*3+1
l.append(x//2)
d[i] = l
pd.DataFrame(dict([(k,pd.Series(v)) for k,v in d.items()]))
1 2 3 4 5 6 7 8 9
0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9
1 4.0 1.0 1.0 2.0 16.0 3.0 22.0 4.0 28
2 2.0 NaN NaN 1.0 8.0 1.0 11.0 2.0 14
3 1.0 NaN NaN NaN 4.0 NaN 34.0 1.0 7
4 NaN NaN NaN NaN 2.0 NaN 17.0 NaN 22
5 NaN NaN NaN NaN 1.0 NaN 52.0 NaN 11
6 NaN NaN NaN NaN NaN NaN 26.0 NaN 34
7 NaN NaN NaN NaN NaN NaN 13.0 NaN 17
8 NaN NaN NaN NaN NaN NaN 40.0 NaN 52
9 NaN NaN NaN NaN NaN NaN 20.0 NaN 26
10 NaN NaN NaN NaN NaN NaN 10.0 NaN 13
11 NaN NaN NaN NaN NaN NaN 5.0 NaN 40
12 NaN NaN NaN NaN NaN NaN 16.0 NaN 20
13 NaN NaN NaN NaN NaN NaN 8.0 NaN 10
14 NaN NaN NaN NaN NaN NaN 4.0 NaN 5
15 NaN NaN NaN NaN NaN NaN 2.0 NaN 16
16 NaN NaN NaN NaN NaN NaN 1.0 NaN 8
17 NaN NaN NaN NaN NaN NaN NaN NaN 4
18 NaN NaN NaN NaN NaN NaN NaN NaN 2
19 NaN NaN NaN NaN NaN NaN NaN NaN 1
</code></pre>
| 3 | 1,707 |
Not able to query dynamoDb data using GeoDataManager in Node
|
<p>I am trying to follow the very basic tutorial of Geo Library for Amazon DynamoDB given here <a href="https://www.npmjs.com/package/dynamodb-geo" rel="nofollow noreferrer">https://www.npmjs.com/package/dynamodb-geo</a>.
Even after following the steps mentioned in link, my myGeoTableManager.queryRadius() call is not giving me any result.
Below are the steps that I follow.</p>
<p>I created the dynamoDB table with below script</p>
<pre><code>require("dotenv").config();
var AWS= require('aws-sdk');
AWS.config.update({accessKeyId: process.env.accessKeyId, secretAccessKey: process.env.secretAccessKey, region: "us-east-1"});
const ddb = new AWS.DynamoDB();
const ddbGeo = require('dynamodb-geo');
const config = new ddbGeo.GeoDataManagerConfiguration(ddb, 'locationData');
config.hashKeyLength = 5;
const createTableInput = ddbGeo.GeoTableUtil.getCreateTableRequest(config);
// Tweak the schema as desired
createTableInput.ProvisionedThroughput.ReadCapacityUnits = 5;
console.log('Creating table with schema:');
console.dir(createTableInput, { depth: null });
// Create the table
ddb.createTable(createTableInput).promise()
// Wait for it to become ready
.then(function () { return ddb.waitFor('tableExists', { TableName: 'locationData' }).promise() })
.then(function () { console.log('Table created and ready!') });
</code></pre>
<p>Then I insert and query data in dynamoDB using below script.</p>
<pre><code>require("dotenv").config();
var AWS= require('aws-sdk');
AWS.config.update({accessKeyId: process.env.accessKeyId, secretAccessKey: process.env.secretAccessKey, region: "us-east-1"});
const ddb = new AWS.DynamoDB();
const ddbGeo = require('dynamodb-geo');
const config = new ddbGeo.GeoDataManagerConfiguration(ddb, 'locationData');
config.hashKeyLength = 5;
const myGeoTableManager = new ddbGeo.GeoDataManager(config);
myGeoTableManager.putPoint({
RangeKeyValue: { S: '1234' },
GeoPoint: {
latitude: 28.749472,
longitude: 77.056534
},
PutItemInput: {
Item: {
country: { S: 'country1' },
capital: { S: 'capital1' }
},
}
}).promise()
.then(function() { console.log('Insert Done!') });
myGeoTableManager.putPoint({
RangeKeyValue: { S: '5678' },
GeoPoint: {
latitude: 28.749999,
longitude: 77.056999
},
PutItemInput: {
Item: {
country: { S: 'country2' },
capital: { S: 'capital2' }
},
}
}).promise()
.then(function() { console.log('Insert Done!') });
myGeoTableManager.queryRadius({
RadiusInMeter: 100000,
CenterPoint: {
latitude: 28.749888,
longitude: 77.056888
}
}).then((locations) => {
console.log(locations);
});
</code></pre>
<p>Even with exactly same latitude and longitude, myGeoTableManager.queryRadius() is giving me empty response.</p>
| 3 | 1,143 |
Passing data between angular controllers using service
|
<p>I am having trouble passing data between controllers using a service. What i want to happen is when send data is clicked the data inputted into the text field should be populated in the Results controller. However nothing shows</p>
<p>Home.html:</p>
<pre><code> <html>
<body>
<ion-header-bar class="bar-dark">
<h1 class="title"></h1>
</ion-header-bar>
<ion-view view-title="Home">
<ion-content ng-controller="StockUpdateCtrl">
<div class="list">
<ion-refresher pulling-text="Pull to Refresh" on-refresh="doRefresh()"></ion-refresher>
<div>{{text}}</div>
<input type='text' ng-model='text' />
<button type='button' ng-click='send()'>Send Data</button>
<div ng-controller='ResultsController'>
<div>
<h4>Ctrl2</h4>
<div>{{text}}</div>
</div>
</div>
</ion-content>
</ion-view>
</body>
</html>
</code></pre>
<p>HomeController.js:</p>
<pre><code>var app = angular.module('starter', ['ionic'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
/*
* Data Service
* Service used to pass data between controllers
*/
app.factory('dataShare', function(){
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.data;
};
return service;
});
/*
* Stock Update Controller
* Gets user input and then performs calculations to prepare to be displayed
*
*/
app.controller("StockUpdateCtrl", function ($scope, $http, dataShare) {
$scope.text = 'Hey';
$scope.send = function(){
dataShare.sendData($scope.text);
};
});
</code></pre>
<p>ResultsController.js:</p>
<pre><code> * Resultse Controller
* Displays the results
*
*/
app.controller("ResultsController",function ($scope, dataShare) {
$scope.text = '';
$scope.$on('data_shared',function(){
var text = dataShare.getData();
$scope.text = text;
});
});
</code></pre>
| 3 | 1,190 |
PHP Functions - Comparison error
|
<p>I am getting an error trying to run the following code. Can you help me fixing this? </p>
<pre><code> if((invite_limit($id_usr) >= 2)||(pending_users() == ' ')){
echo '<div class="new_ativa_off">';
echo '<div class="new_qtd">0</div>';
echo '<div class="new_txt">Pending</div>';
echo '</div>';
}else{
echo '<div class="new_ativa" id="nu_open">';
echo '<div class="new_qtd">';
if($inactive_users >= 2){echo '2';}else{echo $inactive_users;}
echo '</div>';
echo '<div class="new_txt">Pending</div>';
echo '</div>';
}
</code></pre>
<p>
**This is the pending users function >>>>>>>>>>>>>>>>>>>>>>>>>>>
This is the pending users function >>>>>>>>>>>>>>>>>>>>>>>>>>>**
</p>
<pre><code> function pending_users(){
include('_config.php');
if ($stmt = $conex->prepare("SELECT * FROM $tb_user WHERE $user_adate !=? AND $user_ref =?")) {
$stmt->bind_param("ss", $nada, $nada);
$nada = '';
$stmt->execute();
$stmt->store_result();
$inactive_users = $stmt->num_rows;
$stmt->close();
echo $inactive_users;
$conex->close();
}
}
</code></pre>
<p>
**invite limit function >>>>>>>>>>>>>>>>>>>>>>>>>>>
invite limit function >>>>>>>>>>>>>>>>>>>>>>>>>>>**
</p>
<pre><code> function invite_limit($id_usr){
include('_config.php');
if ($stmt = $conex->prepare("SELECT * FROM $tb_user WHERE $user_ref =? AND DATE($user_refdate) > DATE_SUB(NOW(), INTERVAL 24 HOUR) AND DATE($user_refdate) <= NOW()")) {
$stmt->bind_param("s", $id_usr);
$stmt->execute();
$stmt->store_result();
$activations = $stmt->num_rows;
$stmt->close();
echo $activations;
}
$conex->close();
}
</code></pre>
| 3 | 1,240 |
not able to send form data through ajax via json object
|
<p>I am trying to send json data through ajax in jersey api . however i am not able to send the data. Here is my code:</p>
<h3>javascript code</h3>
<pre><code>var jsonObj = createDataObj();
$.ajax({
type : "POST",
url : "/api/orders/addOrder",
data : jsonObj ,
contentType: "application/json",
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
})
.done(function( response ) {
if(response.isSaved){
alert("Your order has been placed successfully & order id is "+response.orderId);
}
else{
alert("Soming went wrong. Please try again.");
}
});
//creating json object
function createDataObj(){
var dataObj = "" + "{" + '"customerId":'+ $('#custId').val()+','+ '"companyName":'+'"'+$("#companyKey").val()+'",'
+ '"street" : '+'"'+$("#streetKey").val()+'",'+'"postalCode" : '+'"'+$("#postalCodeKey").val()+'",'+
'"city":'+'"'+$("#cityKey").val()+'",' + '"country":'+'"'+$("#countryKey").val()+'",'
+ '"productId":"'+ $("#product").val())+'",' + '"quantity":'+ $('#quantity').val() + "} ";
return dataObj;
}
</code></pre>
<h3>and jersey class</h3>
<pre><code>package elisa.devtest.endtoend;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import elisa.devtest.endtoend.dao.OrderDao;
import elisa.devtest.endtoend.model.Customer;
import elisa.devtest.endtoend.model.DataDto;
import elisa.devtest.endtoend.model.Order;
@Path("/orders")
public class OrderResource {
private static final Logger log = Logger.getLogger(OrderResource.class
.getName());
@GET
@Produces(MediaType.APPLICATION_JSON)
public Collection<Order> getOrders() {
return new OrderDao().findOrders();
}
/**
* @param name
* @param company
* @param Country
* @param cityKey
* @param postalCodeKey
* @param Street
* @param product
* @param quant
* @return Method addByPassingValue method used to fetch the data from form
* and sent it DAO for insertion in database. This Method is called
* when submit button is clicked on form
*/
@POST
@Path("/addOrder")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String addByPassingValue(DataDto obj) {
StringBuilder response = new StringBuilder();
try{
log.log(Level.SEVERE, "OrderResource", "Processing records");
response.append("success");
Customer cust = new Customer(2, "test", "test",
"test", "test", "test");
// Customer cust = new Customer(Integer.parseInt(custId), company, Street,
// postalCodeKey, cityKey, Country);
// new OrderService().addOrder(obj.getCustomer(), "f3DFS234#212dfS", 3);
return response.toString();
} catch(IllegalArgumentException e){
e.printStackTrace();
return response.append("{\"isSaved\":").append(false).append("}").toString();
}
catch(Exception e){
e.printStackTrace();
return response.append("{\"isSaved\":").append(false).append("}").toString();
}
}
}
where DataDto has setter and getter method
problem is I am not able to call method through ajax call
please help
thanks in advance
</code></pre>
| 3 | 1,756 |
JavaFX functions do not work even though there are no errors
|
<p>I'm following a tutorial loosely by thenewboston and I'm running into a bit of a roadblock. To my understanding the ID in the .JFXM file is equivalent to a variable in the controller class. The onAction command is a reference to a function in the controller class.</p>
<p>The tutorial link: <a href="https://www.youtube.com/watch?v=LMdjhuYSrqg" rel="nofollow noreferrer">https://www.youtube.com/watch?v=LMdjhuYSrqg</a></p>
<p>What I don't understand:</p>
<ol>
<li><p>Why I need to initialize the variable <code>public Button loginBtn = new Button();</code> when in the tutorial he does not. </p></li>
<li><p>Why does setText do nothing <code>loginBtn.setText("aahh!");</code></p></li>
<li><p>If I wanted to get text from a field, I would use <code>System.out.println(FXuserLoginName.getText());</code> Which results in an error if the variable is not initialized. If It IS initialized, nothing happens. </p></li>
</ol>
<p>Any help is appreciated. Below is the code:</p>
<pre><code>package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
public class Jfx extends Application {
public Button loginBtn = new Button();
TextField FXuserLoginName;
PasswordField userLoginPassword;
@Override
public void start(Stage primaryStage) throws Exception {
try {
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
Scene scene = new Scene(root,208,208);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle("Odin");
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public void ActionloginButton() {//logs into database, loginButton is connected to Login.fxml there #loginButton is present
loginBtn.setText("aahh!");
System.out.println("Login button..");
//System.out.println(FXuserLoginName.getText());
System.out.println("Got text");
}
}
</code></pre>
<p>And here is my Controller</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="150.0" prefWidth="200.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Jfx">
<children>
<TextField id="FXuserLoginName" layoutX="29.0" layoutY="37.0" promptText="Username" />
<PasswordField id="userLoginPassword" layoutX="29.0" layoutY="76.0" maxHeight="-Infinity" maxWidth="-Infinity" promptText="Password" />
<Button id="loginBtn" layoutX="81.0" layoutY="113.0" mnemonicParsing="false" text="Login" onAction="#ActionloginButton"/>
</children>
</AnchorPane>
</code></pre>
| 3 | 1,247 |
Access "too few parameters" or crash but only before compact and repair
|
<p>Bit of an odd one here, essentially I have a VBA function in Microsoft Access that takes two arguments provided and cuts the data from the existing table to a temp table, and then compares this to the latest data from an external an SQL database and then reappends the updated information.</p>
<p>This has worked fine for years, and has never been touched, until recently, everytime I run the function I get an error:</p>
<blockquote>
<p>Run-time error '-2147217904(8004e10)':
Too few parameters. Expected 2.</p>
</blockquote>
<p>However, if I manually compact and repair, or recompile the database, this error goes away and the function completes as normal. But only for that session, currently the staff that use this function have to compact and repair everytime they open the Acces front end to make the function complete. Compact and repair on close does not work.</p>
<p>The code is below, but again, it has worked as-is for year with no changes and works after a C&R.</p>
<pre><code>Function AccCompleteOrder(LabID As String, OrderID As String) As Boolean
Dim cmd As New ADODB.Command
Dim conn As New ADODB.Connection
Dim rstPackageCount As ADODB.Recordset
Dim rstTmpData As ADODB.Recordset
Dim rstRealData As New ADODB.Recordset
Dim i As Integer
Dim params() As Variant
'set up cmd and query parameters
params = Array(LabID, OrderID)
Set conn = CurrentProject.Connection
cmd.ActiveConnection = conn
'check that packages have been added to the order in genophyle
cmd.CommandText = "qryAccCheckPackagesAdded"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
Set rstPackageCount = cmd.Execute(, params)
If (rstPackageCount("packageCount") = 0) Then
AccCompleteOrder = False
Exit Function
End If
'Move dummy records to Temp table
If TableExists("tmpTblAccDeletion") Then
DoCmd.DeleteObject acTable, "tmpTblAccDeletion"
End If
cmd.CommandText = "qryAccMoveToTemp"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
cmd.Execute , params
'delete old lines from table
cmd.CommandText = "qryAccDeleteFromWIL"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
cmd.Execute , params
'Append real data from Genophyle orders
cmd.CommandText = "qryAccAppendfrmGenophyle"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
cmd.Execute , params
'Get tempData recordset
cmd.CommandText = "qryAccSelectTmpData"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
Set rstTmpData = cmd.Execute
'Get real Data (from WIL) dataset
cmd.CommandText = "qryAccSelectRealData"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
cmd.Parameters.Append cmd.CreateParameter("LabID", adChar, , 10, LabID)
cmd.Parameters.Append cmd.CreateParameter("OrderID", adBigInt, , 10, OrderID)
rstRealData.Open cmd, , adOpenDynamic, adLockOptimistic
Do While Not rstRealData.EOF
rstRealData("Country") = rstTmpData("Country")
Do While Not rstTmpData.EOF
If (rstRealData.Fields("Platform") = rstTmpData.Fields("Platform")) Then
For i = 0 To rstRealData.Fields.Count - 1
If (IsNull(rstRealData.Fields(i)) Or rstRealData.Fields(i) = 0) Then
rstRealData.Fields(i) = rstTmpData.Fields(i)
End If
Next
End If
rstTmpData.MoveNext
Loop
rstTmpData.MoveFirst
rstRealData.Update
rstRealData.MoveNext
Loop
rstRealData.Close
'update the accessioning check table
cmd.CommandText = "qryAccUpdateAccessioningCheckOrderComplete"
cmd.Parameters.Refresh
cmd.Parameters.Append cmd.CreateParameter("LabID", adChar, , 10, LabID)
cmd.Parameters.Append cmd.CreateParameter("OrderID", adBigInt, , 10, OrderID)
cmd.Parameters.Append cmd.CreateParameter("ComDate", adChar, , 50, Format(Now(), "dd/mm/yyyy hh:MM:ss"))
cmd.Parameters.Append cmd.CreateParameter("ComCheck", adBoolean, , , True)
cmd.Execute
AccCompleteOrder = True
End Function
</code></pre>
<p>The debugger indicates the error is when it reaches the line</p>
<pre><code>rstRealData.Open cmd, , adOpenDynamic, adLockOptimistic
</code></pre>
<p>This has me stumped.</p>
| 3 | 1,577 |
Scroll button behavior
|
<p>The button scrolls past the content I want to be shown.
I want the "About Us" section to be showed to the display of user (100vh), but it just scrolls past that.</p>
<p>Here's the code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function smoothScroll(target, duration) {
var target = document.querySelector(target);
var targetPosition = target.getBoundingClientRect().top;
var startPosition = window.pageYOffset;
var distance = targetPosition - startPosition;
var startTime = null;
function animation(currentTime) {
if (startTime === null) startTime = currentTime;
var timeElapsed = currentTime - startTime;
var run = ease(timeElapsed, startPosition, distance, duration);
window.scrollTo(0, run);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
function ease(t, b, c, d) {
t /= d / 2;
if (t < 1) return (c / 2) * t * t + b;
t--;
return (-c / 2) * (t * (t - 2) - 1) + b;
}
requestAnimationFrame(animation);
}
var btn = document.querySelector(".btn");
btn.addEventListener("click", function () {
smoothScroll(".text-slider", 600);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hero {
display: flex;
width: 90%;
margin: auto;
height: 100vh;
min-height: 100vh;
align-items: center;
text-align: center;
background-image: url(/img/pexels-tranmautritam-326501.jpg);
background-size: cover;
background-attachment: fixed;
justify-content: center;
}
.introduction {
flex: 1;
height: 30%;
}
.welcometxt h1 {
font-size: 17px;
color: white;
font-weight: 100;
letter-spacing: 12px;
}
.intro-text h1 {
font-size: 44px;
font-weight: 700;
color: white;
/* background: linear-gradient(to left, rgb(184, 184, 184), #ffffff); */
/* -webkit-background-clip: text;
-webkit-text-fill-color: transparent; */
}
.intro-text p {
font-size: 18px;
margin-top: 5px;
color: white;
}
.cta {
padding: 50px 0px 0px 0px;
}
.btn {
background-color: white;
width: 150px;
height: 50px;
cursor: pointer;
font-size: 16px;
font-weight: 400;
letter-spacing: 1px;
color: black;
border: none;
border-radius: 40px;
transition: all 0.6s ease;
box-shadow: 5px 7px 18px rgb(0, 0, 0, 0.4);
}
.btn:hover {
background-color: black;
color: white;
box-shadow: 5px 7px 18px rgb(0, 0, 0, 0.8);
}
.text-slider {
width: 70%;
height: 90vh;
margin: 100px auto;
position: relative;
text-align: center;
align-items: center;
}
.carousel {
height: 70vh;
overflow: hidden;
}
.slider {
height: 100%;
display: flex;
width: 400%;
transition: all 0.3s;
}
.slider p {
width: 70%;
font-size: 17px;
}
.slider section {
flex-basis: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.controls .arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
.controls .arrow i {
font-size: 60px;
}
.arrow.left {
left: 10px;
}
.arrow.right {
right: 10px;
}
.nextpage-arrow i{
font-size: 60px;
cursor: pointer;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="hero">
<div class="introduction">
<div class="welcometxt">
<h1>
WELLCOME
</h1>
</div>
<div class="intro-text">
<h1>Optimal Solution for Your Product</h1>
<p>
Ensuring optimal solution for your
Quality Management.
</p>
</div>
<div class="cta">
<button class="btn">Click for more</button>
</div>
</div>
</section>
<div class="text-slider" id="text-slider">
<h1>About Us</h1>
<div class="carousel">
<div class="slider">
<section>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Aliquam, fugiat.</p>
</section>
<section>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Repellat, commodi?</p>
</section>
<section>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eligendi, velit.</p>
</section>
<section>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quaerat, aperiam.</p>
</section>
</div>
<div class="controls">
<span class="arrow left">
<i class="material-icons">
keyboard_arrow_left
</i>
</span>
<span class="arrow right">
<i class="material-icons">
keyboard_arrow_right
</i>
</span>
</div>
</div>
<div class="nextpage-arrow">
<span class="text-slider-btn">
<i class="material-icons">
keyboard_arrow_down
</i>
</span>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>As shown in the picture, it goes past "About Us" h1.
I want the page to stop at "About Us", and not go past it.
If you need more code, or more explanation please comment and I'll try my best!
Thank you in advance.</p>
<p><a href="https://i.stack.imgur.com/scTq9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/scTq9.png" alt="enter image description here" /></a></p>
<p>UPDATE (GIF):
<a href="https://i.stack.imgur.com/8cRVD.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8cRVD.gif" alt="enter image description here" /></a></p>
| 3 | 3,026 |
Flutter logic issue
|
<p>I'm building this small game , it's similar to Qix game .</p>
<p>I already built the first screens now i need to implement the functionality , the car should be moving using the buttons , and while moving it should draw like a container behind it until it feel all the stadium .</p>
<p>this is where I'm making the car moves :</p>
<pre><code>class _GameScreenState extends State<GameScreen> {
double xPosition = Random().nextInt(230).toDouble();
double yPposition = Random().nextInt(200).toDouble();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bg.png"),
fit: BoxFit.cover,
),
),
child: Column(
children: [
// Game play
Expanded(
flex: 6,
child: Stack(
children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Colors.transparent,
),
Positioned(
bottom: yPposition,
left: xPosition,
child: Image.asset("assets/images/car.png"),
)
],
),
),
// Player inputes
Expanded(
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
RoundIconButton(
onPress: () {
setState(() {
yPposition--;
});
},
icon: Icons.arrow_downward,
),
RoundIconButton(
onPress: () {
setState(() {
yPposition++;
});
},
icon: Icons.arrow_upward,
),
],
),
Row(
children: [
RoundIconButton(
onPress: () {
setState(() {
xPosition--;
});
},
icon: Icons.arrow_back,
),
RoundIconButton(
onPress: () {
setState(() {
xPosition = xPosition + 10;
});
},
icon: Icons.arrow_forward,
),
],
),
],
),
),
),
),
],
),
),
),
);
}
}
</code></pre>
<p>I also need the car keep moving when I press the button , in my case it moves only one time</p>
| 3 | 2,507 |
Button type button posting data is not saving in DB
|
<p>i added on message Box and i am posting that data but not adding in my DB.</p>
<p>when i am trying to click Confirm button it is not saving in data-base how it will save to data-base can you please help me.</p>
<p><a href="https://i.stack.imgur.com/iNBzZ.png" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code>var leaveManagement= {
leaveData: null,
showModal: function(data) {
leaveManagement.leaveData = data;
$('#adminComment').val("");
$('#IsPaidLeave').prop('checked', false);
if ($(data).val() === "Reject") {
$(".form-check").hide();
} else {
var leaveTypeId = $(leaveManagement.leaveData).attr('data-leaveTypeId');
var userId = $(leaveManagement.leaveData).attr('data-employeeId');
if (leaveTypeId !== "" && leaveTypeId !== null && userId !== "" && userId !== null) {
$.ajax({
url: "/PayRoll/Leave/GetEmployeeLeaveTypeCount?employeeId=" +userId+"&leaveTypeId=" +leaveTypeId,
type: 'GET',
async: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#leaveCount').html('<span class="badge badge-outline badge-primary">Remaining Leave : '+data+'</span>');
},
error: function (e) {
}
});
}
$(".form-check").show();
}
$('#showCommentModal').modal('show');
},
changeRequest: function () {
if (leaveManagement.leaveData !== null) {
debugger;
var leaveId;
if ($(leaveManagement.leaveData).val() === "Approve") {
leaveId = $(leaveManagement.leaveData).attr('data-id');
leaveManagement.processRequest(leaveId, true, false);
} else if ($(leaveManagement.leaveData).val() === "Reject") {
leaveId = $(leaveManagement.leaveData).attr('data-id');
leaveManagement.processRequest(leaveId, false, true);
}
}
},
processRequest: function(leaveId, isApproved, isRejected) {
var comment = $('#adminComment').val();
var isPaidLeave = $('#IsPaidLeave').prop('checked');
$.ajax({
url: "/PayRoll/Leave/RespondToLeaveRequest/?leaveId=" +
leaveId +
"&isApproved=" +
isApproved +
"&IsRejected=" +
isRejected +
"&comment=" +
comment +
"&isPaidLeave=" +
isPaidLeave,
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (!data.success) {
$.notify(data.ResponseText, { position: "top right", className: "success" });
} else {
$.notify('Updated', { position: "top right", className: "success" });
}
$("#OpenLeaveRequestGrid").data('kendoGrid').dataSource.read();
$("#ClosedLeaveRequestGrid").data('kendoGrid').dataSource.read();
$('#adminComment').val("");
$('#IsPaidLeave').prop('checked', false);
$('#IsPaid').prop('checked', false);
},
error: function(data) {
console.log(data);
$.notify('Error', { position: "top right", className: "error" });
}
});
},
</code></pre>
<p>this is the button where if i click this button its should be save my comment data.</p>
<pre><code>div class="modal-footer">
<button type="button" class="btn btn-warning" onclick="leaveManagement.changeRequest(this);" data-dismiss="modal" value="Confirm" id="bntconfirm">Confirm</button>@*<span class="fa fa-check"> Confirm</span>*@
</div>
</code></pre>
<p>this is the box where am writing comment.</p>
| 3 | 2,052 |
What does 'x' do in curve/dnorm, and why does it work in my function?
|
<p>I am making a function <code>Prop.Histogram()</code> that plots data as a histogram showing the proportions with a normal distribution curve added to it. Addition of the curve was difficult for me to achieve, but I succeeded (see code below)!</p>
<p>Note: I personally prefer to work with the pipe-operator <code>%>%</code> from the package magrittr in my codes. Though, as probably not everyone is familiar with this operator and/or this package (or they prefer not to use it), I'll also provide the same code without using magrittr below.</p>
<p><strong>Code using magrittr</strong></p>
<pre><code>Prop.Histogram <- function(data,
xlim_min, xlim_max, x_BreakSize,
ylim_max, y_steps) {
# Load packages
library(magrittr)
# Make histogram of data without y-axis
hist(data, freq = FALSE, ylab = "Proportion",
xlim = c(xlim_min, xlim_max), breaks = seq(from = xlim_min, to = xlim_max, by = x_BreakSize),
ylim = c(0, ylim_max %>% divide_by(., x_BreakSize)), yaxt = "n")
# I divided ylim_max by x_BreakSize, as I want ylim_max to be equal to the max proportion shown on the y_axis (and not to the max density)
# Add y-axis that shows proportion and not density
axis(side = 2,
at = seq(from = 0, to = ylim_max %>% divide_by(., x_BreakSize), by = y_steps %>% divide_by(., x_BreakSize)),
labels = seq(from = 0, to = ylim_max, by = y_steps))
box()
# Add curve to histogram
curve(dnorm(x, mean = mean(data), sd = sd(data)), lwd = 5, add = TRUE, yaxt = "n")
}
</code></pre>
<p><strong>Same code without using magrittr</strong></p>
<pre><code>Prop.Histogram <- function(data,
xlim_min, xlim_max, x_BreakSize,
ylim_max, y_steps) {
# Load packages
library(magrittr)
# Make histogram of data without y-axis
hist(data, freq = FALSE, ylab = "Proportion",
xlim = c(xlim_min, xlim_max), breaks = seq(from = xlim_min, to = xlim_max, by = x_BreakSize),
ylim = c(0, ylim_max/x_BreakSize), yaxt = "n")
# I divided ylim_max by x_BreakSize, as I want ylim_max to be equal to the max proportion shown on the y_axis (and not to the max density)
# Add y-axis that shows proportion and not density
axis(side = 2,
at = seq(from = 0, to = ylim_max/x_BreakSize, by = y_steps/x_BreakSize),
labels = seq(from = 0, to = ylim_max, by = y_steps))
box()
# Add curve to histogram
curve(dnorm(x, mean = mean(data), sd = sd(data)), lwd = 5, add = TRUE, yaxt = "n")
}
</code></pre>
<p>This code does exactly what I want it to do: it plots the proportions and adds a normal distribution curve to the plot. Though, I do have difficulties understanding why addition of the curve actually works.</p>
<p><strong>Main question (1)</strong>: I have to put <code>x</code> as the first argument in <code>dnorm()</code>, and even though I have not defined <code>x</code>, it works! So my first and main question is: what is <code>x</code>, what does it do, and why does it work in my function?</p>
<p><strong>Second question (2)</strong>: My second question is whether it is possible (and, if so, how) to use magrittr pipe-operators (<code>%>%</code>) in the line of code that adds the curve to the plot. (Even if using operators is not the best way to do so in this case, I am still interested in the answer as I am eager to learn!)</p>
<hr />
<p>First of all, for those who want to try out my code: here is some data that is representative of data that I want to plot:</p>
<pre><code>data <- rnorm(724, mean = 84, sd = 33)
Prop.Histogram(data,
xlim_min = -50, xlim_max = 200, x_BreakSize = 10,
ylim_max = 0.15, y_step = 0.05)
</code></pre>
<hr />
<p><strong>Main question (1)</strong>: role of <code>x</code> in <code>dnorm()</code>/<code>curve()</code></p>
<p>I started by using <code>data</code> instead of <code>x</code> as the first argument of <code>dnorm()</code>, but this didn't work as it resulted in the following error message:</p>
<pre><code> Error in curve(dnorm(data, mean = mean(data), sd = sd(data)), lwd = 5, :
'expr' must be a function, or a call or an expression containing 'x'
</code></pre>
<p>But then, when I take <code>dnorm(data, mean = mean(data), sd = sd(data))</code> and run it individually (not as an argument of <code>curve()</code>, it gives me 724 values (of which I don't know what they meaning, but at least it's not an error message). Which is weird, since using <code>data</code> as the first argument when <code>dnorm()</code> is part of <code>curve</code> in my formula results in an error message as we saw previously.</p>
<p>Then, when I change <code>data</code> for <code>x</code> and run <code>dnorm(x, mean = mean(data), sd = sd(data))</code> (again not as an argument of <code>curve()</code>), it gives me another error message:</p>
<pre><code> Error in dnorm(x, mean = mean(data), sd = sd(data)) :
object 'x' not found
</code></pre>
<p>This I can understand, as I've not defined <code>x</code> anywhere in my code. But that rises the question: why do I not get this same error message when I run my (working) function.</p>
<p>In short, I observed that <code>x</code> must be the first argument in <code>dnorm()</code> when <code>dnorm()</code> is used as an argument in <code>curve()</code>, but <code>x</code> cannot be used as the first argument when <code>dnorm()</code> is used individually. Conclusion: I am lost.</p>
<p>Of course, when I am lost in R, I always look at the help page of R. The help page of <code>dnorm()</code> states that <code>x</code> is a vector of quantiles... that's it. I know those words individually, but have no idea what it means in my code (as I've not defined <code>x</code>, so what vector or what quantiles is the R help page talking about?).</p>
<hr />
<p><strong>Second question (2)</strong>: use of magrittr in code</p>
<p>I've tried to write the code <code>curve(dnorm(x, mean = mean(data), sd = sd(data)), lwd = 5, add = TRUE, yaxt = "n")</code> using magrittr, but it does not work. Here are some examples I've tried:</p>
<pre><code>data %>% dnorm(x, mean = mean(.), sd = sd(.)) %>% curve(., lwd = 5, add = TRUE, yaxt = "n")
data %>% dnorm(x, mean = mean(.), sd = sd(.)) %>% curve(lwd = 5, add = TRUE, yaxt = "n")
dnorm(x, mean = mean(data), sd = sd(data)) %>% curve(., lwd = 5, add = TRUE, yaxt = "n")
</code></pre>
<p>They all result in the same error message:</p>
<pre><code> Error in dnorm(x, mean = mean(data), sd = sd(data)) :
object 'x' not found
</code></pre>
<p>I'd like to know if it's possible to use magrittr operators like <code>%>%</code> in this situation (even if it's not the best option).</p>
<hr />
<p>PS. This is my first time posting, so please feel free to give feedback or ask me for more information if needed. Thank you in advance!</p>
| 3 | 2,410 |
Query that returns values where a certain number of rows meet certain condition
|
<p>I'm trying to make a report and i'm having some dificulty designing a query to show the data i need.</p>
<p>I have 2 tables:</p>
<pre><code>+-----------+------------+----------+
+TherapyID + CostumerID + ClinicID +
+-----------+------------+----------+
+ 1 + John + Clinic 1 +
+-----------+------------+----------+
+ 2 + Susan + Clinic 2 +
+-----------+------------+----------+
+ 3 + Mary + Clinic 3 +
+-----------+------------+----------+
+-----------+--------------+-----------+--------+
+TherapyID + TherapyLine + Treatment + Result +
+-----------+--------------+-----------+--------+
+ 1 + 1 + A + Success+
+-----------+--------------+-----------+--------+
+ 1 + 2 + B + Success+
+-----------+--------------+-----------+--------+
+ 1 + 3 + C + Success+
+-----------+--------------+-----------+--------+
+ 2 + 1 + A + Success+
+-----------+--------------+-----------+--------+
+ 2 + 2 + B + Fail +
+-----------+--------------+-----------+--------+
+ 2 + 3 + C + Success+
+-----------+--------------+-----------+--------+
+ 3 + 1 + A + Success+
+-----------+--------------+-----------+--------+
+ 3 + 2 + B + Success+
+-----------+--------------+-----------+--------+
+ 3 + 3 + C + Fail +
+-----------+--------------+-----------+--------+
</code></pre>
<p>I need to make a query that shows me only the customers or therapyid's that have successfully received all treatments <strong>A,B,C</strong></p>
<p>The Query Result should be like this:</p>
<pre><code>+------------+-------------+----------+---------+-----------+---------+
+ TherapyID + TherapyLine + Customer + Clinic + Treatment + Result +
+------------+-------------+----------+---------+-----------+---------+
+ 1 + 1 + John + Clinic 1+ A + Success +
+------------+-------------+----------+---------+-----------+---------+
+ 1 + 2 + John + Clinic 1+ B + Success +
+------------+-------------+----------+---------+-----------+---------+
+ 1 + 3 + John + Clinic 1+ C + Success +
+------------+-------------+----------+---------+-----------+---------+
</code></pre>
<p>This was the only therapyid where all treatments <strong>A,B,C</strong> where <strong>Success</strong>
I really don't have any idea on how to query this, what i have tried up to now
allways returns results from <strong>TherapyID</strong> *<em>2,3</em>* where result was <strong>Success</strong> too.
Thx in advance for the help.</p>
| 3 | 1,052 |
ASP.NET Core & SPA - client files not published when the client is outside of the server folder
|
<p>I have a project which has separate client and server folders and my goal is to include client files during the server's publish process. The folder structure looks like this</p>
<pre><code>|- server
| |- src
| |- MyProject
| |- MyProject.csproj
|- client
|- src
|- dist
</code></pre>
<p>Using the default SPA template which defines <code>SpaRoot</code>, in my case <code>../../../client/src/</code> and the following item group definition</p>
<pre><code><ItemGroup>
<DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
<DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
<ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
<RelativePath>%(DistFiles.Identity)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</ResolvedFileToPublish>
</ItemGroup>
</code></pre>
<p>From the logs I can see this results in copying the files elsewhere <code>Copying file from "C:\MyProject\client\src\dist\img\ic_mail.svg" to "C:\MyProject\server\src\MyProject\obj\Release\client\src\dist\img\ic_mail.svg".</code> while the target path should be <code>C:\MyProject\server\src\MyProject\obj\Release\netcoreapp3.1\PubTmp\Out\appsettings.Development.json</code>. I'm assuming it's caused by the different parent directory because the common parent is 3 levels up the hierarchy and the files are also copied to a directory 3 levels higher than they should be.</p>
<p>I tried prefixing the <code>SpaRoot</code> with <code>$(ProjectDir)</code>, but that did not help. My goal is to copy the files from the <code>dist</code> folder to <code>wwwroot</code> located at the root of the publish folder. I attempted to adjust the <code>ResolvedFileToPublish</code>, but I was not able to retrieve the items' relative path (relative to the <code>dist</code> folder).</p>
<p><strong>Edit:</strong> A csproj based workaround was to copy the files manually to <code>wwwroot</code> in the <code>BeforeTargets</code> hook. Can this produce any unforeseen problems? (mostly the <code><ClientDistFile/></code>)</p>
<pre><code><ItemGroup>
<ClientDistFiles Include="$(SpaRoot)dist/**/*.*"/>
</ItemGroup>
<Target Name="PublishRunWebpack" BeforeTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<Exec WorkingDirectory="$(SpaRoot)" Command="yarn install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="yarn build:$(TargetEnvironment)" />
<Copy
SourceFiles="@(ClientDistFiles)"
DestinationFiles="@(ClientDistFiles->'wwwroot\%(RecursiveDir)%(Filename)%(Extension)')"
/>
</Target>
</code></pre>
| 3 | 1,177 |
Need Help reading JSON JAVA
|
<p>I have a JSON with this code.</p>
<pre><code> [
{
},
{
},
{
},
{
},
{
},
{
},
{
"Producto0":[
{
"crf":"4555424"
},
{
"name":"Limpiador"
},
{
"desc":"Producto de importacion italiano"
},
{
"pve":"8.44"
},
{
"pvp":"14.99"
},
{
"cdp":"10"
},
{
"familia":"Limpieza"
},
{
"existencias":"10"
}
],
"Producto1":[
{
"crf":"5132413"
},
{
"name":"Colador"
},
{
"desc":"Colador de acero"
},
{
"pve":"15"
},
{
"pvp":"18"
},
{
"cdp":"10"
},
{
"familia":"Cocina"
},
{
"existencias":"100"
}
]
},
{
},
{
"Proveedor0":[
{
"crf":"10"
},
{
"razonsocial":"pene"
},
{
"cif":"10"
},
{
"num":"10"
},
{
"correo":"10"
},
{
"direccion":"10"
},
{
"metodopago":"1"
},
{
"observaciones":"10"
}
],
"Proveedor1":[
{
"crf":"5421452"
},
{
"razonsocial":"Falete"
},
{
"cif":"45411"
},
{
"num":"42314"
},
{
"correo":"falete@gmail.com"
},
{
"direccion":"tu casa"
},
{
"metodopago":"T"
},
{
"observaciones":"Es muy pesado"
}
]
}
]
</code></pre>
<p>I tried many ways to read this JSON but I cant achieve it. Heres the only part of my code that works.</p>
<pre><code> import org.json.simple.JSONArray;
import org.json.simple.parser.*;
import org.json.*;
import java.io.FileReader;
import java.io.IOException;
public class parse {
routes router = new routes();
String ruta = router.getruta();
public parse() {
// TODO Auto-generated constructor stub
}
public void parseproductos() {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("ruta"));
for (Object o : a)
{
}
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</code></pre>
<p>I try to read an JSON that preoviously generated with another class from a database. At the moment that I try to read for example only the "ProductoXXX" I dont get them or get everythink. Somebody could help me reading the JSON only the "ProductoXX"?</p>
<p>UPDATE, someone asked my JSON codifier to help me simplify it.</p>
<p>import java.io.FileWriter;
import java.io.IOException;</p>
<p>import org.json.simple.JSONArray;
import org.json.simple.JSONObject;</p>
<p>public class getdata extends dbconnect{</p>
<pre><code>public void getData() throws IOException {
int i = 0;
JSONArray listt = new JSONArray();
JSONObject jobj = new JSONObject();
JSONObject jobjt1 = new JSONObject();
JSONObject jobjt2 = new JSONObject();
JSONObject jobjt3 = new JSONObject();
JSONObject jobjt4 = new JSONObject();
JSONObject jobjt5 = new JSONObject();
JSONObject jobjt6 = new JSONObject();
JSONObject jobjt7 = new JSONObject();
JSONObject jobjt8 = new JSONObject();
JSONObject jobjt9 = new JSONObject();
try {
//Albaran
String query1 = "select * from Albaran";
rs = st.executeQuery(query1);
i=0;
while(rs.next()) {
JSONArray list1 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String a1= rs.getString("CodAlbaran");
String a2= rs.getString("CodRefCli");
String a3= rs.getString("CodRefPro");
String a4= rs.getString("CIFPropio");
String a5= rs.getString("Dir.Archivo");
jobja.put("codalbaran", a1);
jobjb.put("codRefCli", a2);
jobjc.put("codrefpro",a3 );
jobjd.put("cifpropio", a4);
jobje.put("directorio", a5);
list1.add(jobja);
list1.add(jobjb);
list1.add(jobjc);
list1.add(jobjd);
list1.add(jobje);
jobjt1.put("Albaran"+i++, list1);
}
listt.add(jobjt1);
//Clientes
String query2 = "select * from Clientes";
rs = st.executeQuery(query2);
i=0;
while(rs.next()) {
JSONArray list2 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String b1 = rs.getString("CodRefCli");
String b2 = rs.getString("RazonSocial");
String b3 = rs.getString("CIF");
String b4 = rs.getString("Num");
String b5 = rs.getString("Correo");
String b6 = rs.getString("Direccion");
String b7 = rs.getString("MetodoPago");
String b8 = rs.getString("Observaciones");
jobja.put("codrefcli", b1);
jobjb.put("razonsocial", b2);
jobjc.put("cif", b3);
jobjd.put("num", b4);
jobje.put("correo", b5);
jobjf.put("direccion", b6);
jobjg.put("metodopago", b7);
jobjh.put("observaciones", b8);
list2.add(jobja);
list2.add(jobjb);
list2.add(jobjc);
list2.add(jobjd);
list2.add(jobje);
list2.add(jobjf);
list2.add(jobjg);
list2.add(jobjh);
jobjt2.put("Cliente"+i++, list2);
}
listt.add(jobjt2);
//Empleados
String query3 = "select * from Empleados";
rs = st.executeQuery(query3);
i=0;
while(rs.next()) {
JSONArray list3 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String c1 = rs.getString("Cod.Empleado");
String c2 = rs.getString("Nombre");
String c3 = rs.getString("Apellidos");
String c4 = rs.getString("DNI");
String c5 = rs.getString("Direccion");
String c6 = rs.getString("FechaAlta");
String c7 = rs.getString("CopiaContrato");
String c8 = rs.getString("NCuenta");
jobja.put("codempleado", c1);
jobjb.put("nombre", c2);
jobjc.put("apellidos", c3);
jobjd.put("dni", c4);
jobje.put("direccion", c5);
jobjf.put("fechaalta", c6);
jobjg.put("copiacontrato", c7);
jobjh.put("numcuenta", c8);
list3.add(jobja);
list3.add(jobjb);
list3.add(jobjc);
list3.add(jobjd);
list3.add(jobje);
list3.add(jobjf);
list3.add(jobjg);
list3.add(jobjh);
jobjt3.put("Empleado"+i++, list3);
}
listt.add(jobjt3);
//Existencias
String query4 = "select * from Existencias";
rs = st.executeQuery(query4);
i=0;
while(rs.next()) {
JSONArray list4 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String d1 = rs.getString("Cod.RefExistencia");
String d2 = rs.getString("Cod.RefPro");
String d3 = rs.getString("Cantidad");
String d4 = rs.getString("Sitio");
String d5 = rs.getString("Proposito");
jobja.put("codrefexistencia", d1);
jobjb.put("codrefproducto", d2);
jobjc.put("cantidad", d3);
jobjd.put("sitio", d4);
jobje.put("proposito", d5);
list4.add(jobja);
list4.add(jobjb);
list4.add(jobjc);
list4.add(jobjd);
list4.add(jobje);
jobjt4.put("Existencia"+i++, list4);
}
listt.add(jobjt4);
//PedidosClientes
String query5 = "select * from PedidosC";
rs = st.executeQuery(query5);
i=0;
while(rs.next()) {
JSONArray list5 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String e1= rs.getString("NumPed");
String e2= rs.getString("FechaPedido");
String e3= rs.getString("FormadePago");
String e4 = rs.getString("EnviadoA");
String e5 = rs.getString("CodCliente");
String e6 = rs.getString("CPP");
jobja.put("numped", e1);
jobjb.put("fechapedido", e2);
jobjc.put("formapago", e3);
jobjd.put("enviadoa", e4);
jobje.put("codcliente", e5);
jobjf.put("cpp", e6);
list5.add(jobja);
list5.add(jobjb);
list5.add(jobjc);
list5.add(jobjd);
list5.add(jobje);
list5.add(jobjf);
jobjt5.put("PedidoCliente"+i++, list5);
}
listt.add(jobjt5);
//PedidosProveedores
String query6 = "select * from PedidosC";
rs = st.executeQuery(query6);
i=0;
while(rs.next()) {
JSONArray list6 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String f1= rs.getString("NumPed");
String f2= rs.getString("FechaPedido");
String f3 = rs.getString("FormadePago");
String f4 = rs.getString("EnviadoA");
String f5 = rs.getString("Cod.Prov");
String f6 = rs.getString("CPP");
jobja.put("numped", f1);
jobjb.put("fechapedido", f2);
jobjc.put("formapago", f3);
jobjd.put("enviadoa", f4);
jobje.put("codcliente", f5);
jobjf.put("cpp", f6);
list6.add(jobja);
list6.add(jobjb);
list6.add(jobjc);
list6.add(jobjd);
list6.add(jobje);
list6.add(jobjf);
jobjt6.put("PedidoProveedor"+i++, list6);
}
listt.add(jobjt6);
//Productos
String query7 = "select * from Productos";
rs = st.executeQuery(query7);
i=0;
while(rs.next()) {
JSONArray list7 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String g1= rs.getString("Cod.RefPro");
String g2= rs.getString("Nombre");
String g3 = rs.getString("Descripcion");
String g4 = rs.getString("PrecioNeto");
String g5 = rs.getString("pvp");
String g6 = rs.getString("CodRefProv");
String g7 = rs.getString("Familia");
String g8 = rs.getString("Existencias");
jobja.put("crf", g1);
jobjb.put("name", g2);
jobjc.put("desc", g3);
jobjd.put("pve", g4);
jobje.put("pvp", g5);
jobjf.put("cdp", g6);
jobjg.put("familia", g7);
jobjh.put("existencias", g8);
list7.add(jobja);
list7.add(jobjb);
list7.add(jobjc);
list7.add(jobjd);
list7.add(jobje);
list7.add(jobjf);
list7.add(jobjg);
list7.add(jobjh);
jobjt7.put("Producto"+i++, list7);
}
listt.add(jobjt7);
//PropiaEmpresa
String query8 = "select * from PropiaEmpresa";
rs = st.executeQuery(query8);
i=0;
while(rs.next()) {
JSONArray list8 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String p1= rs.getString("CIF");
String p2= rs.getString("RazonSocial");
String p3 = rs.getString("Telefono");
String p4 = rs.getString("Correo");
String p5 = rs.getString("Direccion");
String p6 = rs.getString("NCuenta");
jobja.put("cif", p1);
jobjb.put("razonsocial", p2);
jobjc.put("telef", p3);
jobjd.put("correo", p4);
jobje.put("direccion", p5);
jobjf.put("ncuenta", p6);
list8.add(jobja);
list8.add(jobjb);
list8.add(jobjc);
list8.add(jobjd);
list8.add(jobje);
list8.add(jobjf);
jobjt8.put("PropiaEmpresa", list8);
}
listt.add(jobjt8);
//Proveedor
String query9 = "select * from Proveedor";
rs = st.executeQuery(query9);
i=0;
while(rs.next()) {
JSONArray list9 = new JSONArray();
JSONObject jobja = new JSONObject();
JSONObject jobjb = new JSONObject();
JSONObject jobjc = new JSONObject();
JSONObject jobjd = new JSONObject();
JSONObject jobje = new JSONObject();
JSONObject jobjf = new JSONObject();
JSONObject jobjg = new JSONObject();
JSONObject jobjh = new JSONObject();
String h1= rs.getString("Cod.Referencia");
String h2= rs.getString("RazonSocial");
String h3 = rs.getString("CIF");
String h4 = rs.getString("Numero");
String h5 = rs.getString("Correo");
String h6 = rs.getString("Direccion");
String h7 = rs.getString("MetodoPago");
String h8 = rs.getString("Observaciones");
jobja.put("crf", h1);
jobjb.put("razonsocial", h2);
jobjc.put("cif", h3);
jobjd.put("num", h4);
jobje.put("correo", h5);
jobjf.put("direccion", h6);
jobjg.put("metodopago", h7);
jobjh.put("observaciones", h8);
list9.add(jobja);
list9.add(jobjb);
list9.add(jobjc);
list9.add(jobjd);
list9.add(jobje);
list9.add(jobjf);
list9.add(jobjg);
list9.add(jobjh);
jobjt9.put("Proveedor"+i++, list9);
}
listt.add(jobjt9);
// try-with-resources statement based on post comment below :)
routes router = new routes();
String ruta = router.getruta();
try (FileWriter file = new FileWriter(ruta+"data.json")) {
file.write(listt.toJSONString());
file.flush();
}
}catch(Exception ex) {
System.out.println("Error: "+ex);
}
}
</code></pre>
<p>}</p>
<p>Sorry for the raw. Posting from the phone, cant access internet from computer.</p>
| 3 | 9,784 |
Incorrect row numbering sequence
|
<p>I have two tables (questions and answers) with a row number for questions and another for answers. The row number for questions increments when the question changes. The row number for answers increments each answer and resets to 1 for each new question. Both row numbering increments as intended, but the sort order is wrong. Also, I don't want the query outputs the variable that checks if the current record's question matches the last records question.</p>
<p>I believe the problem is the record sorting is performed last, when it should be the variables' assignment that happens last. I've tried to adapt the solution at <a href="https://stackoverflow.com/questions/19721651/mysql-get-row-position-with-order-by-incorrectly-numbered">MySQL get row position with ORDER BY incorrectly numbered</a> but I keep getting errors. I don't know how to 'turn off' the @currQ being displayed.</p>
<p>Table questions has (question_id,question,display_order)
Table answrs has (answer_id, question_id_fk, answer, display_order)</p>
<pre><code>SET @q_row=0,@a_row=0,@currQ='';
SELECT
@q_row:=CASE WHEN q.question=@currQ THEN @q_row ELSE @q_row+1 END AS
'Question No.',
q.question,
@a_row:=CASE WHEN q.question=@currQ THEN @a_row+1 ELSE 1 END AS
'Answer
No.',
a.answer, @currQ:=q.question
FROM
questions q
INNER JOIN
answers a ON q.question_id=a.question_id_fk
ORDER BY
q.question,a.answer ASC;
</code></pre>
<p>The dynamic numbering works, but the sequence is in the wrong order.. </p>
<pre><code>Question No. question Answer No. answer @currQ:=q.question
4 Favourite excercise 3 Archery Favourite excercise
4 Favourite excercise 1 Running Favourite excercise
4 Favourite excercise 2 Sailing Favourite excercise
2 Favourite food 3 French Favourite food
2 Favourite food 2 South... Favourite food
2 Favourite food 1 Indian Favourite food
2 Favourite food 4 Vietnam..Favourite food
1 Favourite band 2 Deep P.. Favourite band
1 Favourite band 1 Jimi H.. Favourite band
1 Favourite band 3 Eagles Favourite band
1 Favourite pet 1 Dog Favourite pet
</code></pre>
<p>This is how I'd like it to look (using different data)</p>
<pre><code>QRow Question Q.ID Q.disp_ord ARow Answer A.ID A.disp_ord
1 Favourite Pet 19 6 1 Dog 17 4
2 Favourite Band 8 9 1 The Who 3 1
2 Favourite Band 8 9 2 Dire Straits 69 3
2 Favourite Band 8 9 3 The Doors 103 15
3 Best Food 26 15 1 Thai 76 1
3 Best Food 26 15 2 Japanese 233 2
</code></pre>
<p>Ordering from Q.disp_ord, A.disp_ord. The results show that both disp_ord must ascend, but note they may not be sequential (as other questions and answers within the sequence may be filtered out). </p>
| 3 | 1,453 |
def function not running correctly
|
<p>Please don't be too mean I have only started to use Python and wanted to try and complete a calculator that can use brackets and BIDMAS. I am currently at the stage of starting the part about brackets but when I run my program it will not run my def functions properly.</p>
<pre><code>import time
import os
import random
import sys
print("=======================")
print("Use ^ for the power of")
print("Use + for adding")
print("Use - for subtracting")
print("Use * for multiplying")
print("Use / for dividing")
print("Use % for a percentage")
print("DON'T USE SPACES!")
print("=======================\n\n")
uilist = ""
uilength = ""
user_input = ""
def to_the_power_of(a):
postion_n1 = a.index("^")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1**n2
sign = "^"
def subtracting(a):
postion_n1 = a.index("-")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1-n2
sign = "-"
def adding(a):
postion_n1 = a.index("+")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1+n2
sign = "+"
def multiplying(a):
postion_n1 = a.index("*")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1*n2
sign = "x"
def dividing(a):
postion_n1 = a.index("/")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1/n2
sign = "/"
def percentage(a):
postion_n1 = a.index("%")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = (n1*n2)/100
sign = "%"
def calculate(ab):
uilength = len(ab)
uilist = list(ab)
if "^" in uilist:
to_the_power_of(answer_1)
elif "+" in uilist:
adding(answer_1)
elif "-" in uilist:
subtracting(answer_1)
elif "*" in uilist:
multiplying(answer_1)
elif "/" in uilist:
dividing(answer_1)
elif "%" in uilist:
percentage(answer_1)
else:
print("Please eneter a valid calculation!")
while True:
user_input = input("Write your calculation: ")
answer_1 = user_input
calculate(user_input)
print(user_input,"=",total)
exit_cal = input("Would you like to exit or make a now calculation?").lower()
exit_list = ["exit","quit","leave","404"]
if exit_cal in exit_list:
sys.exit()
</code></pre>
<p>This is the error I get</p>
<pre><code>=======================
Use ^ for the power of
Use + for adding
Use - for subtracting
Use * for multiplying
Use / for dividing
Use % for a percentage
DON'T USE SPACES!
=======================
Write your calculation: 12*4
Traceback (most recent call last):
File "C:\Users\Max\Desktop\Python Scripts\Calculator.py", line 99, in <module>
print(user_input,"=",total)
NameError: name 'total' is not defined
</code></pre>
<p>Any help will be greatly appreciated!</p>
| 3 | 1,292 |
Works in JSFiddle not in web directory
|
<p>Here is the <a href="http://jsfiddle.net/CPeGK/2/" rel="nofollow">JSFiddle link</a>!</p>
<p>The code works fine except when I insert it in my index.html then the browser cannot resize the icon.</p>
<p>Using the following script tags in my header of the index.html file in my web project</p>
<pre><code><script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"/>
</code></pre>
<p>Do you have any ideas why this is not working?</p>
<p>TY in advance</p>
<p>Here is full code</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Home page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="layout.css" rel="stylesheet" type="text/css" />
<!--
David JavaScript code
-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"/>
<script>
$(document).ready(function() {
$("#imghover1").mouseover(function() {
$("#imghover1").width(295);
$("#imghover1").height(54);
});
$("#imghover1").mouseleave(function() {
$("#imghover1").width(245);
$("#imghover1").height(45);
});
});
</script>
</head>
<body id="page1">
<div class="tail-top">
<div class="tail-bottom">
<div class="main">
<div id="header">
<ul>
<li class="first"><a href="index.html" class="current">Home page</a></li>
<li><a href="index-1.html">Company</a></li>
<li><a href="index-2.html">Registration</a></li>
<li><a href="index-3.html">IT Services</a></li>
<li><a href="index-4.html">Questionnaire</a></li>
<li><a href="index-5.html">Contact Us</a></li>
</ul>
<a href="#"><img alt="" src="images/button2.gif" class="button1" /></a>
<div class="indent2"><img alt="" src="images/icon1.gif" class="alignMiddle" /> &nbsp;<a href="login.jsp">login</a> &nbsp; &nbsp; &nbsp; &nbsp;<img alt="" src="images/icon2.gif" class="alignMiddle" /> &nbsp;<a href="#">search</a></div>
<div><a href="index.html"><img alt="" src="images/xxcloud.gif" id="imghover1" class="logo" width="245" height="45" /></a><br /></div>
<div class="indent">
<img alt="" src="images/slogan.gif" /><br />
<img alt="" src="images/title.gif" /><br />
<p><strong>Donec accumsan malesuada orci. Donec sit amet eros. consectetuer adipiscing elit. Mauris fermentum dictum magna. Sed laoreet aliquam leo. Ut tellus dolor, dapibus eget elementum vel cursus eleifend elit. Aenean auctor wisi et urna. Aliquam erat volutpat. Duis ac turpis. </strong></p>
<a href="#"><img alt="" src="images/button.gif" class="button" /></a><br />
</div>
<div class="indent1">
<a href="#"><img alt="" src="images/banner1.jpg" /></a><a href="#"><img alt="" src="images/banner2.jpg" /></a><a href="#"><img alt="" src="images/banner3.jpg" /></a><a href="#"><img alt="" src="images/banner4.jpg" /></a><a href="#"><img alt="" src="images/banner5.jpg" /></a><br />
</div>
</div>
</code></pre>
| 3 | 2,558 |
(Homework) Running, but not returning the values I need
|
<p>I am very new to programming. I understand that loops would make this look a lot more efficient. But for right now, I just need to figure out <strong>how to return the correct value</strong>.
I need to figure out the best animal based on their value. The highest value should be returned.</p>
<ul>
<li><p><strong>I have changed the code to .equals on the comparing in the statements so now surveyresponse.equals("answer")</strong> It hasn't solved the problems for me.</p></li>
<li><p>The code is currently running, but only returns <strong>dragon</strong> as the <strong>answer</strong>.</p></li>
<li>I need the code to return the animal that has the highest value.</li>
<li><p>The assignment calls for that dog wins all ties, and cats always lose the tie breaker. </p>
<pre><code>import java.util.Scanner;
public class PetSurvey{
public static void main(String[] args){
String surveyResponse;
String y;
int dogScore, catScore, dragonScore, z;
dogScore = 0;
catScore = 0;
dragonScore = 0;
z = 0;
y = "best animal";
Scanner foo = new Scanner( System.in );
System.out.print(" What is your favorite pet? ");
System.out.print(" a) Dogs ");
System.out.print(" b) Cats ");
System.out.print(" c) Dragons ");
System.out.print(" d) I like cats, dogs and dragons ");
surveyResponse = foo.next();
if (surveyResponse == "a"){
dogScore = dogScore + 3;}
if (surveyResponse == "b"){
catScore = catScore + 3;}
if (surveyResponse == "c"){
dragonScore = dragonScore + 3;}
if (surveyResponse == "d"){
dogScore = dogScore + 1;
catScore = catScore + 1;
dragonScore = dragonScore +1;}
System.out.print(" What is your favorite pet? ");
System.out.print(" a) Dogs ");
System.out.print(" b) Cats ");
System.out.print(" c) Dragons ");
System.out.print(" d) I like cats, dogs and dragons ");
surveyResponse = foo.next();
if (surveyResponse == "a"){
dogScore = dogScore + 3;}
if (surveyResponse == "b"){
catScore = catScore + 3;}
if (surveyResponse == "c"){
dragonScore = dragonScore + 3;}
if (surveyResponse == "d"){
dogScore = dogScore + 1;
catScore = catScore + 1;
dragonScore = dragonScore +1;}
System.out.print(" What is your favorite pet? ");
System.out.print(" a) Dogs ");
System.out.print(" b) Cats ");
System.out.print(" c) Dragons ");
System.out.print(" d) I like cats, dogs and dragons ");
surveyResponse = foo.next();
if (surveyResponse == "a"){
dogScore = dogScore + 3;}
if (surveyResponse == "b"){
catScore = catScore + 3;}
if (surveyResponse == "c"){
dragonScore = dragonScore + 3;}
if (surveyResponse == "d"){
dogScore = dogScore + 1;
catScore = catScore + 1;
dragonScore = dragonScore +1;}
if (dogScore > z){
z = dogScore;}
if (catScore > z){
z = catScore;}
if (dragonScore > z){
z = dragonScore;}
if (dogScore == catScore){
z = dogScore;}
if (catScore == dragonScore){
z = dragonScore;}
if (z == dogScore){
y = "dog";}
if (z == catScore){
y = "cat";}
if (z == dragonScore){
y = "dragon";}
System.out.print(" The most popular pet is: " + y + ".");
}
}
</code></pre></li>
</ul>
<p>I would appreciate any help on this, thanks in advance.</p>
| 3 | 1,091 |
loading bmp images OPENGL 3.x - only loading one pixel?
|
<p>So Im having a bit of trouble loading texture images. I am not exactly sure what I could be doing wrong. It seems to only be reading the last pixel and I am not sure why?
Any help is appreciated. Here is my code:</p>
<pre><code>#include "Angel.h"
#include <glew.h>
#include <glut.h>
#include <typeinfo>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
using namespace std;
vec4 gridLines[] = {
vec4(-0.5, -0.5, 0.0, 1.0), //v1
vec4(0.5, -0.5, 0.0, 1.0), //v2
vec4(-0.5, 0.5, 0.0, 1.0), //v3
vec4(0.5, 0.5, 0.0, 1.0), //v4
};
GLuint vertexID[3];
GLuint bufferID2;
GLuint ProjectionLocation, ModelViewLocation;
mat4 instance;
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
float
roundTo(float value, int digits)//Ensures rounding is done correct
{
//check to see if the value is very close to zero
if ((int)(value*10.0) == 0){
return 0.0;
}
double factor = pow(10.0, digits - ceil(log10(fabs(value))));
return round(value * factor) / factor;
}
void
init(void) //Initialize Buffers for all objects
{
//1. Load shaders and use the resulting shader program
GLuint program = InitShader("vshader81.glsl", "fshader81.glsl");
glUseProgram(program);
GLuint vPosition = glGetAttribLocation(program, "vPosition");
GLuint vColor = glGetAttribLocation(program, "vColor");
glGenVertexArrays(1, &vertexID[1]);
vec4 colors2[] = {
vec4(1.0, 1.0, 1.0, 1.0), //1
vec4(1.0, 1.0, 1.0, 1.0), //2
vec4(1.0, 1.0, 1.0, 1.0), //3
vec4(1.0, 1.0, 1.0, 1.0), //4
};
// Create and initialize a buffer object
glBindVertexArray(vertexID[1]);
glGenBuffers(1, &bufferID2);
glBindBuffer(GL_ARRAY_BUFFER, bufferID2);
glBufferData(GL_ARRAY_BUFFER, sizeof(gridLines)+sizeof(colors2), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(gridLines), gridLines);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(gridLines), sizeof(colors2), colors2);
glEnableVertexAttribArray(vPosition);
glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
GLuint textureid;
// Texture coordinates
vec4 tex_coords[] = {
vec4(-0.5, -0.5, 0.0, 1.0), //v1
vec4(0.5, -0.5, 0.0, 1.0), //v2
vec4(-0.5, 0.5, 0.0, 1.0), //v3
vec4(0.5, 0.5, 0.0, 1.0), //v4
};
glGenTextures(1, &textureid);
glBindTexture(GL_TEXTURE_2D, textureid);
/***********************************************/
const char * imagepath = "checkboard2.bmp";
// Data read from the header of the BMP file
unsigned char header[54]; // Each BMP file begins by a 54-bytes header
unsigned int dataPos; // Position in the file where the actual data begins
unsigned int width, height;
unsigned int imageSize; // = width*height*3
// Actual RGB data
unsigned char * data;
// Open the file
FILE * file = fopen(imagepath, "rb");
if (!file) { printf("Image could not be opened\n"); }
if (fread(header, 1, 54, file) != 54){ // If not 54 bytes read : problem
printf("Not a correct BMP file\n");
}
if (header[0] != 'B' || header[1] != 'M'){
printf("Not a correct BMP file\n");
}
cout << "great.." << endl;
// Read ints from the byte array
dataPos = *(int*)&(header[0x0A]);
imageSize = *(int*)&(header[0x22]);
cout << "Image Size: " << imageSize << endl;
width = *(int*)&(header[0x12]);
cout << "width: " << width << endl;
height = *(int*)&(header[0x16]);
// Some BMP files are misformatted, guess missing information
if (imageSize == 0) imageSize = width*height * 3; // 3 : one byte for each Red, Green and Blue component
if (dataPos == 0) dataPos = 54; // The BMP header is done that way
// Create a buffer
data = new unsigned char[imageSize];
// Read the actual data from the file into the buffer
fread(data, 1, imageSize, file);
//Everything is in memory now, the file can be closed
fclose(file);
//GLuint Texture = loadBMP_custom("brick_converted.bmp");
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glActiveTexture(GL_TEXTURE0);
GLuint vTexCoord = glGetAttribLocation(program, "vTexCoord");
glEnableVertexAttribArray(vTexCoord);
glVertexAttribPointer(vTexCoord, 2, GL_FLOAT, GL_FALSE, 0,
BUFFER_OFFSET(sizeof(gridLines)));
glUniform1i(glGetUniformLocation(program, "texture"), 0);
//4. Bind all Buffers
glBindVertexArray(0);
//5.Set Background Color
glClearColor(0.5, 0.5, 0.5, 0.0); // background
}
//----------------------------------------------------------------------------
// Draw on Screen
//----------------------------------------------------------------------------
void
paintOnScreen()
{
glBindVertexArray(vertexID[1]);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
void
display(void) //Display to screen
{
//1.Clear the window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_CULL_FACE);
//2.Translations/Rotations/Projections etc..
glViewport(0, 0, 300, 300);
//3.Draw Objects
paintOnScreen();
glBindVertexArray(0);
//3.Force OpenGL to render
glFlush();
}
void
reshape(int width, int height)
{
glViewport(0, 0, width, height);
//aspect = GLfloat(width)/height;
}
void
keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 033: //ESC
exit(EXIT_SUCCESS);
break;
}
}
//----------------------------------------------------------------------------
int
main(int argc, char **argv)
{
// Initialize glut library
glutInit(&argc, argv);
// Create the window
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(300, 300);
glutInitWindowPosition(300, 200);
glutCreateWindow("Test");
// Initialize glew library
glewInit();
// Your own initialization
init();
// Set callback functions
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
// Start the main loop
glutMainLoop();
return 0;
}
</code></pre>
<p>and my fragment shader:</p>
<pre><code>#version 150
in vec2 texCoord;
out vec4 fColor;
uniform sampler2D texture;
void main()
{
fColor = texture2D( texture, texCoord );
}
</code></pre>
<p>and my vertex shader:</p>
<pre><code>#version 150
in vec4 vPosition;
in vec2 vTexCoord;
out vec2 texCoord;
void main()
{
texCoord = vTexCoord;
gl_Position = vPosition;
}
</code></pre>
| 3 | 2,941 |
Trying to read excel using pandas and adding them as records on Pysolar/Solar but got TypeError: a bytes-like object is required, not 'str'
|
<p>I am trying to read specific columns from an excel file using pandas.
When I am trying to add those records to Solr got TypeError.</p>
<p>The code which i am using -</p>
<pre><code>from __future__ import print_function
import pysolr
import pandas as pd
df_my = pd.read_excel('C:\\Users\\shantanu.nandan\\Desktop\\sample.xlsx',encoding='utf-8')
df_selected = df_my.loc[:,['column_1','column_2','column_3','column_4']]
for index,row in df_selected.iterrows():
row['column_2'] = row['column_2'].replace('\n','')
for index,row in df_selected.iterrows():
row['column_2'] = row['column_2'].replace('\r','')
for index,row in df_selected.iterrows():
row['column_2'] = row['column_2'].replace('<br/>','')
df_dict = df_selected.to_dict('records')
solr = pysolr.Solr('http://localhost:8983/solr/My_Data')
solr.add(df_dict)
</code></pre>
<p>Putting the stack trace of the error -</p>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-62-00ae8c4ee938> in <module>
----> 1 solr.add(df_dict)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pysolr.py in add(self, docs, commit, boost, commitWithin, waitFlush, waitSearcher)
747 end_time = time.time()
748 self.log.debug("Built add request of %s docs in %0.2f seconds.", len(docs), end_time - start_time)
--> 749 return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)
750
751 def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None):
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pysolr.py in _update(self, message, clean_ctrl_chars, commit, waitFlush, waitSearcher)
357 message = sanitize(message)
358
--> 359 return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'})
360
361 def _extract_error(self, resp):
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pysolr.py in _send_request(self, method, path, body, headers, files)
288
289 if int(resp.status_code) != 200:
--> 290 error_message = self._extract_error(resp)
291 self.log.error(error_message, extra={'data': {'headers': resp.headers,
292 'response': resp.content}})
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pysolr.py in _extract_error(self, resp)
367
368 if reason is None:
--> 369 reason, full_html = self._scrape_response(resp.headers, resp.content)
370
371 msg = "[Reason: %s]" % reason
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pysolr.py in _scrape_response(self, headers, response)
430 full_html = "%s" % response
431
--> 432 full_html = full_html.replace('\n', '')
433 full_html = full_html.replace('\r', '')
434 full_html = full_html.replace('<br/>', '')
TypeError: a bytes-like object is required, not 'str'
</code></pre>
| 3 | 1,405 |
Removing d3-flame-graph when loading new data
|
<p>Recently I picked up a project that has <code>d3-flame-graph</code> on it and the graph is displayed according to the Filters defined on another component.
My issue is that when searching with new parameters I can't seem to clean the previous chart and I was wondering if someone could help me. Basically what I'm having right now is, when I first enter the page, the loading component, then I have my graph and when I search for a new date I have the loading component but on top of that I still have the previous graph</p>
<p>I figured I could use <code>flamegraph().destroy()</code> on <code>const updateGraph</code> but nothing is happening</p>
<pre><code>import React, { FC, useEffect, useRef, useState, useCallback } from 'react'
import { useParams } from 'react-router-dom'
import moment from 'moment'
import * as d3 from 'd3'
import { flamegraph } from 'd3-flame-graph'
import Filters, { Filter } from '../../../../../../components/Filters'
import { getFlamegraph } from '../../../../../../services/flamegraph'
import { useQueryFilter } from '../../../../../../hooks/filters'
import FlamegraphPlaceholder from '../../../../../../components/Placeholders/Flamegraph'
import css from './flamegraph.module.css'
import ToastContainer, {
useToastContainerMessage,
} from '../../../../../../components/ToastContainer'
const defaultFilters = {
startDate: moment().subtract(1, 'month'),
endDate: moment(),
text: '',
limit: 10,
}
const getOffSet = (divElement: HTMLDivElement | null) => {
if (divElement !== null) {
const padding = 100
const minGraphHeight = 450
// ensure that the graph has a min height
return Math.max(
window.innerHeight - divElement.offsetTop - padding,
minGraphHeight
)
} else {
const fallBackNavigationHeight = 300
return window.innerHeight - fallBackNavigationHeight
}
}
const Flamegraph: FC = () => {
const [queryFilters, setQueryFilters] = useQueryFilter(defaultFilters)
const [fetching, setFetching] = useState(false)
const [graphData, setGraphData] = useState()
const {
messages: toastMessages,
addMessage: addMessageToContainer,
removeMessage: removeMessageFromContainer,
} = useToastContainerMessage()
const flameContainerRef = useRef<HTMLDivElement | null>(null)
const flameRef = useRef<HTMLDivElement | null>(null)
const graphRef = useRef<any>()
const graphDataRef = useRef<any>()
const timerRef = useRef<any>()
const { projectId, functionId } = useParams()
let [sourceId, sourceLine] = ['', '']
if (functionId) {
;[sourceId, sourceLine] = functionId.split(':')
}
const createGraph = () => {
if (flameContainerRef.current && flameRef.current) {
graphRef.current = flamegraph()
.width(flameContainerRef.current.offsetWidth)
.height(getOffSet(flameRef.current))
.cellHeight(30)
.tooltip(false)
.setColorMapper(function(d, originalColor) {
// Scale green component proportionally to box width (=> the wider the redder)
let greenHex = (192 - Math.round((d.x1 - d.x0) * 128)).toString(16)
return '#FF' + ('0' + greenHex).slice(-2) + '00'
})
}
}
const updateGraph = (newData: any) => {
setGraphData(newData)
graphDataRef.current = newData
if (graphRef.current) {
if (newData === null) {
graphRef.current.destroy()
graphRef.current = null
} else {
d3.select(flameRef.current)
.datum(newData)
.call(graphRef.current)
}
}
}
const fetchGraph = (filters: Filter) => {
setFetching(true)
getFlamegraph(
Number(projectId),
filters.startDate ? filters.startDate.unix() : 0,
filters.endDate ? filters.endDate.unix() : 0,
sourceId,
sourceLine
)
.then(graphData => {
if (!graphRef.current) {
createGraph()
}
updateGraph(graphData)
})
.catch(({ response }) => {
updateGraph(null)
if (response.data) {
addMessageToContainer(response.data.message, true)
}
})
.finally(() => {
setFetching(false)
})
}
const onResize = useCallback(() => {
clearTimeout(timerRef.current)
timerRef.current = setTimeout(() => {
if (graphRef.current && flameContainerRef.current) {
graphRef.current.width(flameContainerRef.current.offsetWidth)
d3.select(flameRef.current)
.datum(graphDataRef.current)
.call(graphRef.current)
}
}, 500)
}, [])
useEffect(() => {
fetchGraph(queryFilters)
window.addEventListener('resize', onResize)
return () => {
window.removeEventListener('resize', onResize)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const onChangeFilters = (filters: Filter) => {
setQueryFilters(filters)
fetchGraph(filters)
}
return (
<div className={css.host}>
<Filters
defaultValues={queryFilters}
searching={fetching}
onSearch={onChangeFilters}
/>
<div className={css.flameBox}>
<div className={css.flameContainer} ref={flameContainerRef}>
<div ref={flameRef} />
</div>
{fetching || !graphData ? (
<FlamegraphPlaceholder loading={fetching} />
) : null}
</div>
<ToastContainer
messages={toastMessages}
toastDismissed={removeMessageFromContainer}
/>
</div>
)
}
export default Flamegraph
</code></pre>
| 3 | 2,240 |
SQL - How to count number of distinct values (payments), after sum of rows where they have another column value (Due Date) in common
|
<p>My 'deals_payments' table is:</p>
<pre><code>Due Date Payment ID
1-Mar-19 1,000.00 123
1-Apr-19 1,000.00 123
1-May-19 1,000.00 123
1-Jun-19 1,000.00 123
1-Jul-19 1,000.00 123
1-Aug-19 1,000.00 123
1-Jun-19 500.00 456
1-Jul-19 500.00 456
1-Aug-19 500.00 456
</code></pre>
<p>I have the SQL code:</p>
<pre><code>select
count(*), payment
from (select deals_payments.*,
(row_number() over (order by due_date) -
row_number() over (partition by payment order by due_date)
) as grp
from deals_payments
where id = 123
) deals_payments
group by grp, payment
order by grp
</code></pre>
<p>which gives me what I want - the number of payments on each distinct amount - (here I only asked for ID 123):</p>
<pre><code>COUNT(*) PAYMENT
6 1000.00
</code></pre>
<p>But now I need the sum of payments of the two ID's (123 and 456), where the due dates are the same, and count the number of payments on each distinct amount, as:</p>
<pre><code>COUNT(*) PAYMENT
3 1000.00
3 1500.00
</code></pre>
<p>I tried the below but it gives me the 'missing right parenthesis' error. What is wrong??</p>
<pre><code> select
count(*),
(select
sum(total) total
from (select distinct
due_date,
(select
sum(payment)
from deals_payments
where (due_date = a.due_date)) as total
from deals_payments a
where a.id in (123, 456)
and payment > 0)
group by due_date
order by due_date) b
from (select deals_payments.*,
(row_number() over (order by due_date) -
row_number() over (partition by payment order by due_date)
) as grp
from deals_payments
where id = 123
) deals_payments
group by grp, payment
order by grp
</code></pre>
| 3 | 1,133 |
AWS problem accessing Spring cloud eureka server
|
<p>I am migrating my spring cloud eureka application to AWS ECS and currently having some trouble doing so. </p>
<p>I have an ECS cluster on AWS in which an EC2 service of eureka-server
is running on it. in this service, there is a task running</p>
<p><strong>My problem is that:</strong> </p>
<p>For my Eureka-server task, it suppose to run on External Link 18.136.147.71:8761 , but it isn't.This 18.136.147.71 is an auto assigned IP by AWS. the only setting i made was allocating an Elastic IP via EC2 Panel.</p>
<p>Although from CloudWatch log i can see that the service is running normal, i am unable to access the link as it always gives this error </p>
<pre><code>This site can’t be reached. 18.136.147.71:8761 took too long to respond.
</code></pre>
<p><strong>what are some possible errors that might have lead to this problem?
there is no problem with the docker image because i am able to run it locally on my computer.</strong> </p>
<p>below are my CloudWatch Log. This log is exactly the same as my local terminal output when i run the docker image locally:</p>
<pre><code>2018-11-21 04:10:13.567 INFO 1 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1376c05c: startup date [Wed Nov 21 04:10:13 GMT 2018]; root of context hierarchy
2018-11-21 04:10:15.178 INFO 1 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-11-21 04:10:15.366 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$7e4594e4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.2.RELEASE)
2018-11-21 04:10:18.870 INFO 1 --- [ main] eureka.server.ServerApplication : No active profile set, falling back to default profiles: default
2018-11-21 04:10:18.972 INFO 1 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@735b5592: startup date [Wed Nov 21 04:10:18 GMT 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@1376c05c
2018-11-21 04:10:24.655 INFO 1 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=1ce1cdc0-5c4b-3c0c-ae18-58ba57b52bb6
2018-11-21 04:10:24.681 INFO 1 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-11-21 04:10:25.164 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration' of type [org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration$$EnhancerBySpringCGLIB$$94583828] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-11-21 04:10:25.179 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$7e4594e4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-11-21 04:10:26.276 INFO 1 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8761 (http)
2018-11-21 04:10:26.370 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2018-11-21 04:10:26.371 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.11
2018-11-21 04:10:26.775 INFO 1 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-11-21 04:10:26.775 INFO 1 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 7803 ms
2018-11-21 04:10:29.661 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'metricsFilter' to: [/*]
2018-11-21 04:10:29.662 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-21 04:10:29.662 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-21 04:10:29.662 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-11-21 04:10:29.662 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-21 04:10:29.664 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webRequestTraceFilter' to: [/*]
2018-11-21 04:10:29.664 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'servletContainer' to urls: [/eureka/*]
2018-11-21 04:10:29.664 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'applicationContextIdFilter' to: [/*]
2018-11-21 04:10:29.665 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-11-21 04:10:30.190 INFO 1 --- [ost-startStop-1] c.s.j.s.i.a.WebApplicationImpl : Initiating Jersey application, version 'Jersey: 1.19.1 03/11/2016 02:08 PM'
2018-11-21 04:10:30.676 INFO 1 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson
2018-11-21 04:10:30.677 INFO 1 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson
2018-11-21 04:10:31.261 INFO 1 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml
2018-11-21 04:10:31.262 INFO 1 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml
2018-11-21 04:10:34.871 INFO 1 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@735b5592: startup date [Wed Nov 21 04:10:18 GMT 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@1376c05c
2018-11-21 04:10:35.375 INFO 1 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-11-21 04:10:35.376 INFO 1 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-11-21 04:10:35.380 INFO 1 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/lastn],methods=[GET]}" onto public java.lang.String org.springframework.cloud.netflix.eureka.server.EurekaController.lastn(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.Object>)
2018-11-21 04:10:35.380 INFO 1 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String org.springframework.cloud.netflix.eureka.server.EurekaController.status(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.Object>)
2018-11-21 04:10:35.482 INFO 1 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-21 04:10:35.482 INFO 1 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-21 04:10:35.758 INFO 1 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-21 04:10:38.472 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.473 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mappings || /mappings.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.474 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.475 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/restart || /restart.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.context.restart.RestartMvcEndpoint.invoke()
2018-11-21 04:10:38.475 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/archaius || /archaius.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.476 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/dump || /dump.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.479 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/loggers/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.LoggersMvcEndpoint.get(java.lang.String)
2018-11-21 04:10:38.556 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/loggers/{name:.*}],methods=[POST],consumes=[application/vnd.spring-boot.actuator.v1+json || application/json],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.LoggersMvcEndpoint.set(java.lang.String,java.util.Map<java.lang.String, java.lang.String>)
2018-11-21 04:10:38.556 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/loggers || /loggers.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.557 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/refresh || /refresh.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke()
2018-11-21 04:10:38.557 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/resume || /resume.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke()
2018-11-21 04:10:38.558 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/auditevents || /auditevents.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.boot.actuate.endpoint.mvc.AuditEventsMvcEndpoint.findByPrincipalAndAfterAndType(java.lang.String,java.util.Date,java.lang.String)
2018-11-21 04:10:38.559 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/info || /info.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.559 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.context.environment.EnvironmentManagerMvcEndpoint.value(java.util.Map<java.lang.String, java.lang.String>)
2018-11-21 04:10:38.560 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env/reset],methods=[POST]}" onto public java.util.Map<java.lang.String, java.lang.Object> org.springframework.cloud.context.environment.EnvironmentManagerMvcEndpoint.reset()
2018-11-21 04:10:38.560 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/health || /health.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(javax.servlet.http.HttpServletRequest,java.security.Principal)
2018-11-21 04:10:38.565 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/heapdump || /heapdump.json],methods=[GET],produces=[application/octet-stream]}" onto public void org.springframework.boot.actuate.endpoint.mvc.HeapdumpMvcEndpoint.invoke(boolean,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.io.IOException,javax.servlet.ServletException
2018-11-21 04:10:38.565 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.568 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2018-11-21 04:10:38.568 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.568 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/features || /features.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.569 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2018-11-21 04:10:38.569 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env || /env.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.570 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/trace || /trace.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-11-21 04:10:38.570 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/pause || /pause.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke()
2018-11-21 04:10:38.570 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/service-registry/instance-status],methods=[GET]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint.getStatus()
2018-11-21 04:10:38.570 INFO 1 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/service-registry/instance-status],methods=[POST]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint.setStatus(java.lang.String)
2018-11-21 04:10:38.989 INFO 1 --- [ main] o.s.ui.freemarker.SpringTemplateLoader : SpringTemplateLoader for FreeMarker: using resource loader [org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@735b5592: startup date [Wed Nov 21 04:10:18 GMT 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@1376c05c] and template loader path [classpath:/templates/]
2018-11-21 04:10:38.990 INFO 1 --- [ main] o.s.w.s.v.f.FreeMarkerConfigurer : ClassTemplateLoader for Spring macros added to FreeMarker configuration
2018-11-21 04:10:39.462 WARN 1 --- [ main] o.s.c.n.a.ArchaiusAutoConfiguration : No spring.application.name found, defaulting to 'application'
2018-11-21 04:10:39.470 WARN 1 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2018-11-21 04:10:39.471 INFO 1 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-11-21 04:10:39.486 WARN 1 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2018-11-21 04:10:39.555 INFO 1 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-11-21 04:10:39.760 INFO 1 --- [ main] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING
2018-11-21 04:10:39.979 INFO 1 --- [ main] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1
2018-11-21 04:10:39.980 INFO 1 --- [ main] com.netflix.discovery.DiscoveryClient : Client configured to neither register nor query for data.
2018-11-21 04:10:40.073 INFO 1 --- [ main] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1542773440073 with initial instances count: 0
2018-11-21 04:10:40.557 INFO 1 --- [ main] c.n.eureka.DefaultEurekaServerContext : Initializing ...
2018-11-21 04:10:40.562 INFO 1 --- [ main] c.n.eureka.cluster.PeerEurekaNodes : Adding new peer nodes [http://localhost:8761/eureka/]
2018-11-21 04:10:41.886 INFO 1 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson
2018-11-21 04:10:41.887 INFO 1 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson
2018-11-21 04:10:41.887 INFO 1 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml
2018-11-21 04:10:41.887 INFO 1 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml
2018-11-21 04:10:42.568 INFO 1 --- [ main] c.n.eureka.cluster.PeerEurekaNodes : Replica node URL: http://localhost:8761/eureka/
2018-11-21 04:10:42.577 INFO 1 --- [ main] c.n.e.registry.AbstractInstanceRegistry : Finished initializing remote region registries. All known remote regions: []
2018-11-21 04:10:42.577 INFO 1 --- [ main] c.n.eureka.DefaultEurekaServerContext : Initialized
2018-11-21 04:10:42.859 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-11-21 04:10:42.868 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'environmentManager' has been autodetected for JMX exposure
2018-11-21 04:10:42.869 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'configurationPropertiesRebinder' has been autodetected for JMX exposure
2018-11-21 04:10:42.870 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'refreshEndpoint' has been autodetected for JMX exposure
2018-11-21 04:10:42.870 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'restartEndpoint' has been autodetected for JMX exposure
2018-11-21 04:10:42.871 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'serviceRegistryEndpoint' has been autodetected for JMX exposure
2018-11-21 04:10:42.872 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'refreshScope' has been autodetected for JMX exposure
2018-11-21 04:10:42.874 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'environmentManager': registering with JMX server as MBean [org.springframework.cloud.context.environment:name=environmentManager,type=EnvironmentManager]
2018-11-21 04:10:42.964 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'restartEndpoint': registering with JMX server as MBean [org.springframework.cloud.context.restart:name=restartEndpoint,type=RestartEndpoint]
2018-11-21 04:10:42.974 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'serviceRegistryEndpoint': registering with JMX server as MBean [org.springframework.cloud.client.serviceregistry.endpoint:name=serviceRegistryEndpoint,type=ServiceRegistryEndpoint]
2018-11-21 04:10:42.980 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'refreshScope': registering with JMX server as MBean [org.springframework.cloud.context.scope.refresh:name=refreshScope,type=RefreshScope]
2018-11-21 04:10:43.068 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'configurationPropertiesRebinder': registering with JMX server as MBean [org.springframework.cloud.context.properties:name=configurationPropertiesRebinder,context=735b5592,type=ConfigurationPropertiesRebinder]
2018-11-21 04:10:43.072 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'refreshEndpoint': registering with JMX server as MBean [org.springframework.cloud.endpoint:name=refreshEndpoint,type=RefreshEndpoint]
2018-11-21 04:10:43.773 INFO 1 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2018-11-21 04:10:43.774 INFO 1 --- [ main] o.s.c.n.e.s.EurekaServiceRegistry : Registering application unknown with eureka with status UP
2018-11-21 04:10:43.973 INFO 1 --- [ Thread-11] o.s.c.n.e.server.EurekaServerBootstrap : Setting the eureka configuration..
2018-11-21 04:10:43.974 INFO 1 --- [ Thread-11] o.s.c.n.e.server.EurekaServerBootstrap : Eureka data center value eureka.datacenter is not set, defaulting to default
2018-11-21 04:10:43.974 INFO 1 --- [ Thread-11] o.s.c.n.e.server.EurekaServerBootstrap : Eureka environment value eureka.environment is not set, defaulting to test
2018-11-21 04:10:44.071 INFO 1 --- [ Thread-11] o.s.c.n.e.server.EurekaServerBootstrap : isAws returned false
2018-11-21 04:10:44.071 INFO 1 --- [ Thread-11] o.s.c.n.e.server.EurekaServerBootstrap : Initialized server context
2018-11-21 04:10:44.072 INFO 1 --- [ Thread-11] c.n.e.r.PeerAwareInstanceRegistryImpl : Got 1 instances from neighboring DS node
2018-11-21 04:10:44.072 INFO 1 --- [ Thread-11] c.n.e.r.PeerAwareInstanceRegistryImpl : Renew threshold is: 1
2018-11-21 04:10:44.072 INFO 1 --- [ Thread-11] c.n.e.r.PeerAwareInstanceRegistryImpl : Changing status to UP
2018-11-21 04:10:44.165 INFO 1 --- [ Thread-11] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2018-11-21 04:10:44.367 INFO 1 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8761 (http)
2018-11-21 04:10:44.369 INFO 1 --- [ main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8761
2018-11-21 04:10:44.372 INFO 1 --- [ main] eureka.server.ServerApplication : Started ServerApplication in 33.505 seconds (JVM running for 36.231)
2018-11-21 04:11:44.159 INFO 1 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry : Running the evict task with compensationTime 0ms
2018-11-21 04:12:44.159 INFO 1 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry : Running the evict task with compensationTime 0ms
</code></pre>
| 3 | 8,657 |
Recylerview items that are visible are not getting updated when notifyDataSetChanged() is called
|
<p>I am having a recycler view whose vies of the items that are visible are not getting updated, when notifyDataSetChanged() is called. The items that are invisible are getting updated without any problem.</p>
<p>I have seen that this has been a problem with listview as given here:
<a href="https://stackoverflow.com/questions/19635220/listview-not-refreshing-already-visible-items">List view not refreshing already visible items</a></p>
<p>But I am not knowing what to do with recycler view.
In my recycler view adapter I add views dynamically according to my code.</p>
<p><strong>Here is my code:</strong></p>
<pre><code>public class Nearby_Viewpager_Stops extends Fragment {
private final String TAG = "Nearby Stops";
View mRootview = null;
RecyclerView mRecyclerView;
MKLoader mProgressBar;
Context mContext;
TextView mNoStopsTV;
Nearby_Stops_Adapter mStops_adapter;
List<BusArrivalPOJO> mBusArrivalPOJOList = new ArrayList<>();
List<List<BusArrivalPOJO>> mBusArrivalDetailsPOJOList = new ArrayList<>();
LinearLayoutManager mLayoutManager;
Handler mHandler;
Handler mHandlerForOnStop;
boolean resumed = true;
private static final int REFRESH_TIME = 30;
int lengthOfStopsList;
boolean isNoStops_available_nearby = false;
boolean isFirstTimeCalled;
boolean isRunningFirstTime;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (mRootview == null) {
mRootview = inflater.inflate(R.layout.nearby_viewpager_stops, container, false);
mRecyclerView = (RecyclerView) mRootview.findViewById(R.id.recycler_view);
mProgressBar = (MKLoader) mRootview.findViewById(R.id.progressBar);
mNoStopsTV = (TextView) mRootview.findViewById(R.id.no_nearby_stops_text);
}
mLayoutManager = new LinearLayoutManager(mContext);
mRecyclerView.setLayoutManager(mLayoutManager);
mStops_adapter = new Nearby_Stops_Adapter(mBusArrivalPOJOList, mBusArrivalDetailsPOJOList);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mStops_adapter);
return mRootview;
}
private class GetNearbyStops extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
isNoStops_available_nearby = false;
mProgressBar.setVisibility(View.VISIBLE);
mBusArrivalPOJOList.clear();
pos = mLayoutManager.findFirstVisibleItemPosition();
mStops_adapter.notifyDataSetChanged();
}
@Override
protected Void doInBackground(Void... voids) {
String urlString = "https://api.tfl.gov.uk/StopPoint?radius=2000&stopTypes=NaptanRailStation,NaptanBusCoachStation,NaptanFerryPort,NaptanPublicBusCoachTram&useStopPointHierarchy=true" +
"&modes=bus&lat="+ Constants.latitude+"&lon="+Constants.longitude+"&categories=facility&app_id=" + Constants.app_id_tfl + "&app_key=" + Constants.app_key_tfl;
Log.v(TAG, urlString);
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader;
String line;
InputStream inputStream;
StringBuilder json_result = new StringBuilder();
try {
System.setProperty("http.keepAlive", "false");
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(2000);
urlConnection.setConnectTimeout(2000);
urlConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(urlConnection.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
json_result.append(line);
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
getDataFromJSON(json_result.toString());
return null;
}
private void getDataFromJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray stopPoints = jsonObject.getJSONArray("stopPoints");
if (stopPoints.length() <= 20 && stopPoints.length() != 0) {
lengthOfStopsList = stopPoints.length();
} else if (stopPoints.length() == 0) {
lengthOfStopsList = 0;
isNoStops_available_nearby = true;
}
for (int i = 0; i< lengthOfStopsList; i++) {
JSONObject jsonObject1 = stopPoints.getJSONObject(i);
int distance = Math.round(jsonObject1.getInt("distance")/60);
Double lat = jsonObject1.getDouble("lat");
Double lon = jsonObject1.getDouble("lon");
String commonName = jsonObject1.getString("commonName");
JSONArray lineGroup = jsonObject1.getJSONArray("lineGroup");
new GetBusArrivals().execute(lineGroup, new LatLng(lat, lon), distance);
String naptanID;
for (int j=0; j< lineGroup.length(); j++) {
JSONObject jsonObject2 = lineGroup.getJSONObject(j);
if (jsonObject2.has("naptanIdReference")) {
naptanID = jsonObject2.getString("naptanIdReference");
BusArrivalPOJO busArrivalPOJO = new
BusArrivalPOJO(commonName, distance, new LatLng(lat, lon), naptanID);
mBusArrivalPOJOList.add(busArrivalPOJO);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mStops_adapter.notifyDataSetChanged();
}
});
}
}
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
if (getActivity()!=null)
getActivity().runOnUiThread(new Runnable() {
public void run() {
new GetNearbyStops().execute();
}
});
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (isNoStops_available_nearby) {
mProgressBar.setVisibility(View.GONE);
mNoStopsTV.setVisibility(View.VISIBLE);
} else {
mProgressBar.setVisibility(View.VISIBLE);
mNoStopsTV.setVisibility(View.GONE);
}
}
}
int pos;
private class GetBusArrivals extends AsyncTask<Object, Void, Void> {
/**
* It represents the position of the first visible position of recycler view
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
if (isFirstTimeCalled) {
if (getActivity() != null)
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mBusArrivalDetailsPOJOList.clear();
mStops_adapter.notifyDataSetChanged();
}
});
isFirstTimeCalled = false;
}
}
LatLng latLng;
String stopID;
int distance;
@Override
protected Void doInBackground(Object... strings) {
JSONArray lineGroup = (JSONArray) strings[0];
latLng = (LatLng) strings[1];
distance = (int) strings[2];
try {
for (int j=0; j< lineGroup.length(); j++) {
JSONObject jsonObject2 = lineGroup.getJSONObject(j);
if (jsonObject2.has("naptanIdReference")) {
stopID = jsonObject2.getString("naptanIdReference");
String urlString = "https://api.tfl.gov.uk/StopPoint/"+stopID+"/Arrivals?app_id="
+ Constants.app_id_tfl + "&app_key=" + Constants.app_key_tfl;
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader;
String line;
InputStream inputStream;
StringBuilder json_result = new StringBuilder();
try {
Log.v(TAG, urlString);
System.setProperty("http.keepAlive", "false");
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(2000);
urlConnection.setConnectTimeout(2000);
urlConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(urlConnection.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
json_result.append(line);
}
List<BusArrivalPOJO> busArrivalPOJOs = getDataFromJSON(json_result.toString(), latLng, distance);
if (busArrivalPOJOs != null) {
mBusArrivalDetailsPOJOList.add(busArrivalPOJOs);
Log.v("length", "leng"+mBusArrivalDetailsPOJOList.size());
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (mProgressBar.getVisibility() == View.VISIBLE)
mProgressBar.setVisibility(View.GONE);
if (mBusArrivalDetailsPOJOList.size() < 5) {
mRecyclerView.setAdapter(mStops_adapter);
} else
mStops_adapter.notifyDataSetChanged();
}
});
}
}
} catch (Exception e) {
j= j-1;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
}
return null;
}
private List<BusArrivalPOJO> getDataFromJSON(String json, LatLng latLng, int distance) {
List<BusArrivalPOJO> busArrivalPOJOList = new ArrayList<>();
try {
Log.v(TAG, json);
JSONArray jsonArray = new JSONArray(json);
for (int i=0; i< jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.has("exceptionType") && jsonObject.getString("exceptionType").contentEquals("EntityNotFoundException")) {
return null;
} else {
String lineName = jsonObject.getString("lineName");
String platformName = jsonObject.getString("platformName");
String destinationName = jsonObject.getString("destinationName");
int timeToArrivalToStation = jsonObject.getInt("timeToStation");
String stationName = jsonObject.getString("stationName");
String naptanId = jsonObject.getString("naptanId");
BusArrivalPOJO busArrivalPOJO = new BusArrivalPOJO(lineName, platformName, destinationName,
timeToArrivalToStation, stationName, latLng, distance, naptanId);
busArrivalPOJOList.add(busArrivalPOJO);
}
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
}
return busArrivalPOJOList;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (pos< mBusArrivalPOJOList.size()-5 && mBusArrivalPOJOList.size()-5 == mBusArrivalDetailsPOJOList.size()
|| mBusArrivalDetailsPOJOList.size() == mBusArrivalPOJOList.size()) {
}
if (MainActivity.menuItem != null && MainActivity.menuItem.getActionView() != null) {
MainActivity.menuItem.getActionView().clearAnimation();
MainActivity.menuItem.setActionView(null);
}
}
}
@Override
public void onResume() {
super.onResume();
mHandler = new Handler();
resumed = true;
isRunningFirstTime = true;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
isFirstTimeCalled = true;
new GetNearbyStops().execute();
mHandler.postDelayed(this, REFRESH_TIME * 1000);
}
}, 1000);
}
}
</code></pre>
<p><strong>Here is the code for my recycler view adapter:</strong></p>
<pre><code>class Nearby_Stops_Adapter extends RecyclerView.Adapter {
private List<List<BusArrivalPOJO>> mBusArrivalPOJOListFullDetails = new ArrayList<>();
private List<BusArrivalPOJO> mBusArrivalPOJOList = new ArrayList<>();
Context mContext;
private LinearLayout mLinearLayout;
private static HashSet<String> isRemainingTimesOpen = new HashSet<>();
private final String TAG = "NearbyStopsAda";
Nearby_Stops_Adapter(List<BusArrivalPOJO> busArrivalPOJOList,List<List<BusArrivalPOJO>> busArrivalPOJOList1 ) {
mBusArrivalPOJOList = busArrivalPOJOList;
mBusArrivalPOJOListFullDetails = busArrivalPOJOList1;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.nearby_stops_adapter,parent,false);
mContext = parent.getContext();
mLinearLayout = (LinearLayout) rootView.findViewById(R.id.linear_layout);
TextView mStationName = (TextView) rootView.findViewById(R.id.stationName);
mStationName.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
MKLoader progressBar = (MKLoader) rootView.findViewById(R.id.progressBar);
TextView timeToWalkToStation = (TextView) rootView.findViewById(R.id.timeToTravel);
CardView cardView = (CardView) rootView.findViewById(R.id.cardView);
return new Nearby_Stops_Adapter.ViewHolder(rootView, mStationName, timeToWalkToStation, cardView, progressBar);
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (mBusArrivalPOJOList.size() > 0) {
((ViewHolder) holder).stationNameTV.setText(mBusArrivalPOJOList.get(position).getStationName());
String time = mBusArrivalPOJOList.get(position).getTimeToWalkToStation() + " min";
((ViewHolder) holder).timeToWalkToStation.setText(time);
}
if (mBusArrivalPOJOListFullDetails.size()>0) {
mLinearLayout.removeAllViews();
for (int a=0; a< mBusArrivalPOJOListFullDetails.size() ;a++) {
if (mBusArrivalPOJOList.get(position).getStationID()
.contentEquals(mBusArrivalPOJOListFullDetails.get(a).get(0).getStationID())) {
if (!mBusArrivalPOJOListFullDetails.get(a).get(0).getPlatformName().contentEquals("null"))
if (!((ViewHolder) holder).stationNameTV.getText().toString().contains("::"))
((ViewHolder) holder).stationNameTV.append(" :: "+mBusArrivalPOJOListFullDetails.get(a).get(0).getPlatformName());
for (int j=0; j< mBusArrivalPOJOListFullDetails.get(a).size() ;j++) {
Collections.sort(mBusArrivalPOJOListFullDetails.get(a), new Comparator<BusArrivalPOJO>() {
@Override
public int compare(BusArrivalPOJO busArrivalPOJO, BusArrivalPOJO t1) {
return busArrivalPOJO.getTimeToArrival() - t1.getTimeToArrival();
}
});
}
Set<String> uniqueBusNamesSet = new HashSet<>();
for (int m = 0; m< mBusArrivalPOJOListFullDetails.get(a).size() ;m++) {
uniqueBusNamesSet.add(mBusArrivalPOJOListFullDetails.get(a).get(m).getBusName());
}
ArrayList<Multimap<String, Integer>> allBusesForParticularStation = new ArrayList<>();
for (String key: uniqueBusNamesSet) {
Multimap<String, Integer> busWithTimes = ArrayListMultimap.create();
for (int s=0; s< mBusArrivalPOJOListFullDetails.get(a).size() ;s++) {
if (key.contentEquals(mBusArrivalPOJOListFullDetails.get(a).get(s).getBusName())) {
busWithTimes.put(key +"::"+ mBusArrivalPOJOListFullDetails.get(a).get(s).getDestinationName()
, mBusArrivalPOJOListFullDetails.get(a).get(s).getTimeToArrival());
}
}
allBusesForParticularStation.add(busWithTimes);
}
((ViewHolder) holder).progressBar.setVisibility(View.GONE);
for (int t=0 ; t< allBusesForParticularStation.size() ;t++) {
Multimap<String, Integer> map = allBusesForParticularStation.get(t);
for (String key: map.keySet()) {
List<Integer> values = new ArrayList<>(map.get(key));
RelativeLayout relativeLayout = new RelativeLayout(mContext);
relativeLayout.setPadding(16, 16, 16, 16);
LinearLayout linearLayoutForBusName = new LinearLayout(mContext);
linearLayoutForBusName.setOrientation(LinearLayout.VERTICAL);
final TextView busNameTV = new TextView(mContext);
busNameTV.setText(key.split("::")[0]);
busNameTV.setTypeface(Typeface.create("sans-serif-normal", Typeface.NORMAL));
busNameTV.setTextColor(ContextCompat.getColor(mContext,R.color.colorTextPrimary));
final TextView destinationNameTV = new TextView(mContext);
destinationNameTV.setText(key.split("::")[1]);
destinationNameTV.setTextSize(12);
destinationNameTV.setTextColor(ContextCompat.getColor(mContext,R.color.colorTextSecondary));
linearLayoutForBusName.addView(busNameTV);
linearLayoutForBusName.addView(destinationNameTV);
LinearLayout linearLayoutForTimes = new LinearLayout(mContext);
linearLayoutForTimes.setOrientation(LinearLayout.VERTICAL);
RelativeLayout timeRelativeLayout = new RelativeLayout(mContext);
timeRelativeLayout.setId(R.id.time_relativeLayout_id);
LinearLayout timeArrowLinearLayout = new LinearLayout(mContext);
timeArrowLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
timeArrowLinearLayout.setId(R.id.time_id);
timeArrowLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
timeArrowLinearLayout.setPadding(6,6,6,6);
RelativeLayout.LayoutParams timeArrowLP = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
timeArrowLP.addRule(RelativeLayout.RIGHT_OF, R.id.time_tv);
timeArrowLP.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
timeArrowLinearLayout.setLayoutParams(timeArrowLP);
//Recent Time text view
TextView timeTV = new TextView(mContext);
int timeSec = values.get(0);
int timeInMin = Math.round(timeSec / 60);
if (timeInMin == 0) {
String timeText = "due";
timeTV.setText(timeText);
} else {
String timeInMinText = timeInMin + " min";
timeTV.setText(timeInMinText);
}
timeTV.setTextColor(ContextCompat.getColor(mContext, R.color.textColorAccent));
timeTV.setPadding(0,0,16,0);
final TextView remainingTimesTV = new TextView(mContext);
remainingTimesTV.setTextColor(ContextCompat.getColor(mContext, R.color.colorTextSecondary));
remainingTimesTV.setTextSize(11);
remainingTimesTV.setVisibility(View.GONE);
for (int l=1; l< values.size() && l < 4; l++) {
String tempTime;
if (l == 3 || l == values.size() - 1) {
tempTime = values.get(l) / 60 + " min";
}
else
tempTime = values.get(l)/60 + " min, ";
remainingTimesTV.append(tempTime);
}
RelativeLayout.LayoutParams remainingTimeLayoutParams = new RelativeLayout.LayoutParams
(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
remainingTimeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
remainingTimeLayoutParams.addRule(RelativeLayout.BELOW, R.id.time_id);
remainingTimesTV.setLayoutParams(remainingTimeLayoutParams);
timeArrowLinearLayout.addView(timeTV);
if (values.size() > 1) {
//Down arrow button
final ImageView imageButton = new ImageView(mContext);
imageButton.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.arrow_down));
if (isRemainingTimesOpen != null) {
for (String openedRowKey : isRemainingTimesOpen) {
if (openedRowKey.contains(busNameTV.getText().toString()) &&
openedRowKey.contains(destinationNameTV.getText().toString()) &&
openedRowKey.contains(((ViewHolder) holder).stationNameTV.getText().toString())) {
remainingTimesTV.setVisibility(View.VISIBLE);
imageButton.setImageResource(R.drawable.arrow_top);
}
}
}
timeArrowLinearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (remainingTimesTV.getVisibility() == View.GONE) {
isRemainingTimesOpen.add(busNameTV.getText().toString()
+destinationNameTV.getText().toString()
+(((ViewHolder) holder).stationNameTV.getText().toString()));
remainingTimesTV.setVisibility(View.VISIBLE);
imageButton.setImageResource(R.drawable.arrow_down);
imageButton.animate().rotation(180).start();
} else {
remainingTimesTV.setVisibility(View.GONE);
imageButton.setImageResource(R.drawable.arrow_top);
imageButton.animate().rotation(-180).start();
}
}
});
timeArrowLinearLayout.addView(imageButton);
}
RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams2.addRule(RelativeLayout.CENTER_VERTICAL);
timeRelativeLayout.setLayoutParams(layoutParams2);
timeRelativeLayout.addView(timeArrowLinearLayout);
timeRelativeLayout.addView(remainingTimesTV);
View horLine = new View(mContext);
RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1);
horLine.setLayoutParams(layoutParams3);
horLine.setBackgroundColor(ContextCompat.getColor(mContext, R.color.horizontal_line));
horLine.setPadding(0,5,0,5);
relativeLayout.addView(linearLayoutForBusName);
relativeLayout.addView(timeRelativeLayout);
((ViewHolder) holder).cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
mLinearLayout.addView(relativeLayout);
if (t < uniqueBusNamesSet.size()-1) {
mLinearLayout.addView(horLine);
}
}
}
}
}
}
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return mBusArrivalPOJOList.size();
}
private class ViewHolder extends RecyclerView.ViewHolder {
TextView stationNameTV;
TextView timeToWalkToStation;
CardView cardView;
MKLoader progressBar;
ViewHolder(View view, TextView stationNameTV, TextView timeToWalkToStation, CardView cardView,
MKLoader progressBar) {
super(view);
this.stationNameTV = stationNameTV;
this.timeToWalkToStation = timeToWalkToStation;
this.cardView = cardView;
this.progressBar = progressBar;
}
}
}
</code></pre>
| 3 | 14,057 |
Mustache js - template for navigation not loaded sometimes
|
<p>I'm building a site with the help of Mustache js. There is quite a lot of data in the top navigation.</p>
<p>The problem is that approximately half of the time when I load the html, the navigation is not loaded/missing -The output is an empty div :</p>
<pre><code><div id="nav"> </div>
</code></pre>
<p>Here is the html code :</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/lib/mustache.js"></script>
<script type="text/javascript" src="js/templates.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
</head>
<body id="productPage">
<div id="header">
{{{header}}}
<div id="nav">
{{{nav}}}
</div>
</div>
...
...
...
</code></pre>
<p>Here are the templates : </p>
<pre><code>var Templates = {
'header': '<div id="headerWrapper">' +
'<div id="logo" class="left"><img src="images/logo.png" /></div>'+
'<div class="right">'+
'<div class="search"></div>'+
'<div class="login">Login</div>'+
'</div>' +
'<ul class="user_type">'+
'{{#user_type_list}}'+
'<li><a href="{{user_type_element_link}}">{{user_type_element_text}}</a></li>'+
'{{/user_type_list}}'+
'</ul>'+
'<div id="menuWrapper" class="clearfix"></div>' +
'<div class="clearfix"></div> ' +
'</div>',
'nav': '<ul id="menu">' +
'{{#menu_links}}' +
'<li class="menu_top" id="{{menu_id}}">' +
'<a href="{{menu_link}}">{{menu_text}}</a>' +
'<div class="menu_content"></div>' +
'</li>' +
'{{/menu_links}}' +
'</ul>',
'products_services': '<div class="submenu">' +
'<ul class="top_list left">' +
'{{#top_list}}' +
'<li class="top_list_elem">' +
'<a href="{{top_list_link}}">{{top_list_text}}</a>' +
'<div class="extraInfo">' +
'<div class="categories">' +
'<ul>' +
'{{#categories}}' +
'<li class="category">' +
'<div class="cat_name">{{category_name}}</div>' +
'<ul class="subcategories">' +
'{{#subcategories}}' +
'<li class="sub_category"><a href="{{subcategory_link}}">{{subcategory_name}}</a></li>' +
'{{/subcategories}}' +
'</ul>' +
'</li>' +
'{{/categories}}' +
'</ul>' +
'</div>' +
'<div class="teasers">' +
'{{#teasers}}' +
'<div class="teaser">' +
'<a href="{{teaser_link}}">' +
'<img src="images/nav_teaser.jpg"/>' +
'</a>' +
'<div class="caption">' +
'<a href="{{teaser_link}}">{{teaser_caption}}</a>' +
'</div>' +
'</div>' +
'{{/teasers}}' +
'</div>' +
'</div>'+
'</li>' +
'{{/top_list}}' +
'</ul>' +
'{{#appointment}}' +
'<div class="right"><a href="#">Appointment</a></div>' +
'{{/appointment}}' +
'</div>',
'footer': '<div id="footerWrapper" class="clearfix">' +
'<ul>' +
'{{#footer_list}}' +
'<li>' +
'<div class="title">{{footer_title}}' +
'</div>' +
'<ul>' +
'{{#footer_sub_list}}' +
'<li>' +
'<a href="{{footer_sub_link}}" class="{{footer_sub_link_class}}">' +
'{{footer_sub_link_title}}' +
'</a>' +
'</li>' +
'{{/footer_sub_list}}' +
'</ul>' +
'</li>' +
'{{/footer_list}}' +
'</ul>' +
'</div>'
</code></pre>
<p>}</p>
<p>And this is the main js :</p>
<pre><code>jQuery(document).ready(function($){
$.templates = function(page)
{
var plugin = this;
var mustache;
plugin.init = function() {
getHeader();
getNav();
getFooter();
}
var getHeader = function(){
...
};
var getNav = function(){
var template = Templates.nav;
var pages = ["products_services"];
// setTimeout(function() {
$.ajax({
type: "GET",
url: "data/menu.json",
dataType: "JSON",
success: function(data) {
$('#menuWrapper').html(Mustache.render(template, data));
$.each(pages, function(key, val){
var template = Templates[val];
$.ajax({
type: "GET",
url: "data/"+val+".json",
dataType: "JSON",
success: function(data) {
var html = Mustache.render(template, data);
var menuContent = $('#'+val).find('.menu_content');
menuContent.html(html);
menuContent.find('.top_list_elem').bind('mouseenter', function(){
var categories = $(this).find('.categories');
var teasers = $(this).find('.teasers');
var categoriesH = categories.outerHeight(true);
var teasersH = teasers.outerHeight();
var height;
if((categories.width() + teasers.width()) > $(window).width())
height = categoriesH + teasersH;
else
height = Math.max(categoriesH, teasersH);
menuContent.height(height + 50);
});
menuContent.bind('mouseleave', function(){
$(this).height('');
});
}
});
});
}
})/*;},30)*/;
};
var getFooter = function(){
...
};
plugin.init();
}
$.fn.templates = function(page)
{
return this.each(function()
{
if (undefined == $(this).data('templates'))
{
var plugin = new $.templates(page);
$(this).data('templates', plugin);
}
});
}
var body = $('body');
var page = body.attr('id');
body.templates(page);
});
</code></pre>
<p>If it helps with anything.... : If I add the timeOut function that's commented out it works, but when I simulate a slow internet connection, the problem still exists..</p>
<p>The json files:</p>
<p>menu.json:</p>
<pre><code>{
"menu_links": [
{
"menu_link": "#",
"menu_text": "link1",
"menu_id": "link1"
},
{
"menu_link": "#",
"menu_text": "link2",
"menu_id": "link2"
},
{
"menu_link": "#",
"menu_text": "link3",
"menu_id": "link3"
},
{
"menu_link": "#",
"menu_text": "link4",
"menu_id": "link4"
}
]
}
</code></pre>
<p>products_services.json is very long, so here is a snippet :</p>
<pre><code>{
"top_list": [
{
"top_list_link": "#",
"top_list_text": "Top List Text",
"categories": [
{
"category_name": "Name",
"subcategories": [
{
"subcategory_link": "#",
"subcategory_name": "Subcategory name 1"
},
{
"subcategory_link": "#",
"subcategory_name": "Subcategory name 1"
},
{
"subcategory_link": "#",
"subcategory_name": "Subcategory name 1"
},
{
"subcategory_link": "#",
"subcategory_name": "Subcategory name 1"
},
{
"subcategory_link": "#",
"subcategory_name": "Subcategory name 1"
...
...
</code></pre>
<p>I hope I provided enough information.
Thank you for the answers in advance!</p>
| 3 | 7,192 |
Iterate through DataContext items without casting it to a viewmodel type
|
<p>Is their a way to access Items contained in a DataContext without having to explicitly cast it to this <code>ViewModel</code>.</p>
<p>Let's say I'm binding a <code>DataContext</code> on an MvxFrameControl view, then I obtain this DataContext in code-behind once it is binded. It will look like an anonymous object containing a list of Items that are known as the children of this <code>ViewModel</code>. Can I swiss-bind these items, or some properties of this DataContext to another object, and so on?</p>
<p>I.e.</p>
<pre><code>this.DelayBind(() =>
{
var data = DataContext;
// It looks like data contains something called "Items" with a list of children viewModels.
});
</code></pre>
<p>Can I access <code>DataContext.Items[0]</code>, or at least <code>DataContext.Items</code>, and bind it to an observable collection? Then finally swiss-bind some Items to views (<code>MvxFrameControl</code>s) on their <code>DataContext</code>?</p>
<p>So, summary: I'm curious if there is a way to work in code-behind with <code>DataContext</code> and its content so I could create a generic <code>MvxFrameControl</code> that would dispatch the data to custom views based on swiss-binding.</p>
<p>I have <code>ViewModels</code> containing lists of lists, and I want to handle a lot of situations in code-behind as I've experienced a lot of memory problems with <code>MvxListView</code>s containing <code>MvxListView</code>s.</p>
<p>[Edit]</p>
<p>This is actually what I was doing in my code that led me to think I should completely redefine how bindings are done. I'll write a minimal fake axml:</p>
<p>// Warning to anyone: this is a fake layout, don't use that</p>
<p>view_myactivity_layout.axml :</p>
<pre><code><LinearLayout>
<MvxListView
android:MvxItemTemplate="@layout/food_category_item"
local:MvxBind="ItemsSource FoodCategories" />
</LinearLayout>
</code></pre>
<p>food_category_item.axml:</p>
<pre><code><LinearLayout>
<TextView
local:MvxBind="Text Category" />
<MvxListView
android:MvxItemTemplate="@layout/list_of_food_for_a_category_item"
local:MvxBind="ItemsSource FoodList" />
</LinearLayout>
</code></pre>
<p>list_of_food_for_a_category_item.axml:</p>
<pre><code><LinearLayout>
<TextView
local:MvxBind="Text NameOfThatFood" />
<MvxListView
android:MvxItemTemplate="@layout/list_of_colors_for_that_food_item"
local:MvxBind="ItemsSource FoodList" />
</LinearLayout>
</code></pre>
<p>[Etc...]</p>
<p>Nesting binded controls works well, but there are tons of GC happening when scrolling. So that's why I was thinking about making my own binding pattern using reflection for this case.</p>
| 3 | 1,029 |
How to allow scrolling on a modal window with open dropdown?
|
<p>I use Material UI Dialog and use property scroll="body" for modal window. I have issue when dropdown is open a can't scroll modal window. How to allow scrolling in this case?</p>
<p><a href="https://codesandbox.io/s/material-demo-forked-gy2ns?file=/demo.tsx:1283-2699" rel="nofollow noreferrer">https://codesandbox.io/s/material-demo-forked-gy2ns?file=/demo.tsx:1283-2699</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> <Dialog
open={open}
onClose={handleClose}
scroll={scroll}
aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description"
>
<DialogTitle id="scroll-dialog-title">Subscribe</DialogTitle>
<DialogContent dividers={scroll === "paper"}>
<DialogContentText
id="scroll-dialog-description"
ref={descriptionElementRef}
tabIndex={-1}
>
<Select labelId="demo-simple-select-label" id="demo-simple-select">
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
<br />
{[...new Array(50)]
.map(
() => `Cras mattis consectetur purus sit amet fermentum.
Cras justo odio, dapibus ac facilisis in, egestas eget quam.
Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et.`
)
.join("\n")}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
Cancel
</Button>
<Button onClick={handleClose} color="primary">
Subscribe
</Button>
</DialogActions>
</Dialog></code></pre>
</div>
</div>
</p>
| 3 | 1,066 |
C++ - BST segmentation fault upon deletion of node with 2 children
|
<h2>Segmentation faults when trying to delete a node with 2 children</h2>
<p>So i've recently started studying algorithms and have been working a bit on binary search trees, basing my C++ code on the pseudo code taken from the book <code>Introduction to Algorithms</code>. I'm however having large issues with it's delete function for it's binary search tree. The code for the delete function is:</p>
<pre><code>void bstDelete(BSTtree &bst, int key)
{
treeNode *z = findNode(bst, key);
if (z != nullptr)
{
treeNode *y = z;
treeNode *x;
if (z->left == bst.NIL)
{
x = z->right;
transplant(bst, z, z->right);
}
else if (z->right == bst.NIL)
{
x = z->left;
transplant(bst, z, z->left);
}
else
{
y = treeMin(z->right);
x = y->right;
if (y->parent == z)
{
x->parent = y;
}
else
{
transplant(bst, y, y->right);
y->right = z->right;
y->right->parent = y;
}
transplant(bst, z, y);
y->left = z->left;
y->left->parent = y;
}
}
}
</code></pre>
<p>Transplant function:</p>
<pre><code>void transplant(BSTtree &bst, treeNode *u, treeNode *v)
{
if (u->parent == bst.NIL)
{
v->right = u->right;
v->left = u->left;
v->right->parent = v;
v->left->parent = v;
bst.root = v;
}
else if (u == u->parent->left)
{
u->parent->left = v;
}
else
{
u->parent->right = v;
}
v->parent = u->parent;
}
</code></pre>
<p>I'm not expecting someone to debug my code, I've just sat pretty much for multiple days trying to figure it out, looking at other people's versions of the delete function trying to understand why mine doesn't work. There's also the issue of why the book's own delete function doesn't do it's job, or if it's just me who's at fault. I would really appreciate if someone could take a look at this. I've been looking around quite a lot and still haven't found anyone having issues with this.</p>
<p><strong>Edit</strong><br>
Added other parts related to the code</p>
<pre><code>treeNode *findNode(RBtree bst, int key)
{
treeNode *z = nullptr;
treeNode *x = bst.root;
treeNode *y = bst.NIL;
while (x != nullptr && x != bst.NIL)
{
y = x;
if (key < x->value)
{
x = x->left;
}
else
{
x = x->right;
}
if (y->value == key)
{
break;
}
}
if (y->value == key)
{
z = y;
}
return z;
}
</code></pre>
<pre><code>treeNode *treeMin(treeNode *root)
{
treeNode *treeNode = root;
while (treeNode->left != nullptr)
{
treeNode = treeNode->left;
}
return treeNode;
}
</code></pre>
<pre><code>struct treeNode
{
treeNode *left;
treeNode *right;
treeNode *parent;
std::string color;
int value;
treeNode() : left(nullptr), right(nullptr), parent(nullptr) {}
treeNode(int paramValue) : left(nullptr), right(nullptr), parent(nullptr), value(paramValue) {}
treeNode(int paramValue, treeNode *parent) : value(paramValue), parent(parent) {}
};
</code></pre>
<pre><code>struct BSTtree
{
treeNode *root;
treeNode *NIL;
BSTtree()
{
NIL = new treeNode();
root = nullptr;
}
};
</code></pre>
<p>Reason i have with NIL is so that i can easier make this into an RB tree later on. The smallest scale needed to cause a crash is a 3 node tree, where you have a root, and it has a right and left child. That way you push the delete function into case three, where it has to find a successor and transplant it. It's in this part of the delete-function which it crashes and gives me a segmentation-fault.</p>
<p><strong>Edit 2</strong><br>
Code which causes a crash:</p>
<pre><code>int main()
{
BSTtree bst;
bstInsert(bst, 5);
bstInsert(bst, 7);
bstInsert(bst, 2);
bstDelete(bst, 5);
}
</code></pre>
<p>Insert function</p>
<pre><code>void bstInsert(BSTtree &bst, int key)
{
treeNode *z = new treeNode(key);
treeNode *y = bst.NIL;
treeNode *x = bst.root;
while (x != nullptr && x != bst.NIL)
{
y = x;
if (z->value < x->value)
{
x = x->left;
}
else
{
x = x->right;
}
}
z->parent = y;
if (y == bst.NIL)
{
bst.root = z;
z->parent = bst.NIL;
}
else if (z->value < y->value)
{
y->left = z;
}
else
{
y->right = z;
}
z->left = bst.NIL;
z->right = bst.NIL;
}
</code></pre>
<p>The nullptr is not a problem here as it's resolved in the insert function, as you can see if it's root, root is given <code>bst.NIL</code> as it's parent. I agree it's error prone to have this construction, it's only there to be able to be used for red and black trees which uses a specific NIL node instead of nullptr.</p>
| 3 | 2,531 |
How to avoid putting dll.config files containing EF configuration into bin output directory?
|
<p>In my build artifacts for .NET(C#) app I have a lot of <code>dll.config</code> files. I don't know why they're put there. I looked at all my <code>packages.config</code>, <code>app.config</code>, <code>web.config</code> files and they have <code>Do Not Copy</code> setting in their property. I can't see any settings that would prevent these config files to be put in the output directories?</p>
<p>How I can prevent their existence?</p>
<p>The only thing I can find in these files is EF stuff:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxx requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.OData.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.12.0.0" newVersion="6.12.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.OData.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.12.0.0" newVersion="6.12.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Spatial" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.12.0.0" newVersion="6.12.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
</code></pre>
| 3 | 1,458 |
TCPDF table header apply a different margin on next page + closee table before page break
|
<p>The code used to print the pdf is as follows:</p>
<p><strong>PdfController</strong> :</p>
<pre><code>/**
* @Route("/{id}", name="api_article_pdf", methods={"GET"})
*/
public function gepdf2html($id)
{
// create new PDF document
$pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('OPAL TPE');
$pdf->SetTitle('Articles');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE . ' 001', PDF_HEADER_STRING, array(0, 64, 255), array(0, 64, 128));
$pdf->setFooterData(array(0, 64, 0), array(0, 64, 128));
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// ---------------------------------------------------------
// set default font subsetting mode
$pdf->setFontSubsetting(true);
// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 14, '', true);
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();
// set text shadow effect
$pdf->setTextShadow(array('enabled' => true, 'depth_w' => 0.2, 'depth_h' => 0.2, 'color' => array(196, 196, 196), 'opacity' => 1, 'blend_mode' => 'Normal'));
// $id document
$id_d= substr($id, 0,-7);
$id=$id_d-5;
$id=$id/7;
// Set some content to print
// $em = $this->getDoctrine()->getManager();
$query2= $this->em->createQuery('SELECT
a.libelle as libelle,
a.description as desc,
a.prixVenteHt as prixHt,
a.prixVenteTtc as prixTtc
FROM
App\Entity\Dossier\Article as a
WHERE a.id = :id
');
$query2->setParameter("id", $id);
$data = $query2->getResult();
$html = $this->renderView('test.html.twig',
['data' => $data]);
// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
// ---------------------------------------------------------
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
return $pdf->Output('example_001.pdf', 'I');
</code></pre>
<p>and my <strong>test.html.twig</strong> code :</p>
<pre><code><html>
<head>
</head>
<body>
<table nobr="true" cellspacing="0" cellpadding="1" border="1">
<thead>
<tr style="background-color:silver;"><th>Libelle</th>
<td>Description</td>
<td>Prix V HT</td>
<td>Prix V TTC</td>
</tr>
</thead>
<tbody>
{% for d in data %}<br>
<tr>
<td>{{ d.libelle }}</td>
<td>{{ d.desc }}</td>
<td>{{ d.prixHt }}</td>
<td>{{ d.prixTtc }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</code></pre>
<p></p>
<p>On the first page, everything works fine, but after the first page break the table header floats to the left side.</p>
<p>I tried to fix thead width to resolve the issue, but that didn't works.</p>
<p>I tried very solution on stack or google with no closer result </p>
<p>Another question please : how could i close my tablee before evreeey page break (2)</p>
<p><a href="https://i.stack.imgur.com/Ufnmh.png" rel="nofollow noreferrer">PDF SCREENSHOT</a></p>
<p>Thank you so much :) </p>
| 3 | 2,166 |
<video> causes many requests *before being clicked*
|
<p>Even with preload disabled, the most simple <code><video></code> tag</p>
<pre><code><video src="video.mp4" preload="none"></video>
</code></pre>
<p>will cause <strong>10</strong> requests to the server <em>before being clicked</em>:</p>
<pre><code>89.212.77.133 - - [01/Dec/2010:11:48:43 +0100] "GET /temp/html5-video-requests-test/one-noposter.html HTTP/1.1" 200 267 "-" "Mozilla/5.0 (iPhone Simulator; U; CPU iPhone OS 4_0_2 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A400 Safari/6531.22.7"
89.212.77.133 - - [01/Dec/2010:11:48:43 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 2 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:43 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 8621463 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:43 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 101783 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:44 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 8499743 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:44 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 304 - "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:44 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 2 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:44 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 8621463 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:44 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 101783 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:45 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 8505535 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
89.212.77.133 - - [01/Dec/2010:11:48:44 +0100] "GET /temp/html5-video-requests-test/video.mp4 HTTP/1.1" 206 8519680 "-" "AppleCoreMedia/1.0.0.8A400 (iPhone Simulator; U; CPU OS 4_0_2 like Mac OS X; en_us)"
</code></pre>
<p>Setting a poster reduces this to poster + approx. 3 requests.</p>
<p>Since I have many videos on a page, I don't want the browser to make <em>any</em> requests until the video is clicked.</p>
<p>What more can I do besides set a poster and disable preload?</p>
| 3 | 1,241 |
Can someone explain that why the BehaviorSubject result like this?
|
<p>I wrote a service contain a BehaviorSubject called loginStatus and a function to return that.</p>
<pre><code>private loginStatus = new BehaviorSubject<boolean>(false);
getLoginStatus(): Observable<boolean> {
return this.loginStatus;
}
</code></pre>
<p>Then I subscribe it in other component's DOM with a async pipe in 4 different div, I just commented the shareReplay to show what I'm wondering.</p>
<pre><code> loginStatus$ = this.authService.getLoginStatus().pipe(
switchMap(res => {
if (!res) { return this.authService.isLoggedIn(); }
else { return of(res); }
}),
tap(res => console.log('tap: ' + res)),
//shareReplay(1),
);
</code></pre>
<p>The isLoggedIn is a http request to check am I logged in or not, I check the loginStatus value in the switchMap, if it's false then call the isLoggedIn</p>
<pre><code>isLoggedIn(): Observable<boolean> {
console.log('called isLoggedIn');
return this.httpService.get('/auth/isLoggined').pipe(
map(res => {
console.log('isLoggedIn res: ' + JSON.stringify(res));
if (res) {
this.loginStatus.next(true);
this.firstName = res.first_name;
this.lastName = res.last_name;
this.tel = res.tel;
return 'fool';
} else {
this.clearAll();
return false;
}
}),
</code></pre>
<p>Finally It's my console result:</p>
<pre><code>called isLoggedIn
called isLoggedIn
called isLoggedIn
called isLoggedIn
</code></pre>
<p>isLoggedIn called 4 times because of my 4 async pipe, and the loginStatus is false.</p>
<p>while the first http request response, I got a json object like {first_name:xxx, last_name:yyy, 1234}, so I push the true to the loginStatus and return a 'fool' to the further operator.</p>
<p>I suppose that I will get the fool in the tap operator of the loginStatus$, but it doesn't.</p>
<pre><code>isLogedIn res: {"logined":true,"first_name":"xxx","last_name":"yyy","tel":"1234"}
tap: true
tap: true
tap: true
tap: true
</code></pre>
<p>I only got the response of the first isLoggedIn request, the other 3 is lost.
And I never get the fool, all the async pipe get the true from the loginStatus BehaviorSubject I guess.</p>
<p>Then I commented the this.loginStatus.next(true) in the isLoggedIn function to compare the result.</p>
<pre><code>isLogedIn res: {"logined":true,"first_name":"xxx","last_name":"yyy","tel":"1234"}
tap: fool
isLogedIn res: {"logined":true,"first_name":"xxx","last_name":"yyy","tel":"1234"}
tap: fool
isLogedIn res: {"logined":true,"first_name":"xxx","last_name":"yyy","tel":"1234"}
tap: fool
isLogedIn res: {"logined":true,"first_name":"xxx","last_name":"yyy","tel":"1234"}
tap: fool
</code></pre>
<p>It's result with this which is what I prefered, I called 4 times, so I got 4 responses and It pass the fool to the tap 4 times.</p>
<p>I wanna know why the other reponse is lost when I change the BehaviorSubject in the process of the first subscription.<br />
And why all 4 subscription get the true value, I suppose at least the first time will get the fool.<br />
Does it means the BehaviorSubject will cancel the further process when change rather than complete it?</p>
| 3 | 1,342 |
Unexpected results for yaml-cpp comparisons
|
<p>Consider the following code (yamltest.cpp):</p>
<pre><code>#include <yaml-cpp/yaml.h>
#include <iostream>
#include <string>
int main() {
std::string val = "[1, 2, 3]";
YAML::Node yn0 = YAML::Load(val);
YAML::Node yn1 = YAML::Load(val);
std::cout << "===== yn0 =====\n" << yn0 << std::endl;
std::cout << "\n" << std::endl;
std::cout << "===== yn1 =====\n\n" << yn1 << std::endl;
std::cout << std::boolalpha;
std::cout << "yn0 == yn0: " << (yn0==yn0) << std::endl;
std::cout << "yn1 == yn1: " << (yn1==yn1) << std::endl;
std::cout << "yn0 == yn1: " << (yn0==yn1) << std::endl;
std::cout << "yn1 == yn0: " << (yn1==yn0) << std::endl;
std::cout << "YAML::Load(val) == YAML::Load(val): " << (YAML::Load(val)==YAML::Load(val)) << "\n" << std::endl;
std::cout << "yn0 != yn0: " << (yn0!=yn0) << std::endl;
std::cout << "yn1 != yn1: " << (yn1!=yn1) << std::endl;
std::cout << "yn0 != yn1: " << (yn0!=yn1) << std::endl;
std::cout << "yn1 != yn0: " << (yn1!=yn0) << std::endl;
std::cout << "YAML::Load(val) != YAML::Load(val): " << (YAML::Load(val)!=YAML::Load(val)) << std::endl;
std::cout << std::noboolalpha;
return 0;
}
</code></pre>
<p>Along with its associated Makefile:</p>
<pre><code>yt:
g++ -g -Wall yamltest.cpp -o yt -lyaml-cpp
clean:
rm yt
</code></pre>
<p>Running it produces the following results:</p>
<pre><code>$ ./yt
===== yn0 =====
[1, 2, 3]
===== yn1 =====
[1, 2, 3]
yn0 == yn0: true
yn1 == yn1: true
yn0 == yn1: false
yn1 == yn0: false
YAML::Load(val) == YAML::Load(val): false
yn0 != yn0: false
yn1 != yn1: false
yn0 != yn1: false
yn1 != yn0: false
YAML::Load(val) != YAML::Load(val): false
</code></pre>
<p>I expected all of the <code>==</code> tests to return <code>true</code> and all of the <code>!=</code> tests to return <code>false</code>, but this is clearly not happening. So, is this the correct way to compare YAML-CPP objects to test for equivalence? If not, what is the correct way?</p>
<p>This is running on CentOS 7.x and GCC 9.2.0.</p>
| 3 | 1,154 |
OS X Crash: pointer being freed was not allocated
|
<p>Need a help to understand the real reason of a crash. I've made the app that should work 24/7. It reads and prepares some data from an equipment and creates a web-server to send data to the probe.
The crash happens after a various amount of time, so I can't really reproduce it in the simulator.</p>
<p>Here are the last crash file details:</p>
<blockquote>
<p>Time Awake Since Boot: 110000 seconds</p>
<p>System Integrity Protection: enabled</p>
<p>Crashed Thread: 37 Dispatch queue: com.apple.root.default-qos</p>
<p>Exception Type: EXC_CRASH (SIGABRT)</p>
<p>Exception Codes: 0x0000000000000000, 0x0000000000000000</p>
<p>Exception Note: EXC_CORPSE_NOTIFY</p>
<p>Dispatch Thread Soft Limit Reached: 64 (too many dispatch threads blocked in synchronous operations)</p>
<p>Application Specific Information:
abort() called</p>
<p>*** error for object 0x247032000: pointer being freed was not allocated</p>
</blockquote>
<p>Details for Thread 37:</p>
<blockquote>
<p>Thread 37 Crashed:: Dispatch queue: com.apple.root.default-qos</p>
<p>0 libsystem_c.dylib 0x00007fff8dab3298 usleep$NOCANCEL + 0</p>
<p>1 libsystem_c.dylib 0x00007fff8dae16e9 abort + 139</p>
<p>2 libsystem_malloc.dylib 0x00007fff965fe041 free + 425</p>
<p>3 libswiftCore.dylib 0x0000000106fed219 $Ss19_SwiftStringStorageCfD + 9</p>
<p>4 libswiftCore.dylib 0x0000000106ffba00 _swift_release_dealloc + 16</p>
</blockquote>
<p>...</p>
<blockquote>
<p>46 org.cocoapods.GCDWebServer 0x0000000106c67316 -[GCDWebServerConnection(Subclassing) processRequest:completion:] + 128</p>
<p>47 org.cocoapods.GCDWebServer 0x0000000106c6392e -[GCDWebServerConnection _startProcessingRequest] + 146</p>
<p>48 org.cocoapods.GCDWebServer 0x0000000106c64e13 __45-[GCDWebServerConnection _readRequestHeaders]_block_invoke + 1781</p>
<p>49 org.cocoapods.GCDWebServer 0x0000000106c65935 __64-[GCDWebServerConnection(Read) readHeaders:withCompletionBlock:]_block_invoke + 290</p>
<p>50 org.cocoapods.GCDWebServer 0x0000000106c65613 __68-[GCDWebServerConnection(Read) readData:withLength:completionBlock:]_block_invoke + 307</p>
<p>51 libdispatch.dylib 0x00007fff8e73c7a8 __dispatch_read_block_invoke_252 + 39</p>
<p>52 libdispatch.dylib 0x00007fff8e72a93d _dispatch_call_block_and_release + 12</p>
<p>53 libdispatch.dylib 0x00007fff8e71f40b _dispatch_client_callout + 8</p>
<p>54 libdispatch.dylib 0x00007fff8e72329b _dispatch_root_queue_drain + 1890</p>
<p>55 libdispatch.dylib 0x00007fff8e722b00 _dispatch_worker_thread3 + 91</p>
<p>56 libsystem_pthread.dylib 0x00007fff8ea934de _pthread_wqthread + 1129</p>
<p>57 libsystem_pthread.dylib 0x00007fff8ea91341 start_wqthread + 13</p>
</blockquote>
<p>Code:</p>
<p>This is a code of a singletone that handles the web-server (GCDWebServer). It reads stored in memory data according to an id in an http query</p>
<pre><code>private let queue = DispatchQueue(label: "gcdwebserver_queue")
private func setupServer(){
webServer.delegate = self
webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self) { (req, completion) in
if let resp = self.response(for: req) {
return completion(resp)
}
}
queue.async {
self.webServer.start(withPort: 8521, bonjourName: "GCD Web Server")
}
}
</code></pre>
<p>And here is the code of a singleton that calls modbus (C Modbus library) connection (every 30 sec) to a list of devices and reads data:</p>
<pre><code>private let modbusQueue = DispatchQueue(label: "modbus_queue")
private func initiateTimer() {
polling()
timer?.invalidate()
if #available(OSX 10.12, *) {
timer = Timer.scheduledTimer(withTimeInterval: pollingInterval, repeats: true) { (_) in
self.polling()
}
} else {
timer = Timer.scheduledTimer(timeInterval: pollingInterval, target: self, selector: #selector(polling), userInfo: nil, repeats: true)
}
}
@objc private func polling() {
for device in self.devices {
if !device.isInProcess && device.isEnabled {
self.modbusQueue.async {
self.connectAndReadValues(device: device)
}
}
}
}
private func connectAndReadValues(device: Device) {
device.isInProcess = true
let connect = device.modbus.connect()
//handling connection status
//...
readValues(forDevice: device)
}
private func readValues(forDevice device: Device){
//some constants
do {
let registers = try device.modbus.readRegisters(from: startAddress, count: registersCount)
device.readState = .success
device.modbus.close()
//parse and save data to the app memory just as a dictionary. It saves only one small dictionary per device
parseRegisters(controllerIP: device.modbus.host, vendor: vendor, registers: registers, startAdd: startAddress)
} catch let error {
//handling errors
}
//refreshing interface in the main queue
}
</code></pre>
| 3 | 2,166 |
SOAP Webservices
|
<p>I have a wsdl containing SAOP Header and SOAP Body. I generated client with eclipse and APACHE CXF and sent request. But request is failing saying Header is missed or invalid.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
</code></pre>
<p> </p>
<pre><code><types>
<xsd:schema>
<xsd:import
namespace="http://finservice.cl.com/Services/financier/Operational/Messages/Request"
schemaLocation="financierRequest.xsd"/>
<xsd:import
namespace="http://finservice.cl.com/Services/financier/Operational/Messages/Response"
schemaLocation="financierResponse6.xsd"/>
<xsd:import namespace="http://finservice.cl.com/Services/Faults"
schemaLocation="finserviceFaults.xsd"/>
<xsd:import namespace="http://www.cl.com/Services/SOAPHeaders"
schemaLocation="CLSoapHeaders.xsd"/>
<xsd:import
namespace="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
schemaLocation="oasis-200401-wss-wssecurity-secext-1.0.xsd"/>
</xsd:schema>
</types>
<message name="WS-Security-SOAPHeader">
<part element="wssec:Security" name="Security"/>
</message>
<message name="CLSOAPHeader">
<part element="hdr_ns:RequestContextHeader" name="requestHeader"/>
<part element="hdr_ns:ProcessingNodesHeader" name="processingNodesHeader"/>
</message>
<message name="financierRequest">
<part element="req_ns:financierRequestElement" name="financierRequestElement"/>
</message>
<message name="financierResponse">
<part element="res_ns:financierResponseElement" name="financierResponseElement"/>
</message>
<message name="Fault_Exception">
<part element="fault_ns:Fault" name="fault"/>
</message>
<portType name="finServicePortType">
<operation name="getFinanciers">
<input message="tns:financierRequest"/>
<output message="tns:financierResponse"/>
<fault message="tns:Fault_Exception" name="Fault_Exception"/>
</operation>
</portType>
<binding name="finServiceBinding" type="tns:finServicePortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="getFinanciers">
<soap:operation soapAction=""/>
<input>
<soap:body parts="financierRequestElement" use="literal"/>
<soap:header message="tns:CLSOAPHeader" part="requestHeader" use="literal"/>
<!-- soap:header message="tns:CLSOAPHeader" part="processingNodesHeader" use="optional"/-->
<soap:header message="tns:WS-Security-SOAPHeader" part="Security" use="literal"/>
</input>
<output>
<soap:body use="literal"/>
<soap:header message="tns:CLSOAPHeader" part="processingNodesHeader" use="literal"/>
<soap:header message="tns:WS-Security-SOAPHeader" part="Security" use="literal"/>
</output>
<fault name="Fault_Exception">
<soap:fault name="Fault_Exception" use="literal"/>
</fault>
</operation>
</binding>
<service name="financierService_v4">
<port binding="tns:finServiceBinding" name="finServicePort">
<soap:address location="http://finservice.qtcorpCL.cl.com:20021/finservService"/>
</port>
</service>
</code></pre>
<p></p>
<p>Can any one guide me how to write client for this wsdl?
How to attach header for this.</p>
| 3 | 1,716 |
WPF:DataGridTemplateColumn on Windows server 2003/2008
|
<p>I have a <code>DataGridTemplateColumn</code> :</p>
<pre><code><DataGridTemplateColumn CellStyle="{x:Null}" Width="85" Header="{Extentions:DisplayName Type=Type:StandardClass, PropertyName=ProductKind}">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding ElementName=viewSourceDataGrid, Path=DataContext.ProductKindCollection}"
DisplayMemberPath="Title" Style="{x:Null}"
SelectedValue="{Binding ProductKind, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding ProductKind.Title, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</code></pre>
<p>And also tried :</p>
<pre><code><DataGridComboBoxColumn Header="{Extentions:DisplayName Type=Type:StandardClass, PropertyName=ProductKind}"
DisplayMemberPath="Title"
SelectedItemBinding="{Binding ProductKindID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True,ValidatesOnDataErrors=True}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource EditBaseStyle}">
<Setter Property="ItemsSource" Value="{Binding ElementName=viewSourceDataGrid, Path=DataContext.ProductKindCollection}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource EditBaseStyle}">
<Setter Property="ItemsSource" Value="{Binding ElementName=viewSourceDataGrid, Path=DataContext.ProductKindCollection}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</code></pre>
<p>Everything works fine on win 7 but tested them on win server 2008 and 2003 and the result :</p>
<p><img src="https://i.stack.imgur.com/pkMwf.png" alt="DataGridComboBoxColumn"></p>
<p>I removed styles of cell , And DataGrid but still
(as you see) <code>ComboBox</code> items doesn't appear </p>
| 3 | 1,412 |
Passing a Datatable From One Form to Another Form
|
<p>I have a form1 and form2. Form2 is opened from form1, it has a dgv after filling it, it's copied to a datatable on a click button, and form2 is closed or visible = false. I passed the datatable to form1 but it's giving me a null reference. Here is my code in form2:</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
perclothesdescriptionDT = new DataTable();
foreach (DataGridViewColumn col in dataGridView3.Columns)
{
perclothesdescriptionDT.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView3.Rows)
{
DataRow dRow = perclothesdescriptionDT.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
perclothesdescriptionDT.Columns.RemoveAt(0);
perclothesdescriptionDT.Rows.Add(dRow);
}
this.Visible = false;
}
public DataTable mydt
{
get
{
return perclothesdescriptionDT;
}
}
</code></pre>
<p>In form1:</p>
<pre><code>form2= new Form2();
cmd1.CommandText = "insert into [dbo].[personClothesDesc](upperPart, lowerPart, belt, socks, shoes, differentSigns) values (@upperPart, @lowerPart, @belt, @socks, @shoes, @differentSigns)";
for (int i = 0; i < form2.mydt.Rows.Count; i++)
{
cmd1.Parameters.Clear();
cmd1.Parameters.AddWithValue("@upperPart", form2.mydt.Rows[i].ItemArray.GetValue(5).ToString());
cmd1.Parameters.AddWithValue("@lowerPart", form2.mydt.Rows[i].ItemArray.GetValue(4).ToString());
cmd1.Parameters.AddWithValue("@belt", form2.mydt.Rows[i].ItemArray.GetValue(3).ToString());
cmd1.Parameters.AddWithValue("@socks", form2.mydt.Rows[i].ItemArray.GetValue(2).ToString());
cmd1.Parameters.AddWithValue("@shoes", form2.mydt.Rows[i].ItemArray.GetValue(1).ToString());
cmd1.Parameters.AddWithValue("@differentSigns", form2.mydt.Rows[i].ItemArray.GetValue(0).ToString());
cmd1.ExecuteNonQuery();
}
</code></pre>
| 3 | 1,258 |
PHP Upload - how to get the relative path of an uploaded file?
|
<p>I have my videos in a folder on my desktop:</p>
<pre><code>/home/john/Desktop/Samples/Vids/small.mp4
</code></pre>
<p>How can I get this file path from upload or other ways?</p>
<p>This is my html form:</p>
<pre><code><form class="form-submission" method="post" action="upload.php" enctype= "multipart/form-data">
<input type="file" name="upload[]" id="input-file" multiple required>
<button type="submit" class="btn btn-default no-gradient">Submit</button>
</form>
</code></pre>
<p>upload.php:</p>
<pre><code><?php
print_r($_FILES);
</code></pre>
<p>Result:</p>
<pre><code>Array
(
[upload] => Array
(
[name] => Array
(
[0] => small.mp4
)
[type] => Array
(
[0] => video/mp4
)
[tmp_name] => Array
(
[0] => /tmp/php1KNwas
)
[error] => Array
(
[0] => 0
)
[size] => Array
(
[0] => 383631
)
)
)
</code></pre>
<p>But there is no info of the path - <code>/home/john/Desktop/Samples/Vids/small.mp4</code></p>
<p>Any ideas how can I get it?</p>
<p>I need to find the video file path so I can send it to my youtube channel:</p>
<pre><code>// REPLACE this value with the path to the file you are uploading.
$videoPath = "/home/john/Desktop/Samples/Vids/small.mp4";
....
$media->setFileSize(filesize($videoPath));
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
</code></pre>
<p>The entire video uploading code is from <a href="https://developers.google.com/youtube/v3/code_samples/php#upload_a_video" rel="nofollow">google's</a>.</p>
| 3 | 1,049 |
Syntax errors in vue.js code for autocomplete
|
<p>hi I'm trying to <a href="https://vuejsexamples.com/an-autocomplete-typeahead-component-for-vue-2-and-bootstrap-4/" rel="nofollow noreferrer">autocomplete/typeahead component for Vue 2 and Bootstrap 4</a>
This is my code.</p>
<pre><code><html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<link href="https://unpkg.com/vue-bootstrap-typeahead/dist/VueBootstrapTypeahead.css" rel="stylesheet">
</head>
<body>
<div id="container">
<vue-bootstrap-typeahead
v-model="query"
:data="['Canada', 'USA', 'Mexico']" />
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.11.10/vue.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/vue-bootstrap-typeahead"></script>
<script>
import VueBootstrapTypeahead from 'vue-bootstrap-typeahead';
Vue.component('vue-bootstrap-typeahead', VueBootstrapTypeahead);
new Vue({
el: '#container',
data: {
value: '',
},
});
</script>
</body>
</html>
</code></pre>
<p>Unfortunately this is not working due to following errors.</p>
<blockquote>
<p><strong>SyntaxError: import declarations may only appear at top level of a module</strong></p>
<p>Source map error: request failed with status 404 Resource URL:
<a href="https://unpkg.com/vue-bootstrap-typeahead" rel="nofollow noreferrer">https://unpkg.com/vue-bootstrap-typeahead</a> Source Map URL:
VueBootstrapTypeahead.umd.min.js.map</p>
</blockquote>
<p>It would be great if someone can help me on this.</p>
| 3 | 1,113 |
Unexplained halt of execution
|
<p>I am working on a Java process that contains 2 threads: one for reading a file's contents and adding them in one shared blocking queue; and one for retrieving the lines from the blocking queue and sending them through the network (under a specified send rate). The two classes I have are the following:</p>
<p><strong>Updated Code below</strong></p>
<p>Producer Thread:</p>
<pre><code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
public class SourceFileProducer implements Runnable {
private File file;
private BufferedReader reader;
private ArrayBlockingQueue<String> buffer;
private String fileName;
private String endMarker;
public SourceFileProducer(ArrayBlockingQueue<String> buffer,
String endMarker, String fileName) {
this.buffer = buffer;
this.endMarker = endMarker;
file = new File(fileName);
if(file.exists()) {
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
this.fileName = fileName;
}
@Override
public void run() {
System.out.println("SourceFileProducer thread-" + Thread.currentThread().getId() + " initiating with source file: " + fileName);
String line = "";
try {
while((line = reader.readLine()) != null) {
try {
buffer.put(line);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
buffer.put(endMarker);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("SourceFileProducer thread-" + Thread.currentThread().getId() + " scanned and buffered the whole file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>and the Consumer thread:</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
public class SourceFileConsumer implements Runnable {
private ArrayBlockingQueue<String> buffer;
private BufferedReader socketInput;
private PrintWriter socketOutput;
private Socket client;
private ServerSocket serverSocket;
private long checkpoint[] = null;
private int rate[] = null;
private String endMarker;
public SourceFileConsumer(ArrayBlockingQueue<String> buffer, String endMarker,
ServerSocket serverSocket, Socket client, long checkpoint[], int rate[]) {
this.buffer = buffer;
this.endMarker = endMarker;
this.client = client;
try {
socketOutput = new PrintWriter(client.getOutputStream(), true);
socketInput = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
this.checkpoint = new long[checkpoint.length];
this.rate = new int[rate.length];
for(int i = 0; i < checkpoint.length; i++) {
this.checkpoint[i] = checkpoint[i];
this.rate[i] = rate[i];
}
this.serverSocket = serverSocket;
}
@Override
public void run() {
String line = null;
long start = System.currentTimeMillis();
int index = 0;
boolean fileScanFlag = true;
while(fileScanFlag) {
long startTimestamp = System.currentTimeMillis();
long interval = (startTimestamp - start) / 1000L;
if(interval >= checkpoint[index]) {
if(index < checkpoint.length - 1) {
if(interval >= checkpoint[index + 1]) {
index += 1;
System.out.println("SourceFileConsumer thread-" + Thread.currentThread().getId() +
" progressed to checkpoint " + index + " with rate: " + rate[index]);
}
}
}
int counter = 0;
while(counter < rate[index]) {
try {
line = buffer.take();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if(line == endMarker) {
fileScanFlag = false;
break;
}
if(socketOutput != null && socketOutput.checkError()) {
System.out.println("SourceFileConsumer Thread-" + Thread.currentThread().getId() + " detected broken link...");
try {
client = serverSocket.accept();
socketOutput = new PrintWriter(client.getOutputStream(), true);
socketInput = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch(IOException e) {
e.printStackTrace();
}
System.out.println("SourceFileConsumer Thread-" + Thread.currentThread().getId() + " re-established connection...");
}
if(socketOutput != null)
socketOutput.println(line);
counter += 1;
}
long endTimestamp = System.currentTimeMillis();
if(endTimestamp - startTimestamp <= 1000) {
System.out.println("thread-" + Thread.currentThread().getId() + " input rate: " + counter +
", wait time: " + (1000 - (endTimestamp - startTimestamp)));
try {
Thread.sleep((1000 - (endTimestamp - startTimestamp)));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(socketInput != null && socketOutput != null && client != null) {
try {
socketInput.close();
socketOutput.close();
client.close();
} catch(IOException e) {
e.printStackTrace();
}
}
System.out.println("SourceFileConsumer Thread-" + Thread.currentThread().getId() + " transfer complete.");
}
}
</code></pre>
<p>The problem is that, after a while, both threads hang and no tuples are sent. When I run a top command in my Linux machine, I see that the Java process, in which the two threads are running in, uses a really small amount of CPU time. Why is this happening? Is this a problem with starvation? I think that starvation can be avoided by using the <code>LinkedBlockingQueue</code>.</p>
<p>Any hints?</p>
<p>Thanks,
Nick</p>
| 3 | 3,166 |
setImageResource causing crash of application
|
<p>i'm trying to make a button that when clicked on it picks a random card from a set of card and show it into an ImageView.
To do this I have a Card class for their value and their id (the image card name in drawable).</p>
<pre><code>public class Carte {
int valeur;
static String nomCarte;
public Carte(int valeur, String nomImage) {
valeur = this.valeur;
nomCarte = this.nomCarte;
}
public static String getImageId() {
return nomCarte;
}
}
</code></pre>
<p>I initialize 52 of them into a tab[], when the button draw is clicked it pick a random one from the tab[] and i try to then change my ImageView with the image of the card picked by getting the id of the card picked and using an setImageResource but it make my application crash can you help me there ?</p>
<p>Here's my mainActivity code : </p>
<pre><code>public class MainActivity extends AppCompatActivity {
protected Carte tab[];
protected ImageView imageCarte;
protected Button afficherCarte;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageCarte = (ImageView) findViewById(R.id.imageCarte);
tab = new Carte[]{new Carte(1, "c_1"), new Carte(1, "d_1"), new Carte(1, "h_1"), new Carte(1, "s_1"),
new Carte(2, "c_2"), new Carte(2, "d_2"), new Carte(2, "h_2"), new Carte(2, "s_2"),
new Carte(3, "c_2"), new Carte(3, "d_3"), new Carte(3, "h_3"), new Carte(3, "s_3"),
new Carte(4, "c_4"), new Carte(4, "d_4"), new Carte(4, "h_4"), new Carte(4, "s_4"),
new Carte(5, "c_5"), new Carte(5, "d_5"), new Carte(5, "h_5"), new Carte(5, "s_5"),
new Carte(6, "c_6"), new Carte(6, "d_6"), new Carte(6, "h_6"), new Carte(6, "s_6"),
new Carte(7, "c_7"), new Carte(7, "d_7"), new Carte(7, "h_7"), new Carte(7, "s_7"),
new Carte(8, "c_8"), new Carte(8, "d_8"), new Carte(8, "h_8"), new Carte(8, "s_8"),
new Carte(9, "c_9"), new Carte(9, "d_9"), new Carte(9, "h_9"), new Carte(9, "s_9"),
new Carte(10, "c_10"), new Carte(10, "d_10"), new Carte(10, "h_10"), new Carte(10, "s_10"),
new Carte(11, "c_11"), new Carte(11, "d_11"), new Carte(11, "h_11"), new Carte(11, "s_11"),
new Carte(12, "c_12"), new Carte(12, "d_12"), new Carte(12, "h_12"), new Carte(12, "s_12"),
new Carte(13, "c_13"), new Carte(13, "d_13"), new Carte(13, "h_13"), new Carte(13, "s_13"),};
afficherCarte = (Button) findViewById(R.id.afficherCarte);
afficherCarte.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random r = new Random();
int i1 = r.nextInt(53 - 1) + 1;
int id = getResources().getIdentifier(tab[i1].getImageId(), "drawable", getPackageName());
imageCarte.setImageResource(id);
}
});
}
}
</code></pre>
| 3 | 1,402 |
App is force closing when i run it? Unable to start app activity
|
<p>When i run it i get an immediate force close. I can never understand the logcat errors. I am using Eclipse along with the Android SDK. Here is the Logcat error but what does it mean?</p>
<pre><code>02-29 12:59:35.875: E/AndroidRuntime(9759): FATAL EXCEPTION: main
02-29 12:59:35.875: E/AndroidRuntime(9759): java.lang.RuntimeException: Unable to start activity ComponentInfo{izzy.n/izzy.n.IzzynActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.os.Handler.dispatchMessage(Handler.java:99)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.os.Looper.loop(Looper.java:130)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.app.ActivityThread.main(ActivityThread.java:3687)
02-29 12:59:35.875: E/AndroidRuntime(9759): at java.lang.reflect.Method.invokeNative(Native Method)
02-29 12:59:35.875: E/AndroidRuntime(9759): at java.lang.reflect.Method.invoke(Method.java:507)
02-29 12:59:35.875: E/AndroidRuntime(9759): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
02-29 12:59:35.875: E/AndroidRuntime(9759): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-29 12:59:35.875: E/AndroidRuntime(9759): at dalvik.system.NativeStart.main(Native Method)
02-29 12:59:35.875: E/AndroidRuntime(9759): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.createView(LayoutInflater.java:518)
02-29 12:59:35.875: E/AndroidRuntime(9759): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:684)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:707)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
02-29 12:59:35.875: E/AndroidRuntime(9759): at android.view.Layout
02-29 12:59:43.347: I/Process(9759): Sending signal. PID: 9759 SIG: 9
</code></pre>
<p>Thanks for the Help anyone</p>
<p>and here is main.xml:</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="@drawable/bg"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<include
android:id="@+id/include1"
android:layout_width="160dp"
android:layout_height="200dp"
android:layout_marginRight="15dp"
android:layout_marginTop="280dp"
layout="@layout/main" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="69dp"
android:text="@string/button1" />
</RelativeLayout>
</code></pre>
<p>Here is AndroidActivity(Java file for main.xml)</p>
<pre><code>package izzy.n;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.Manifest;
public class IzzynActivity extends Activity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button wg = (Button) findViewById(R.id.button1);
wg.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(IzzynActivity.this, notes.class);
IzzynActivity.this.startActivity(myIntent);
}
});
}
}
</code></pre>
<p>Here is Android Manifest:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="izzy.n"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name="izzy.n.IzzynActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="izzy.n.notes"
android:label="@string/notes"></activity>
</application>
</manifest>
</code></pre>
| 3 | 4,165 |
Delete empty dataframes from List
|
<p>Have this following dataframe's List which I'm working with inside a for Loop. Here I have two empty dataframes, x[[2]] and x[[4]]. How can I remove then inside my for loop, let's say, if I do:</p>
<pre><code>for (i in 1:length(x)){
****x[[i]] = ***remove empty dataframes in x[[i]]***
}
</code></pre>
<p>DATASET:</p>
<pre><code> x <- list(structure(list(`8935364000175` = c(0.0060428512369981, 0.00603116477577714,
0.00601948031544453, 0.00584680183237651, 0.00588356233492959,
0.00604482211201685, 0.00595391284150537, 0.00612897711107507,
0, 0.00608207737968769), `25079578000106` = c(0.0561319890039158,
0.0713528263077023, -0.310352321776008, 0.244770088829682, 0.0361304175385158,
-0.215327063233417, -0.0463209246845508, 0, 0.0781647175244871,
0.0306871725115343)), row.names = c("Retorno D - 260", "Retorno D - 259",
"Retorno D - 258", "Retorno D - 257", "Retorno D - 256", "Retorno D - 255",
"Retorno D - 254", "Retorno D - 253", "Retorno D - 252", "Retorno D - 251"
), class = "data.frame"), structure(list(), row.names = c("Retorno D - 260",
"Retorno D - 259", "Retorno D - 258", "Retorno D - 257", "Retorno D - 256",
"Retorno D - 255", "Retorno D - 254", "Retorno D - 253", "Retorno D - 252",
"Retorno D - 251"), class = "data.frame"), structure(list(`25079578000106` = c(-0.0284871479379945,
0.141976900522423, -0.115634388475883, 0.0858369759953348, 0.252102295598888,
-0.130994651044603, 0.213179273123387, 0, 0.254748840234242,
-0.162688137697842), `19107923000175` = c(-2.542040795106, -1.30722252988562,
0.166101507966232, -0.333577277251607, -0.48391700402135, -0.287302340893802,
0.276978237343428, 0, -2.20114477424431, 2.28636453339277), `15674503000110` = c(0.151917711446004,
0.27261553095741, -0.0217761778003478, 0.0357082184564206, 0,
-0.430589756888367, 0.0980497330601793, 0.162832113528566, 0.135437075368827,
0.0254803373536561), `19391009000107` = c(0.118515970461885,
0.0201793494852609, 0.05212900123297, -0.122335026844667, 0,
-0.173768502372695, -0.146583881632978, -0.102553665146843, -0.161486374236119,
0.522601667762501), `26111809000184` = c(0.188357122169691, 0.597206398924754,
-0.117262560343079, -0.350788641299005, 0, -0.427825340193522,
0.0359309879058856, 0.144902896136045, 0.43725947070925, 0.0456868876426597
), `32666326000149` = c(1.84565666459093, 3.33521612974437, -0.706821796120494,
-1.41998375802359, 0, -1.00702592444577, -0.764259576953918,
0.504494091364904, 2.34908743768756, 1.12513038984616)), row.names = c("Retorno D - 260",
"Retorno D - 259", "Retorno D - 258", "Retorno D - 257", "Retorno D - 256",
"Retorno D - 255", "Retorno D - 254", "Retorno D - 253", "Retorno D - 252",
"Retorno D - 251"), class = "data.frame"), structure(list(), row.names = c("Retorno D - 260",
"Retorno D - 259", "Retorno D - 258", "Retorno D - 257", "Retorno D - 256",
"Retorno D - 255", "Retorno D - 254", "Retorno D - 253", "Retorno D - 252",
"Retorno D - 251"), class = "data.frame"))
</code></pre>
| 3 | 1,681 |
CopyFileExW fails with 0 for an existing file
|
<p><strong>Context:</strong></p>
<p>I have an application that searches files in a directory using <code>QDirIterator</code>, filters and copies specific files.</p>
<p><strong>Problem:</strong></p>
<p>Using the results from <a href="https://doc.qt.io/qt-5/qdiriterator.html#next" rel="nofollow noreferrer">QDirIterator::next()</a>, I ensure the file exists (as a unnecessary safe measure) using <a href="https://doc.qt.io/qt-5/qfile.html#exists" rel="nofollow noreferrer">QFile::exists(QString)</a> which is valid.</p>
<p>However, when attempting to copy the file using <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-copyfileexw" rel="nofollow noreferrer">CopyFileExW</a>, it <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-copyfileexw#return-value" rel="nofollow noreferrer">returns 0</a> meaning the file copy failed. I have absolutely no idea why.</p>
<p><strong>File location:</strong></p>
<pre><code>C:/Users/CybeX/Documents/BLMS/Repo/BLMS-Work-Dev/Meeting 2 - Requirements Document Discussion & Dev/2020-05-19 11.22.30 Someone Person's Zoom Meeting 98661954658/zoom_0.mp4
</code></pre>
<hr />
<p><strong>Sanity Tests</strong></p>
<p>I added some sanity tests to check the file content through the conversion from <code>QString</code> -> <code>LPCWSTR</code> as <code>FileCopyExW</code> requires <code>LPCWSTR</code> and it is suggested to convert <code>QString -> LPCWSTR</code> <a href="https://www.qtcentre.org/threads/65546-Can-t-convert-QString-to-LPCWSTR?p=289096#post289096" rel="nofollow noreferrer">here</a>.</p>
<p><em>Regarding the conversion, I have tried <a href="https://stackoverflow.com/a/26366143/4628115">this</a> too but it yields the same result. It is also suggested as bad practice to user c-style casts</em></p>
<p>Sanity tests (in application code below) all pass, but <code>FileCopyExW</code> always fails with:</p>
<blockquote>
<p>"Error 0x80070002: The system cannot find the file specified."</p>
</blockquote>
<p>Code inside application:</p>
<pre><code>QString m_src = QString("C:/Users/CybeX/Documents/BLMS/Repo/BLMS-Work-Dev/Meeting 2 - Requirements Document Discussion & Dev/2020-05-19 11.22.30 Someone Person's Zoom Meeting 98661954658/zoom_0.mp4");
QString m_dst = QString("C:/Users/CybeX/Documents/BLMS/Repo/BLMS-Work-Dev/Meeting 2 - Requirements Document Discussion & Dev/2020-05-19 11.22.30 Someone Person's Zoom Meeting 98661954658/zoom_0.mp42");
// Hard coded test location attempting to match variables' content below
// QString srcLocation = QString("C:/Users/CybeX/Documents/BLMS/Repo/BLMS-Work-Dev/Meeting 2 - Requirements Document Discussion & Dev/2020-05-19 10.41.17 Someone Person's Zoom Meeting 96047275811/zoom_0.mp4");
// QString dstLocation = QString("C:/Users/CybeX/Documents/BLMS/Repo/BLMS-Work-Dev/Meeting 2 - Requirements Document Discussion & Dev/2020-05-19 10.41.17 Someone Person's Zoom Meeting 96047275811/zoom_0.mp44");
// std::wstring srcWString1 = srcLocation.toStdWString();
// std::wstring dstWString1 = dstLocation.toStdWString();
// const wchar_t* localC_src1 = srcLocation.toStdWString().c_str();
// const wchar_t* localC_dst1 = dstLocation.toStdWString().c_str();
//
// std::wstring srcWString = m_src.toStdWString();
// std::wstring dstWString = m_dst.toStdWString();
// Used inside copy function
const wchar_t* localC_src = m_src.toStdWString().c_str();
const wchar_t* localC_dst = m_dst.toStdWString().c_str();
// Sanity tests
if (m_src.contains("96047275811/zoom_0.mp4")) {
if (srcLocation != m_src) {
qDebug() << "Warning"; // Never gets hit
}
if (srcWString != srcWString1) {
qDebug() << "Warning"; // Never gets hit
}
if (*localC_src != *localC_src1) {
qDebug() << "Warning"; // Never gets hit
}
if (!QFile::exists(srcLocation)) {
qDebug() << "Warning"; // Never gets hit
}
}
auto rc = CopyFileExW(localC_src, localC_dst, &FileManager::copyProgress, this, &bStopBackup, 0);
if (rc == 0) {
printWarning(TAG, QString("File Copy Error: %1").arg(getLastErrorMsg()));
// copy failed
return FileResult::IOError; // This file always hits
}
// copy success
return FileResult::Success;
</code></pre>
<p>However, hard coding the file location in a custom test application does indeed work correctly.</p>
<p><strong>Testing Application:</strong></p>
<p><em>Result is successful</em></p>
<pre><code>static QString toString(HRESULT hr)
{
_com_error err{hr};
const TCHAR* lastError = err.ErrorMessage();
return QStringLiteral("Error 0x%1: %2").arg((quint32)hr, 8, 16, QLatin1Char('0'))
.arg(lastError);
}
static QString getLastErrorMsg()
{
QString s = toString(HRESULT_FROM_WIN32(GetLastError()));
return s;
}
int main(int argc, char* argv[])
{
QCoreApplication a(argc, argv);
QString m_src = QString("C:/Users/CybeX/Documents/BLMS/Repo/BLMS-Work-Dev/Meeting 2 - Requirements Document Discussion & Dev/2020-05-19 11.22.30 Someone Person's Zoom Meeting 98661954658/zoom_0.mp4");
QString m_dst = QString("C:/Users/CybeX/Documents/BLMS/Repo/BLMS-Work-Dev/Meeting 2 - Requirements Document Discussion & Dev/2020-05-19 11.22.30 Someone Person's Zoom Meeting 98661954658/zoom_0.mp42");
auto rc = CopyFileExW(m_src.toStdWString().c_str(), m_dst.toStdWString().c_str(),
NULL, NULL, NULL, 0);
if (rc == 0) {
QString s = getLastErrorMsg();
// copy failed
qDebug() << "Failed";
}
else {
qDebug() << "Copied"; // Always gets hit
}
// copy success
return a.exec();
}
</code></pre>
| 3 | 2,535 |
Android programmatically add ImageView with ConstraintLayout
|
<p>I want to programmatically insert several ImageView into a RecyclerView using ConstraintLayout.</p>
<p>To insert images in an equidistant way using Horizontal Bias, the value for each image is calculated as:</p>
<pre><code>float biasedValue = (1f / (flightPlanWeather.weather.size () + 1f)) * (i + 1f);
</code></pre>
<p>The code is as follows</p>
<pre><code>public class FlightPlanWeatherRecyclerAdapter extends RecyclerView.Adapter<FlightPlanWeatherRecyclerAdapter.MyViewHolder> {
private static final String TAG = FlightPlanWeatherRecyclerAdapter.class.getName();
private List<FlightPlanWeather> dataSet;
private LayoutInflater mInflater;
Context mContext;
// Provide a suitable constructor (depends on the kind of dataset)
// data is passed into the constructor
public FlightPlanWeatherRecyclerAdapter(Context context, List<FlightPlanWeather> data) {
this.mInflater = LayoutInflater.from(context);
this.dataSet = data;
this.mContext = context;
}
// inflates the row layout from xml when needed
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.row_item_flightplan_weather, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.bind(dataSet.get(position));
FlightPlanWeather flightPlanWeather = dataSet.get(position);
holder.from_img.setImageResource(flightPlanWeather.from.getImg_resource());
holder.from_label.setText(flightPlanWeather.from.getLabel());
holder.to_img.setImageResource(flightPlanWeather.to.getImg_resource());
holder.to_label.setText(flightPlanWeather.to.getLabel());
int dimensionInPixel = 256;
ConstraintLayout.LayoutParams lp =
new ConstraintLayout.LayoutParams(/*ConstraintLayout.LayoutParams.WRAP_CONTENT,*/ dimensionInPixel,
/*ConstraintLayout.LayoutParams.WRAP_CONTENT*/ dimensionInPixel);
//weather
for(int i=0; i<flightPlanWeather.weather.size(); i++ ){
ConstraintSet constraintSet = new ConstraintSet();
holder.mConstraintSetList.add(constraintSet);
ImageView imageView = new ImageView(mContext);
imageView.setId(View.generateViewId());
imageView.setImageResource(flightPlanWeather.weather.get( i ));
imageView.setLayoutParams(lp);
imageView.requestLayout();
holder.weather.add(imageView);
holder.mConstraintLayout.addView( imageView/*, lp */);
//}
constraintSet.clone(holder.mConstraintLayout);
float biasedValue = (1f/ (flightPlanWeather.weather.size()+1f)) * (i+1f);
Log.d(TAG, Float.toString( biasedValue ) +"i:"+ Integer.toString( i )+"size:"+ flightPlanWeather.weather.size());
constraintSet.setHorizontalBias(imageView.getId(), biasedValue);
constraintSet.connect(imageView.getId(), ConstraintSet.START, holder.mConstraintLayout.getId(), ConstraintSet.START, 0);
constraintSet.connect(imageView.getId(), ConstraintSet.END, holder.mConstraintLayout.getId(), ConstraintSet.END, 0);
constraintSet.connect(imageView.getId(), ConstraintSet.TOP, holder.mConstraintLayout.getId(), ConstraintSet.TOP, 0);
constraintSet.connect(imageView.getId(), ConstraintSet.BOTTOM, holder.mConstraintLayout.getId(), ConstraintSet.BOTTOM, 0);
constraintSet.applyTo(holder.mConstraintLayout);
holder.mConstraintLayout.requestLayout();
}
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return dataSet == null ? 0 : dataSet.size();
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
// Static inner class to initialize the views of rows
static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView from_label;
TextView to_label;
ImageView from_img;
ImageView to_img;
ImageView line;
ConstraintLayout mConstraintLayout;
List<ConstraintSet> mConstraintSetList = new ArrayList<>( );
List<ImageView> weather = new ArrayList<>( );
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mConstraintLayout = (ConstraintLayout) itemView.findViewById(R.id.mainConstraintLayout);
from_label = (TextView) itemView.findViewById(R.id.from_label);
to_label = (TextView) itemView.findViewById(R.id.to_label);
from_img = (ImageView) itemView.findViewById(R.id.from_img);
to_img = (ImageView) itemView.findViewById(R.id.to_img);
line = (ImageView) itemView.findViewById(R.id.line);
}
public void bind(Object object){
}
@Override
public void onClick(View view) {
Log.d("onclick", "onClick " + getLayoutPosition() + " " /*+ /*item.getText()*/);
}
}
}
</code></pre>
<p>The problem is that the Horizontal Bias of the weather does not work properly
<a href="https://i.stack.imgur.com/RDi0K.png" rel="nofollow noreferrer">screenshot</a></p>
<p>The View should come this way:
<a href="https://i.stack.imgur.com/dglfG.png" rel="nofollow noreferrer">screenshot</a></p>
| 3 | 2,270 |
.sheet: Shows only once and then never again
|
<p>Working with Beta4, it seems that the bug is still existing. The following sequence of views (a list, where a tap on a list entry opens another list) allows to present the <code>ListView</code> exactly once; the <code>onDisappear</code> is never called, so the <code>showModal</code> flag changes, but does not triggers the redisplay of <code>ListView</code> when tapped again. So, for each <code>GridCellBodyEntry</code>, the <code>.sheet</code> presentation works exactly once, and then never again.</p>
<p>I tried around with several suggestions and workarounds, but none worked (e.g., encapsulating with a NavigationViewModel). I even tried to remove the List, because there was an assumption that the <code>List</code> causes that behaviour, but even this did not change anything.</p>
<p>Are there any ideas around?</p>
<p>The setup: </p>
<ol>
<li>A <code>GridCellBody</code> with this view:</li>
</ol>
<pre><code>var body: some View {
GeometryReader { geometry in
VStack {
List {
Section(footer: self.footerView) {
ForEach(self.rawEntries) { rawEntry in
GridCellBodyEntry(entityType: rawEntry)
}
}
}
.background(Color.white)
}
}
}
</code></pre>
<ol start="2">
<li>A <code>GridCellBodyEntry</code> with this definition:</li>
</ol>
<pre><code>struct GridCellBodyEntry: View {
let entityType: EntityType
let viewModel: BaseViewModel
init(entityType: EntityType) {
self.entityType = entityType
self.viewModel = BaseViewModel(entityType: self.entityType)
}
@State var showModal = false {
didSet {
print("showModal: \(showModal)")
}
}
var body: some View {
Group {
Button(action: {
self.showModal.toggle()
},
label: {
Text(entityType.localizedPlural ?? "")
.foregroundColor(Color.black)
})
.sheet(isPresented: $showModal, content: {
ListView(showModal: self.$showModal,
viewModel: self.viewModel)
})
}.onAppear{
print("Profile appeared")
}.onDisappear{
print("Profile disappeared")
}
}
}
</code></pre>
<ol start="3">
<li>A <code>ListView</code> with this definition:</li>
</ol>
<pre><code>struct ListView: View {
// MARK: - Private properties
// MARK: - Public interface
@Binding var showModal: Bool
@ObjectBinding var viewModel: BaseViewModel
// MARK: - Main view
var body: some View {
NavigationView {
VStack {
List {
Section(footer: Text("\(viewModel.list.count) entries")) {
ForEach(viewModel.list, id: \.objectID) { item in
NavigationLink(destination: ItemView(),
label: {
Text("\(item.objectID)")
})
}
}
}
}
.navigationBarItems(leading:
Button(action: {
self.showModal = false
}, label: {
Text("Close")
}))
.navigationBarTitle(Text(viewModel.entityType.localizedPlural ?? ""))
}
}
}
</code></pre>
<ol start="4">
<li>The <code>BaseViewModel</code> (excerpt): </li>
</ol>
<pre><code>class BaseViewModel: BindableObject {
/// The binding support.
var willChange = PassthroughSubject<Void, Never>()
/// The context.
var context: NSManagedObjectContext
/// The current list of typed items.
var list: [NSManagedObject] = []
// ... other stuff ...
}
</code></pre>
<p>where <code>willChange.send()</code> is called whenever something changes (create, modify, delete operations).</p>
| 3 | 1,961 |
React Redux how to properly distribute components
|
<p><strong>I have a store in Redux, I'm making an online clothes shop with products for Womans and Mens</strong></p>
<pre><code>const defaultState = {
womanProducts:
[
{
name: "Mini Skirt",
img: "https://static.pullandbear.net/2/photos//2022/I/0/1/p/8399/316/800/8399316800_4_1_8.jpg?t=1656932863233&imwidth=563",
price: 35,
inCart: 1,
id: 1.1,
},
{
name: "Basic Jeans",
img: "https://static.pullandbear.net/2/photos//2022/I/0/1/p/8685/326/400/8685326400_4_1_8.jpg?t=1657798996961&imwidth=563",
price: 39,
inCart: 1,
id: 1.2,
},
{
name: "Fit Dress",
img: "https://static.pullandbear.net/2/photos//2022/V/0/1/p/4390/422/611/4390422611_4_1_8.jpg?t=1643722977148&imwidth=563",
price: 45,
inCart: 1,
id: 1.3,
},
{
name: "Basic Sweatshirt",
img: "https://static.pullandbear.net/2/photos//2021/I/0/1/p/8393/363/485/8393363485_4_1_8.jpg?t=1634212398331&imwidth=563",
price: 29,
inCart: 1,
id: 1.4,
}
],
manProducts:
[
{
name: "Basic Hoodie",
img: "https://static.pullandbear.net/2/photos//2022/I/0/2/p/8591/513/250/05/8591513250_6_1_8.jpg?t=1648556110506&imwidth=563",
price: 39,
inCart: 1,
id: 2.1,
},
{
name: "Basic Jeans",
img: "https://static.pullandbear.net/2/photos//2022/I/0/2/p/8591/513/827/03/8591513827_6_1_8.jpg?t=1646659329763&imwidth=563",
price: 29,
inCart: 1,
id: 2.2,
},
{
name: "Black Shorts",
img: "https://static.pullandbear.net/2/photos//2021/I/0/2/p/4695/507/800/4695507800_4_1_8.jpg?t=1629285223879&imwidth=563",
price: 19,
inCart: 1,
id: 2.3,
},
{
name: "Naruto Set",
img: "https://static.pullandbear.net/2/photos//2022/V/0/2/p/4693/700/800/4693700800_4_1_8.jpg?t=1643120792610&imwidth=563",
price: 59,
inCart: 1,
id: 2.4,
}
],
cartProducts: [],
}
</code></pre>
<p><strong>And also I have a two components, where I get products from store, drawing them in two pages and there is function to add products to shopping cart</strong></p>
<p><strong>Components:</strong></p>
<p>WomanProducts:</p>
<pre><code>export default function WomansProducts() {
const dispatch = useDispatch();
const selector = useSelector(state => state);
const womanProducts = selector.womanProducts;
const cartProducts = selector.cartProducts;
const addProducts = (id) => {
let isInCart = false;
cartProducts.forEach(el => {
if(id === el.id) {
isInCart = true
}
})
if(!isInCart) {
dispatch({type: "ADD_PRODUCTS", payload: womanProducts.find((product) => id === product.id)})
}
}
return (
<div className="mainProducts">
{womanProducts.map(item =>
<div className="womanProduct" key={item.id}>
<img src={item.img} />
<h3>{item.name}</h3>
<h3>{item.price}$</h3>
<button onClick={() => addProducts(item.id)}>Add to Cart</button>
</div>
)}
</div>
)
</code></pre>
<p>}</p>
<p>MenProducts:</p>
<pre><code>export default function MansProducts() {
const dispatch = useDispatch();
const selector = useSelector(state => state);
const manProducts = selector.manProducts;
const cartProducts = selector.cartProducts;
const addProducts = (id) => {
let isInCart = false;
cartProducts.forEach(el => {
if(id === el.id) {
isInCart = true
}
})
if(!isInCart) {
dispatch({type: "ADD_PRODUCTS", payload: manProducts.find((product) => id === product.id)})
}
}
return (
<div className="mainProducts">
{manProducts.map(item =>
<div className="manProduct" key={item.id}>
<img src={item.img} />
<h3>{item.name}</h3>
<h3>{item.price}$</h3>
<button onClick={() => addProducts(item.id)}>Add to Cart</button>
</div>
)}
</div>
)
</code></pre>
<p>}</p>
<p><strong>These components are the same, is it okay or I should to distribute this components? And how?</strong></p>
| 3 | 2,532 |
502 error and unhealthy health status in the target group when using AWS ELB and ACM for https
|
<p>I'm using AWS ELB and ACM to use HTTPS on Node.js but, I have been facing 502 error.<br>
The health status of the target group for the HTTPS is "unhealthy" which is making me understand I'm doing something wrong around ELB.</p>
<p>The following is what I did.</p>
<p><b>[ELB]</b></p>
<b>VPC</b>: Same VPC with the EC2 instance<br>
<b>Subnet #1</b>: 10.0.1.0/24: Same subnet with the EC2 instance<br>
<b>Subnet #2</b>: 10.0.3.0/24: New subnet which was created for this test<br>
<b>Security group</b>: All traffic for inbound & outbound are opened (for this test purpose)<br>
<b>Listener_a(http:80)</b>:<br>
Rule1: <br>
(If) Host is [example].com OR www.[example].com<br>
(Then) Redirect to https://www.[example].com:443/#{path}?#{query}<br>
(path and query are untouched from the default placeholder)<br>
Status code: HTTP_301<br>
Rule last: untouched from the default<br>
<b>Listener_b(https:443)</b>:<br>
Rule1: <br>
(If) Host is [example].com<br>
(Then) Redirect to https://www.[example].com:443/#{path}?#{query}<br>
(path and query are untouched from the default placeholder)<br>
Status code: HTTP_301<br>
Rule last: untouched from the default<br>
<br>
<p><b>[Target groups of ELB]</b><p>
<b> Target group #1</b>:<br>
[Target type] [Protocol version] [Instance ID] [Name] [Port] [Zone] [Health status]<br>
Instance HTTP1 [Instance ID of the EC2] testname1 80 us-east-2b healthy <br>
<b> Target group #2</b>:<br>
[Target type] [Protocol version] [Instance ID] [Name] [Port] [Zone] [Health status] [Health status details]<br>
Instance HTTP1 [Instance ID of the EC2] testname2 443 us-east-2b unealthy "Health checks failed"<br>
<br>
<p><b>[Summary of ELB log]</b><p>
<b>type</b>: h2<br>
<b>target</b>:port: Private IPv4 address of the EC2 instance<br>
<b>request_processing_time</b>: -1<br>
<b>target_processing_time</b>: -1<br>
<b>response_processing_time</b>: -1<br>
<b>elb_status_code</b>: 502<br>
<b>target_status_code</b>: -<br>
<b>request</b>: GET https://www.[example].com:443/HTTP/2.0<br>
<br>
<p><b>[Route 53]</b><p>
[Record name] [Type] [Routing Policy] [Differentiator] [Value/Route traffic to]<br>
[example].com A Simple - www.[example].com.<br>
www.[example].com A Simple - dualstack.[DNS name of the ELB].<br>
[CNAME name of *.[example].com from ACM] CNAME Simple - [CNAME value from ACM]<br>
[CNAME name of www.[example].com from ACM] CNAME Simple - [CNAME value from ACM]<br>
[example].com NS Simple - [4 Name Servers added by Route 53]<br>
[example].com SOA Simple - [Value added by Route 53]<br>
<br>
<p><b>[ACM]</b><p>
[Domain] [Status]<br>
*.[example].com Success<br>
[example].com Success<br>
www.[example].com Success<br>
<br>
<p><b>[EC2]</b><p>
<b>VPC</b>: Same VPC with the ELB (10.0.0.0/16)<br>
<b>Subnet #1</b>: Same subnet with the one of the subnet assinged to ELB (10.0.1.0/24)<br>
<b>Public IPv4 address</b>: [ElasticIP assigned]<br>
<b>Security group</b>: All traffic for inbound & outbound are opened (for this test purpose)<br>
<br>
<p><b>[Routing table (same for both subnet)]</b><p>
[Destination] [Target]<br>
10.0.0.0/16 local<br>
0.0.0.0/0 [IGW]<br>
<br>
<p><b>[ACLs]</b><p>
All are allowed for both Inbound and Outbound(for this test purpose).
<br>
<p><b>[iptables I ran on EC2]</b><p>
# iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8000<br>
# iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443<br>
<br>
<p><b>[Node.js code on EC2 (index.js)]</b><p>
<pre><code>const fs = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');
const app = express();
const path = require('path');
app.get('/', (req, res) => {
res.send("Hello World!");
});
const httpServer = http.createServer(app);
const httpsServer = https.createServer(app);
httpServer.listen(8000, () => {
console.log("App is listening on port 8000");
});
httpsServer.listen(8443, () => {
console.log("App is listening on port 8443");
});
</code></pre>
<p><b>[Summary of results accessing from browser]</b></p>
https://www.[example.com]<br> => "502 Bad Gateway"<br>
http://[example].com<br> => Browser redirect it to https://www.[example].com and returns "502 Bad Gateway"<br>
[my Elastic IP]<br> => Can see the web page w/o error<br>
[Public IPv4 DNS of the EC2 instance]<br> => Can see the web page w/o error<br>
[DNS name]<br> => Can see the web page w/o error<br>
<br>
<p><b>[Summary of results accessing from EC2 command line with curl]</b></p>
http://www.[example].com<br> => 301 Moved Permanently<br>
https://www.[example].com<br> => 502 Bad Gateway<br>
<br>
I tried to figure out what is wrong based on the following documents but, so far, no luck.<br>
<br>
https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#enable-access-logging<br>
https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html<br>
https://aws.amazon.com/premiumsupport/knowledge-center/elb-fix-failing-health-checks-alb/<br>
https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-troubleshooting.html<br>
https://aws.amazon.com/premiumsupport/knowledge-center/troubleshoot-unhealthy-checks-ecs/<br>
<br>
If anyone could provide me with your insight about what I am missing/doing wrong, it would be great. Please let me know if there is any other information needed.<br>
Thank you!<br>
<br>
<p><b>[Additional edits (8/21/2022)]</b></p>
As it looked similar to what was discussed on this thread (https://stackoverflow.com/questions/60738575/target-group-443-gives-health-checks-failed-with-these-codes-502?rq=1), I just tried changing the Health check protocol for the target group of HTTPS to use HTTP; however, the results (unhealthy) were the same.<br>
<br>
| 3 | 2,164 |
Apache Ignite Near Cache - local cache metrics
|
<p>I've been experimenting with Ignite Near Caches. In doing so I'm configuring a client node with two server nodes in the cluster. I instantiated a near cache and would like to see the associated metrics on the cache hits/misses. Functionally everything works fine, but I can't figure out where the near cache metrics are.</p>
<p>I've tried to extract the cache metrics via calls</p>
<pre><code>NearCacheConfiguration<Integer, Integer> nearCfg =
new NearCacheConfiguration<>();
nearCfg.setNearEvictionPolicyFactory(new LruEvictionPolicyFactory<>(100));
nearCfg.setNearStartSize(50);
IgniteCache<Integer, Integer> cache = ignite.getOrCreateCache(
new CacheConfiguration<Integer, Integer>("myCache"), nearCfg);
// run some cache puts and gets
for (int i=0; i<10000; i++) { cache.put(i, i); }
for (int i=0; i<10000; i++) { cache.get(i); }
// then try to retrieve metrics
System.out.println(cache.localMetrics());
System.out.println(cache.metrics());
</code></pre>
<p>output</p>
<pre><code>CacheMetricsSnapshot [reads=0, puts=0, hits=0, misses=0, txCommits=0, txRollbacks=0, evicts=0, removes=0, putAvgTimeNanos=0.0, getAvgTimeNanos=0.0, rmvAvgTimeNanos=0.0, commitAvgTimeNanos=0.0, rollbackAvgTimeNanos=0.0, cacheName=myCache, offHeapGets=0, offHeapPuts=0, offHeapRemoves=0, offHeapEvicts=0, offHeapHits=0, offHeapMisses=0, offHeapEntriesCnt=0, heapEntriesCnt=0, offHeapPrimaryEntriesCnt=0, offHeapBackupEntriesCnt=0, offHeapAllocatedSize=0, size=0, keySize=0, isEmpty=true, dhtEvictQueueCurrSize=0, txThreadMapSize=0, txXidMapSize=0, txCommitQueueSize=0, txPrepareQueueSize=0, txStartVerCountsSize=0, txCommittedVersionsSize=0, txRolledbackVersionsSize=0, txDhtThreadMapSize=0, txDhtXidMapSize=0, txDhtCommitQueueSize=0, txDhtPrepareQueueSize=0, txDhtStartVerCountsSize=0, txDhtCommittedVersionsSize=0, txDhtRolledbackVersionsSize=0, isWriteBehindEnabled=false, writeBehindFlushSize=-1, writeBehindFlushThreadCnt=-1, writeBehindFlushFreq=-1, writeBehindStoreBatchSize=-1, writeBehindTotalCriticalOverflowCnt=0, writeBehindCriticalOverflowCnt=0, writeBehindErrorRetryCnt=0, writeBehindBufSize=-1, totalPartitionsCnt=0, rebalancingPartitionsCnt=0, keysToRebalanceLeft=0, rebalancingKeysRate=0, rebalancingBytesRate=0, rebalanceStartTime=0, rebalanceFinishTime=0, keyType=java.lang.Object, valType=java.lang.Object, isStoreByVal=true, isStatisticsEnabled=false, isManagementEnabled=false, isReadThrough=false, isWriteThrough=false, isValidForReading=true, isValidForWriting=true]
CacheMetricsSnapshot [reads=0, puts=0, hits=0, misses=0, txCommits=0, txRollbacks=0, evicts=0, removes=0, putAvgTimeNanos=0.0, getAvgTimeNanos=0.0, rmvAvgTimeNanos=0.0, commitAvgTimeNanos=0.0, rollbackAvgTimeNanos=0.0, cacheName=myCache, offHeapGets=0, offHeapPuts=0, offHeapRemoves=0, offHeapEvicts=0, offHeapHits=0, offHeapMisses=0, offHeapEntriesCnt=0, heapEntriesCnt=100, offHeapPrimaryEntriesCnt=0, offHeapBackupEntriesCnt=0, offHeapAllocatedSize=0, size=0, keySize=0, isEmpty=true, dhtEvictQueueCurrSize=-1, txThreadMapSize=0, txXidMapSize=0, txCommitQueueSize=0, txPrepareQueueSize=0, txStartVerCountsSize=0, txCommittedVersionsSize=0, txRolledbackVersionsSize=0, txDhtThreadMapSize=0, txDhtXidMapSize=-1, txDhtCommitQueueSize=0, txDhtPrepareQueueSize=0, txDhtStartVerCountsSize=0, txDhtCommittedVersionsSize=-1, txDhtRolledbackVersionsSize=-1, isWriteBehindEnabled=false, writeBehindFlushSize=-1, writeBehindFlushThreadCnt=-1, writeBehindFlushFreq=-1, writeBehindStoreBatchSize=-1, writeBehindTotalCriticalOverflowCnt=-1, writeBehindCriticalOverflowCnt=-1, writeBehindErrorRetryCnt=-1, writeBehindBufSize=-1, totalPartitionsCnt=0, rebalancingPartitionsCnt=0, keysToRebalanceLeft=0, rebalancingKeysRate=0, rebalancingBytesRate=0, rebalanceStartTime=-1, rebalanceFinishTime=-1, keyType=java.lang.Object, valType=java.lang.Object, isStoreByVal=true, isStatisticsEnabled=false, isManagementEnabled=false, isReadThrough=false, isWriteThrough=false, isValidForReading=true, isValidForWriting=true]
</code></pre>
<p>Looks like there are no meaningful metrics. I figured that it may be part of the NearCacheConfiguration to configure stats as is the case with CacheConfiguration but no.</p>
<p>Any idea?</p>
| 3 | 1,517 |
Toggle "CanExecute" of a button based on grid selection
|
<p>I am very to Modern UI Programming and now i got stuck in a small C# WPF Application which is basically a learning project of MVVM design pattern.</p>
<p>I have a DataGrid and some Buttons to handle data operation (add, edit, delete).</p>
<p>What i want to achieve: the edit button should not be enable, when no row in grid is selected. </p>
<p><strong>edit button:</strong></p>
<pre><code><Button Width="126" Height="22" Content="Edit" Margin="5,5,5,5" Command="{Binding KontoEdit}" />
</code></pre>
<p><strong>grid:</strong></p>
<pre><code> <DataGrid ItemsSource="{Binding Konten}" SelectedItem="{Binding SelectedKonto}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=KtoNr}" Header="Nr" IsReadOnly="True" />
<DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" IsReadOnly="True" />
<DataGridTextColumn Binding="{Binding Path=KtoArt}" Header="Kontoart" IsReadOnly="True" />
<DataGridTextColumn Binding="{Binding Path=KtoKlasse}" Header="Kontenklasse" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
</code></pre>
<p><strong>view model:</strong></p>
<pre><code>public class MainViewModel : INotifyPropertyChanged
{
KontenDB ctx = new KontenDB();
public MainViewModel()
{
FillKonten();
CanKontoEditExecute = true ;
KontoEdit = new RelayCommand(o => { DoKontoEdit(SelectedKonto); }, param => CanKontoEditExecute);
}
#region //Commands
public void DoKontoEdit(Konten k)
{
//Edit the Selected Item
}
private ICommand _kontoEdit;
public ICommand KontoEdit
{
get
{
return _kontoEdit;
}
set
{
_kontoEdit = value;
}
}
private bool _canKontoEditExecute;
public bool CanKontoEditExecute
{
get
{
return _canKontoEditExecute;
}
set
{
_canKontoEditExecute = value;
}
}
#endregion //Commands
private void FillKonten()
{
var q = (from k in ctx.Konten
select k).ToList();
Konten = new ObservableCollection<Konten>(q);
}
private ObservableCollection<Konten> _konten;
public ObservableCollection<Konten> Konten
{
get
{
return _konten;
}
set
{
_konten = value;
NotifyPropertyChanged();
}
}
private Konten _selectedKonto;
public Konten SelectedKonto
{
get
{
return _selectedKonto;
}
set
{
_selectedKonto = value;
NotifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
</code></pre>
<p>model is generated by EF6.</p>
<p><strong>edit: RelayCommand class:</strong></p>
<pre><code>public class RelayCommand : ICommand
{
private Action<object> execute;
private Predicate<object> canExecute;
private event EventHandler CanExecuteChangedInternal;
public RelayCommand(Action<object> execute)
: this(execute, DefaultCanExecute)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
if (canExecute == null)
{
throw new ArgumentNullException("canExecute");
}
this.execute = execute;
this.canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
CanExecuteChangedInternal += value;
}
remove
{
CommandManager.RequerySuggested -= value;
CanExecuteChangedInternal -= value;
}
}
public bool CanExecute(object parameter)
{
return canExecute != null && canExecute(parameter);
}
public void Execute(object parameter)
{
execute(parameter);
}
public void OnCanExecuteChanged()
{
EventHandler handler = CanExecuteChangedInternal;
if (handler != null)
{
handler.Invoke(this, EventArgs.Empty);
}
}
public void Destroy()
{
canExecute = _ => false;
execute = _ => { return; };
}
private static bool DefaultCanExecute(object parameter)
{
return true;
}
}
</code></pre>
<p>So how can i achieve that when: no row in datagrid is selected or SelectedKonto is null the CanKontoEditExecute property changes to false?</p>
<p>Thanks a lot for your help!</p>
| 3 | 2,506 |
I get a java.util.NoSuchElementException on input from System.in
|
<p>I am writing code for a program which displays a map based a file with x & y coordinates, as well as a type value.</p>
<p>My code correctly displays the ASCII map and allows me to perform functions on the map, but when the code finally returns to the switch statement where it should take input for choosing the next option, it skips the line "option = input.nextInt();" and continues to the finally block where "input.nextLine();" gives me a Java.util.NoSuchElementException.</p>
<p>Does anyone know why this is? I know that this exception usually occurs with an enumeration when there is no such element, but I don't know why my code would skip the input.nextInt() line and then fail on input.nextLine();</p>
<p>This error occurs only when the Gorgon case is activated in the viewMap Switch case at the end. I have tried adding "input.nextLine()" calls before the "input.nextInt()" call, but it doesn't make a difference.</p>
<p>Included is the code for the Switch Statement in my MapViewer program, as well as the code for building the map and displaying it. I have also added the Gorgon class at the end.</p>
<pre><code>public class MapViewerMenu {
public int option = 0;
public boolean complete = false;
Scanner input = new Scanner(System.in);
char [][] mapper = null;
Map currentMap = null;
User currentUser = null;
Vector <Grue> currentGrues = null;
public void run(){
while(!complete){
System.out.println("*******************");
System.out.println("* Map Viewer Menu *");
System.out.println("*******************");
System.out.println("1. Load Files");
System.out.println("2. Set Symbols");
System.out.println("3. View Map");
System.out.println("4. Scramble Map");
System.out.println("5. Reset Map");
System.out.println("6. Exit");
System.out.println("");
try{
option = input.nextInt();
}
catch(Exception e){
System.out.println("Error in input.");
System.out.println("Try again.");
System.out.println("");
}
finally{
// The Error occurs once the program exits viewMap and returns here.
//It skips the above "option = input.nextInt();" and comes down here and fails.
input.nextLine();
}
switch(option){
//removed irrelevant cases
case 3:
viewMap();
break;
case 6:
complete = true;
input.close();
break;
}
}
}
</code></pre>
<hr>
<pre><code> public void viewMap(){
//removed earlier code that built part of the map for readability
number = currentGrues.elements(); //this is an enumeration
while(number.hasMoreElements()){
temp3 = number.nextElement();
int sure =2;
switch(temp3.getName()){
case "Gorgon":
while(sure != 0){
System.out.printf("Would you like the Gorgon to change a square type?\n");
System.out.println("(0 for yes, 1 for no.)");
try{
sure = input.nextInt();
}
catch(Exception e){
System.out.println("Error in input.");
System.out.println("Try again.");
System.out.println("");
sure = 2;
}
finally{
input.nextLine();
}
if(sure == 0){
Gorgon gor = (Gorgon) temp3;
gor.boulder(currentMap, mapper);
after = true;
break;
}
else{
if(sure == 1){
break;
}
}
}
break;
// A boolean value after tells the program to reprint the map.
if(after){
System.out.println("Since some squares were changed, the updated map is printed.");
System.out.println("");
System.out.printf("Map Name: %s", currentMap.getName());
System.out.println("");
for(xpos = 0, ypos = 0; xpos < 16 && ypos < 16;){
System.out.print(mapper[xpos][ypos]);
xpos++;
if(xpos < 16){
continue;
}
else{
System.out.println("");
ypos++;
if(ypos < 16){
xpos = 0;
continue;
}
}
}
System.out.println("");
}
}
//This should then go back to the "option = input.nextInt" line, where it should ask the user for input, but doesnt.
</code></pre>
<hr>
<pre><code>import java.util.Scanner;
public class Gorgon extends Giant {
//Included is the function called by the viewMap switch statement.
//I added this because the error might exist here.
//other classes have similar functions, but perform just fine.
public void boulder(Map map, char[][] mapper){
int x = 0;
int y = 0;
Scanner input = new Scanner(System.in);
System.out.println("The Gorgon wants to turn an adjacent Square to stone!");
System.out.printf("Its position is (%d,%d).\n", this.currPos.col, this.currPos.row);
do{
do{ // Get an adjacent x coordinate
try{
System.out.println("Enter an x coordinate:");
x = input.nextInt();
}
catch(Exception e){
System.out.println("Error in input.");
System.out.println("Try again:");
System.out.println("");
}
finally{
input.nextLine();
}
}while(!(x >= currPos.col-1 && x <= currPos.col+1));
do{ // get an adjacent y coordinate
try{
System.out.println("Enter a y coordinate:");
y = input.nextInt();
}
catch(Exception e){
System.out.println("Error in input.");
System.out.println("Try again:");
System.out.println("");
}
finally{
input.nextLine();
}
}while(!(y >= currPos.row-1 && y <= currPos.row+1)); // keep asking for input while the input isn't within range.
}while(!((x >= currPos.col-1 && x <= currPos.col+1) && (y >= currPos.row-1 && y <= currPos.row+1)));
mapper[x][y] = 'B'; //Change the value in map data.
input.close(); //Close local input reader.
</code></pre>
<h2> }</h2>
<p>The user is at (3,3)</p>
<p>I have in my collection of grues a Gorgon at (6,6) which should be able to turn an adjacent square to type "boulder", which is an obstacle the user can't stand on. </p>
<p>Everytime I choose to use the Gorgon's function boulder, my program fails when it reaches the original switch statement at the beginning of the program.</p>
<p><strong>When the program runs, this is how is usually goes:</strong></p>
<p><strong>I load the appropriate files (these don't have to do with the error.)</strong></p>
<hr>
<ul>
<li><p>Map Viewer Menu *</p>
<hr>
<ol>
<li>Load Files</li>
<li>Set Symbols</li>
<li>View Map</li>
<li>Scramble Map</li>
<li>Reset Map</li>
<li>Exit</li>
</ol></li>
</ul>
<p>3</p>
<p>Building map...</p>
<p><strong>The map is then displayed with ASCII characters.</strong></p>
<p>The user's Rope has been stolen!</p>
<p>Would you like the Giant to change a square type?</p>
<p>(0 for yes, 1 for no.)</p>
<p>1</p>
<p>Meat! Meat! Meat!</p>
<p>Would you like the Gorgon to change a square type?</p>
<p>(0 for yes, 1 for no.)</p>
<p>0</p>
<p>The Gorgon wants to turn an adjacent Square to stone!</p>
<p>Its position is (6,6).</p>
<p>Enter an x coordinate:</p>
<p>7</p>
<p>Enter a y coordinate:</p>
<p>6</p>
<p><strong>Since some squares were changed, the updated map is printed.</strong></p>
<p><strong>The updated is then correctly printed again.</strong></p>
<hr>
<ul>
<li><p>Map Viewer Menu *</p>
<hr>
<ol>
<li>Load Files</li>
<li>Set Symbols</li>
<li>View Map</li>
<li>Scramble Map</li>
<li>Reset Map</li>
<li>Exit</li>
</ol></li>
</ul>
<p>Error in input.
Try again.</p>
<pre><code>Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at viewer.MapViewerMenu.run(MapViewerMenu.java:92) //points to the finally block at the beginning, where "input.nextLine()" is written.
at viewer.MapViewer.main(MapViewer.java:40) //This is just the original main that runs the program.
</code></pre>
<p><strong>It fails once it returns to the class's original switch statement, but it should just return to the beginning and ask for input for the switch again.</strong></p>
| 3 | 4,475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.