title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Loading multiple images on a page for Blackberry 10
|
<p>I am working on BB10 cascades. I am trying to load multiple images from network. I have referred <a href="http://blackberry.github.io/Cascades-Samples/imageloader.html" rel="nofollow">following example</a> and I have modified it to load a single image. Sample code is as follows:</p>
<p><strong>main.qml</strong></p>
<pre><code>import bb.cascades 1.2
Page {
Container {
id: outer
Container {
preferredHeight: 500
preferredWidth: 768
layout: DockLayout {}
onCreationCompleted: {}
// The ActivityIndicator that is only active and visible while the image is loading
ActivityIndicator {
id: activity
horizontalAlignment: HorizontalAlignment.Center
verticalAlignment: VerticalAlignment.Center
preferredHeight: 300
visible: _loader.loading
running: _loader.loading
}
// The ImageView that shows the loaded image after loading has finished without error
ImageView {
id: image
horizontalAlignment: HorizontalAlignment.Fill
verticalAlignment: VerticalAlignment.Fill
image: _loader.image
visible: !_loader.loading && _loader.label == ""
}
// The Label that shows a possible error message after loading has finished
Label {
id: lable
horizontalAlignment: HorizontalAlignment.Center
verticalAlignment: VerticalAlignment.Center
preferredWidth: 500
visible: !_loader.loading && !_loader.label == ""
text: _loader.label
multiline: true
}
}
Button {
text: "load Image"
onClicked: {
_loader.load();
console.log("loading:::"+_loader.loading);
}
}
}
}</code></pre>
<p><strong>applicatioui.hpp</strong></p>
<pre><code>#ifndef ApplicationUI_HPP_
#define ApplicationUI_HPP_
#include "imageloader.hpp"
#include
namespace bb
{
namespace cascades
{
class LocaleHandler;
}
}
class QTranslator;
class ApplicationUI : public QObject
{
Q_OBJECT
public:
ApplicationUI();
virtual ~ApplicationUI() {}
Q_INVOKABLE void prepareImage();
Q_INVOKABLE void loadImage();
Q_INVOKABLE ImageLoader* getImageloadderInstance();
private slots:
void onSystemLanguageChanged();
private:
ImageLoader* image;
QTranslator* m_pTranslator;
bb::cascades::LocaleHandler* m_pLocaleHandler;
};
#endif /* ApplicationUI_HPP_ */</code></pre>
<p><strong>applicatioui.cpp</strong></p>
<pre><code>#include "applicationui.hpp"
#include
#include
#include
#include
using namespace bb::cascades;
ApplicationUI::ApplicationUI() :
QObject()
{
// prepare the localization
m_pTranslator = new QTranslator(this);
m_pLocaleHandler = new LocaleHandler(this);
image =new ImageLoader("http://uat2.thomascook.in/bpmapp-upload/download/fstore/7f00000105a3d7bf_eb1af9_1485f184f7b_-52f0/GIT_banner.jpg",this);
bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()));
// This is only available in Debug builds
Q_ASSERT(res);
// Since the variable is not used in the app, this is added to avoid a
// compiler warning
Q_UNUSED(res);
// initial load
onSystemLanguageChanged();
// Create scene document from main.qml asset, the parent is set
// to ensure the document gets destroyed properly at shut down.
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
qml->setContextProperty("_loader",this);
// Create root object for the UI
AbstractPane *root = qml->createRootObject();
if(root)
{
}
// Set created root object as the application scene
Application::instance()->setScene(root);
}
void ApplicationUI::onSystemLanguageChanged()
{
QCoreApplication::instance()->removeTranslator(m_pTranslator);
// Initiate, load and install the application translation files.
QString locale_string = QLocale().name();
QString file_name = QString("loading_Image_%1").arg(locale_string);
if (m_pTranslator->load(file_name, "app/native/qm")) {
QCoreApplication::instance()->installTranslator(m_pTranslator);
}
}
ImageLoader* ApplicationUI::getImageloadderInstance()
{
image =new ImageLoader("http://uat2.thomascook.in/bpmapp-upload/download/fstore/7f00000105a3d7bf_eb1af9_1485f184f7b_-52f0/GIT_banner.jpg",this);
return (image);
}
void ApplicationUI::prepareImage()
{
image =new ImageLoader("http://uat2.thomascook.in/bpmapp-upload/download/fstore/7f00000105a3d7bf_eb1af9_1485f184f7b_-52f0/GIT_banner.jpg",this);
}
void ApplicationUI::loadImage()
{
image->load();
}</code></pre>
<p>Now I want to load multiple images. I tried to create <code>QList<QObject*>* image;</code>
and add instances of the <code>ImageLoader</code> class, but I don't know how to access it in main.qml.
Any ideas how to do so?</p>
| 3 | 2,141 |
Load more script for content using jquery
|
<p>I am using below script but it's not working for my script want to keep limit 3 boxes after 3 boxes if user wants more he have to click load more link i gave a live link to see i want load more for that boxes or any new code for load more jsut give me?</p>
<pre><code> <ul id="myList">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
<li>Nine</li>
<li>Ten</li>
<li>Eleven</li>
<li>Twelve</li>
<li>Thirteen</li>
<li>Fourteen</li>
<li>Fifteen</li>
<li>Sixteen</li>
<li>Seventeen</li>
<li>Eighteen</li>
<li>Nineteen</li>
<li>Twenty one</li>
<li>Twenty two</li>
<li>Twenty three</li>
<li>Twenty four</li>
<li>Twenty five</li>
</ul>
<div id="loadMore">Load more</div>
<div id="showLess">Show less</div>
$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
});
$('#showLess').click(function () {
x=(x-5<0) ? 3 : x-5;
$('#myList li').not(':lt('+x+')').hide();
});
});
#myList li{ display:none;
}
#loadMore {
color:green;
cursor:pointer;
}
#loadMore:hover {
color:black;
}
#showLess {
color:red;
cursor:pointer;
}
#showLess:hover {
color:black;
}
</code></pre>
<p>i want to work for this but i was not able to get </p>
<pre><code> <div class="row carousel-row lss">
<div class="col-xs-8 col-xs-offset-2 slide-row">
<div id="carousel-1" class="carousel slide slide-carousel" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators lsse">
<li data-target="#carousel-1" data-slide-to="0" class="active"></li>
<li data-target="#carousel-1" data-slide-to="1"></li>
<li data-target="#carousel-1" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="http://lorempixel.com/150/150?rand=1" alt="Image">
</div>
<div class="item">
<img src="http://lorempixel.com/150/150?rand=2" alt="Image">
</div>
<div class="item">
<img src="http://lorempixel.com/150/150?rand=3" alt="Image">
</div>
</div>
</div>
<div class="slide-content">
<h4>Example product</h4>
<p>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat
</p>
</div>
<div class="slide-footer">
<span class="pull-right buttons">
<button class="btn btn-sm btn-info" onclick="relocateTo('jobtitle.html')"><i class="fa fa-fw fa-eye"></i>View Job</button>
</span>
</div>
</div>
</div>
</code></pre>
<p>live url: <a href="http://projects.santabantathegreat.com/glassicam/design2/dashboard.html" rel="nofollow">click here to see</a></p>
| 3 | 2,195 |
Are Blank Tag Names Causing A Parsing Error?
|
<p>I'm trying to restructure some XML by taking the data, creating a DOM doc, and transferring across just the bits I need, before saving the output, however I keep getting a "XML Parsing Error: no element found: Line Number 1, Column 1:" error. I think it's related to the blank tags inside the first :</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<report title="My Programs" name="aAffiliateMyProgramsReport" time="2012-11-27 16:06">
<matrix rowcount="2">
<rows>
<row>
<>You must select one or more sale events before editing</>
</row>
</rows>
</matrix>
<matrix rowcount="2343">
<rows>
<row>
<siteName>thewebsite.com</siteName>
<affiliateId>123456</affiliateId>
<programName>TheProgram.com</programName>
<currentStatusExcel>Ok</currentStatusExcel>
<programId>203866</programId>
<applicationDate>2012-09-15</applicationDate>
<programTariffAmount>0.0</programTariffAmount>
<programTariffCurrency>GBP</programTariffCurrency>
<programTariffPercentage>0.0</programTariffPercentage>
<status>Accepted</status>
<event>Unique visitor</event>
<eventIdView>2</eventIdView>
<eventLastModified>2011-03-15</eventLastModified>
<segmentID>1</segmentID>
<segmentName>General</segmentName>
<lastModified>2012-09-15</lastModified>
</row>........
</code></pre>
<p>And here's the PHP I'm trying to run:</p>
<pre><code>//contents of MyPrograms report - tested $query in browser many times: it is correct
$query = $q1.$siteID.$q2.$rKey.$q3;
//create DOM document for newTree
$newTree = new DOMDocument();
$newTree->formatOutput =true;
$r = $newTree->createElement ("ProgramTariffs");
$newTree->appendChild($r);
//load contents of MyPrograms report into an xml element
//$oldTree = simplexml_load_file($query);
//that wasn't working so tried file_get_contents instead
$oldTree = file_get_contents($query);
//the above is now at least allowing this script to produce an xml file, but it just contains
"<?xml version="1.0"?> <ProgramTariffs/>"
//and still throws the no element found error.................................
//for each instance of a program id in $oldTree.....
foreach($oldTree->matrix->rows->row as $program)
{ //an attempt to skip over first $program if nothing is set
if (!empty($program->programId)) {
//create the top line container tag
$row = $newTree->createElement ("programTariff");
//create the container tag for programId
$progID = $newTree->createElement("programId");
//fill it with the information you want
$progID->appendChild ( $newTree->createTextNode ( $program->programId ) );
//attach this information to the row
$row->appendChild($progID);
//create the container tag for eventName
$eventName = $newTree->createElement("eventName");
//fill it with the information you want
$eventName->appendChild ( $newTree->createTextNode ( $program->event ) );
//attach this information to the row
$row->appendChild($eventName);
//create the container tag for eventAmount
$eventPercent = $newTree->createElement("eventPercent");
//fill it with the information you want
$eventPercent->appendChild ( $newTree->createTextNode ( $program->programTariffPercentage ) );
//attach this information to the row
$row->appendChild($eventPercent);
//attach all of the above to a row in NewTree
$r->appendChild ($row);
}
}
//save the output
$newTree->save("ProgramTariffs.xml");
</code></pre>
<p>Have I made a basic mistake in accessing the original XML, or do I need to find a better way to work around the row containing a tag name of "<>" ?</p>
<p>I await your wrath / salvation</p>
| 3 | 1,691 |
Can we freeze columns in HTML on basis of colgroup?
|
<p>I was dealing with complex tabular data and wanted to freeze the header and column heading but on the "col" tag.
I can freeze the row heading with position sticky for each tag but then for the second heading when I use-value of the width in the left position the table distorts in some large screens.</p>
<pre><code>th{
position:sticky;
}
tr:nth-child(1){
left:0;
}
tr:nth-child(1){
left:5%;
}
</code></pre>
<p>this doesn't works on large screens.</p>
<p>Sample data:</p>
<pre><code><table border = 1>
<colgroup>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
<col style="widht:5%;" width="5%"/>
</colgroup>
<thead>
<tr>
<th colspan="20">table heading</th>
</tr>
<tr>
<th colspan="10">table subheading 1</th>
<th colspan="10">table subheading 2</th>
</tr>
<tr>
<th colspan="5">table sub1-subheading 1</th>
<th colspan="5">table sub1-subheading 2</th>
<th colspan="5">table sub2-subheading 1</th>
<th colspan="5">table sub2-subheading 2</th>
</tr>
<tr>
<th colspan="3">table sub1-subheading 1</th>
<th colspan="2">table sub1-subheading 2</th>
<th colspan="3">table sub2-subheading 1</th>
<th colspan="2">table sub2-subheading 2</th>
<th colspan="3">table sub1-subheading 1</th>
<th colspan="2">table sub1-subheading 2</th>
<th colspan="3">table sub2-subheading 1</th>
<th colspan="2">table sub2-subheading 2</th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="2">col heading 1</th>
<th>col heading 2</th>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
<tr>
<th>col heading 2</th>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
</tbody>
</table>
</code></pre>
| 3 | 2,753 |
self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200
|
<hr />
<p>This is were the error comes from</p>
<pre><code>def test_single_status_retrieve(self):
serializer_data = ProfileStatusSerializer(instance=self.status).data
response = self.client.get(reverse("status-detail", kwargs={"pk": 1}))
self.assertEqual(response.status_code, status.HTTP_200_OK)
response_data = json.loads(response.content)
self.assertEqual(serializer_data, response_data)
</code></pre>
<p>It seems like the error is coming from somewhere else.</p>
<p>Here is my setUp</p>
<pre><code>def setUp(self):
self.user = User.objects.create_user(username="test2",
password="change123",
)
self.status = ProfileStatus.objects.create(user_profile=self.user.profile,
status_content="status test")
self.token = Token.objects.create(user=self.user)
self.api_authentication()
</code></pre>
<p>here is <strong>urls.py</strong> file</p>
<pre><code>from django.db import router
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from profiles.api.views import (AvatarUpdateView,
ProfileViewSet,
ProfileStatusViewSet,
)
router = DefaultRouter()
router.register(r"profiles", ProfileViewSet)
router.register(r"status", ProfileStatusViewSet, basename="status")
urlpatterns = [
path("", include(router.urls)),
path("avatar/", AvatarUpdateView.as_view(), name="avatar-update"),
]
</code></pre>
<p><strong>This is what I got when I ran the test</strong></p>
<blockquote>
<p>(ProjectName) bash-3.2$ <strong>python3 manage.py test</strong> Creating test database for alias 'default'... System check identified no issues (0
silenced). F.........
================================================================= FAIL: test_single_status_retrieve
(profiles.tests.ProfileStatusViewSetTestCase)
---------------------------------------------------------------------- Traceback (most recent call last): File
"path.../ProjectName/src/profiles/tests.py", line 101, in
test_single_status_retrieve
self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200</p>
<p>---------------------------------------------------------------------- Ran 10 tests in 1.362s</p>
<p>FAILED (failures=1) Destroying test database for alias 'default'...</p>
</blockquote>
| 3 | 1,131 |
getting an attribute from a tag with beautiful soup
|
<p>I am trying to get the attribute 'datetime' but cant seem to do it right for the past couple of hours:</p>
<pre><code> driver.get("https://cointelegraph.com/tags/bitcoin")
time.sleep(10)
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
#print(soup.prettify())
articles = soup.find_all("article")
for article in articles:
print("--------------------------------")
if article.has_attr('datetime'):
print(article['datetime'])
else:
print('no attribute present')
</code></pre>
<p>I execute this and its seems that said attribute is not there:</p>
<pre><code>--------------------------------
no attribute present
--------------------------------
no attribute present
--------------------------------
no attribute present
--------------------------------
no attribute present
--------------------------------
no attribute present
--------------------------------
no attribute present
--------------------------------
</code></pre>
<p>I checked the HTML and the 'datetime' attribute is there within the 'article' tag. But it looks like it only has one attribute which is 'class'.</p>
<pre><code><article class="post-card-inline" data-v-a5013924="">
<a class="post-card-inline__figure-link" href="/news/top-5-cryptocurrencies-to-watch-this-week-btc-xrp-link-bch-fil">
<figure class="post-card-inline__figure">
<div class="lazy-image post-card-inline__cover lazy-image_loaded">
<span class="pending lazy-image__pending pending_dark pending_finished">
<span class="pending__runner">
</span>
</span>
<!-- -->
<img alt="Top 5 cryptocurrencies to watch this week: BTC, XRP, LINK, BCH, FIL" class="lazy-image__img" pinger-seen="true" src="https://images.cointelegraph.com/images/370_aHR0cHM6Ly9zMy5jb2ludGVsZWdyYXBoLmNvbS91cGxvYWRzLzIwMjItMDQvYWJlMzJhMjYtMmMwMi00ODczLTllNGUtYWQ2ZTdmMzEzOGNlLmpwZw==.jpg" srcset="https://images.cointelegraph.com/images/370_aHR0cHM6Ly9zMy5jb2ludGVsZWdyYXBoLmNvbS91cGxvYWRzLzIwMjItMDQvYWJlMzJhMjYtMmMwMi00ODczLTllNGUtYWQ2ZTdmMzEzOGNlLmpwZw==.jpg
1x, https://images.cointelegraph.com/images/740_aHR0cHM6Ly9zMy5jb2ludGVsZWdyYXBoLmNvbS91cGxvYWRzLzIwMjItMDQvYWJlMzJhMjYtMmMwMi00ODczLTllNGUtYWQ2ZTdmMzEzOGNlLmpwZw==.jpg 2x"/>
</div>
<span class="post-card-inline__badge post-card-inline__badge_default">
Price Analysis
</span>
</figure>
</a>
<div class="post-card-inline__content">
<div class="post-card-inline__header">
<a class="post-card-inline__title-link" href="/news/top-5-cryptocurrencies-to-watch-this-week-btc-xrp-link-bch-fil">
<span class="post-card-inline__title">
Top 5 cryptocurrencies to watch this week: BTC, XRP, LINK, BCH, FIL
</span>
</a>
<div class="post-card-inline__meta">
<time class="post-card-inline__date" datetime="2022-04-17">
4 hours ago
</time>
<p class="post-card-inline_
...
</code></pre>
| 3 | 1,463 |
Weird behavior of Redux thunk in a React Native app
|
<p>I recently noticed a very weird behavior of Redux in my app that I would like to share with you. When I click this TouchableOpacity in my settings in order to disconnect, I get the following error: </p>
<blockquote>
<p>TypeError: Cannot read property first_name of null</p>
</blockquote>
<p>from Homepage.js</p>
<p>So my code is firing an error for that piece component that is in a page where I'm not supposed to go.</p>
<p><strong>Homepage.js</strong></p>
<pre><code><AppText textStyle={styles.title}>
Welcome {userReducer.infos.first_name}
</AppText>
</code></pre>
<p>The workflow that is supposed to happen is the user clicking on the disconnect button, then the tryLogout function is called, which fires the action with the type 'LOGOUT'. Then this action sets to null user related data and information with some additional booleans. The state gets updated then the UI should be re-rendered and componentWillUpdate() called. In there, I check my state to redirect the user to the landing/not connected navigation.</p>
<p>I tried to comment <code>infos: null</code> in my reducer and my code processes without errors.</p>
<p>This variable is nowhere in my app asking to redirect to any page.</p>
<p>It may seem complicated to debug, since the problem must be deeper than it looks. Anyway, maybe someone has already had a similar problem so I give you here the potential elements to try to solve the problem.</p>
<p><strong>Settings.js</strong></p>
<pre><code>import { tryLogout } from '@actions/user'
const mapDispatchToProps = dispatch => ({
tryLogout: () => dispatch(tryLogout()),
})
class Settings extends React.Component<Props, State> {
// What should normally happen
componentDidUpdate(prevProps: Props) {
const { userReducer, navigation } = this.props
if (
prevProps.userReducer.isSignedUp !== userReducer.isSignedUp ||
prevProps.userReducer.isLoggedIn !== userReducer.isLoggedIn
) {
if (!userReducer.isSignedUp && !userReducer.isLoggedIn) {
navigation.navigate('Landing')
}
}
}
// Inside my render() method
<AppTouchableOpacity
onPress={() => tryLogout()}
style={styles.touchableOpacity}
>
Disconnect
</AppTouchableOpacity>
}
</code></pre>
<p><strong>actions/user.js</strong></p>
<pre><code>export const tryLogout = (): Function => (dispatch: Function) => {
const logout = () => ({
type: LOGOUT,
})
dispatch(logout())
}
</code></pre>
<p><strong>reducers/user.js</strong></p>
<pre><code>case LOGOUT:
return {
...state,
data: null,
infos: null,
isLoggedIn: false,
isSignedUp: false,
}
</code></pre>
<p><strong>App.js</strong> (I'm using React Navigation)</p>
<pre><code>const LandingScenes = {
Welcome: { screen: WelcomeScreen },
{ /* Some other screens */ }
}
const LandingNavigator = createStackNavigator(LandingScenes, {
initialRouteName: 'Welcome',
defaultNavigationOptions: {
header: null,
},
})
const SecuredScenes = {
Homepage: { screen: HomepageScreen },
Settings: { screen: SettingsScreen },
{ /* Some other screens */ }
}
const SecuredNavigator = createStackNavigator(SecuredScenes, {
initialRouteName: 'Homepage',
defaultNavigationOptions: {
header: null,
},
})
export default createAppContainer(
createSwitchNavigator(
{
Landing: LandingNavigator,
Secured: SecuredNavigator,
},
{
initialRouteName: 'Landing',
}
)
)
</code></pre>
| 3 | 1,249 |
Draggable left side of screen (JQuery)
|
<p>I'm wondering if someone can help me work out the offset of <code>left</code> side of the screen. I've currently got the <code>right</code> side done and you can see the example below. However I want the same for <code>left</code> side with the text saying "Not Interested".</p>
<p>Could someone please point me in the right direction or help me out achieve this? </p>
<p>Also if anyone wants to give feedback on my current code, if they have any better way of doing this.</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(){
var currentDiff;
var currentOpacity;
$("#event_container .content .card").draggable({
drag: function(el, ui){
var cardWidth = $(this).width();
var bodyWidth = $("body");
var rightOverlay = $(this).offset().left + (cardWidth * .6);
var leftOverlay = ($(this).offset().left - cardWidth) / 6;
if(rightOverlay > cardWidth){
var widthDiff = rightOverlay - cardWidth;
if(!$("#interested-message").is(":visible")){
currentDiff = 0;
currentOpacity = 0;
}
if(widthDiff > 175){
if(currentDiff === 0){
currentOpacity = 0.1;
$("#interested-message").addClass("interested").css("opacity", currentOpacity).text("Interested").show();
currentDiff = widthDiff;
} else if((currentDiff + 20) > currentDiff) {
if(currentOpacity !== 1){
currentOpacity = currentOpacity + 0.1;
$("#interested-message").addClass("interested").css("opacity", currentOpacity);
currentDiff = widthDiff;
}
}
} else {
$("#interested-message").css("opacity", 0).hide().text("....");
}
} else {
$("#interested-message").css("opacity", 0).hide().text("....");
}
if(leftOverlay > cardWidth){
var widthDiff = leftOverlay - cardWidth;
console.log(widthDiff);
} else {
console.log(leftOverlay);
}
}
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#interested-message{
display: none;
position: absolute;
width: auto;
padding: 5px 15px!important;
z-index: 100;
border-radius: 6px;
font-size: 30px;
top: calc(45% - 100px);
left: calc(25% - 100px);
opacity: 0;
}
#interested-message.interested{
display: block;
border: 2px solid #0b9c1e;
color: #0b9c1e;
}
#interested-message.not-interested{
display: block;
border: 2px solid #d93838;
color: #d93838;
}
#body{
width: 250px;
height: 600px;
max-width: 250px;
max-height: 600px;
border: 2px solid black;
overflow: hidden;
}
#event_container{
height: 100%;
width: 100%;
background: lightblue;
padding: 50px;
}
#event_container .content{
position: relative;
}
#event_container .content .card{
border: 2px solid black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="body">
<div id="event_container">
<div id="interested-message">....</div>
<div class="content">
<div class="card">
Test card
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| 3 | 1,908 |
PHP Javascript - cannot change selector onclick to Remove preview files
|
<p>I'm doing upload multiple files(use <code><input type="file" multiple/></code>) with preview image file and can remove the image preview and filedata successfully.</p>
<p>but the problem is, I cannot change the selector for onclick to remove filedata.
(If I change to other selector, it will only remove the preview image but the files still be uploaded to my folder)</p>
<p>The selector for click to remove that work successfully is <code>.selFile</code> but when
I want to change selector for onclick to <code>.selFile2</code> it will not remove filedata) </p>
<p>these are my focus line of code. (To see my Full code, Please look on bottom) </p>
<pre><code> var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile'
title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
</code></pre>
<p>..</p>
<p>I change from </p>
<pre><code>$("body").on("click", ".selFile", removeFile);
</code></pre>
<p>to</p>
<pre><code>$("body").on("click", ".selFile2", removeFile);
</code></pre>
<p>but it remove preview image only not remove filedata (it's still be uploaded to my folder)
..</p>
<p>And I try to change code in <code>function removeFile(e)</code>
from <code>var file = $(this).data("file");</code> to <code>var file = $('.selFile).data("file");</code> the result is It can remove only 1 filedata.
...
How could I do?</p>
<p>Here is my full code (2 pages)</p>
<p>firstpage.html (I use ajax to post form)</p>
<pre><code><!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
cursor:pointer;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if(!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
</code></pre>
<p>..
upload.php page</p>
<pre><code><?php
for($i=0;$i < count($_FILES["files"]["name"]);$i++)
{
if($_FILES["files"]["name"][$i] != "")
{
$tempFile = $_FILES['files']['tmp_name'][$i];
$targetFile = "upload/". $_FILES["files"]["name"][$i];
move_uploaded_file($tempFile,$targetFile);
}
}
?>
</code></pre>
| 3 | 2,206 |
PHP form required fields error message not shown
|
<p>Why there's no error message shown in the browser window?
(had more fields but reduced all to a minimum)
There is just nothing happening but that it is redirecting to the 'save_entries.php'.
I would have liked the error message in the table as first row, second column.</p>
<p>The code:</p>
<pre><code><?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
if (empty($_POST['name']))
{
$errors['name'] = "Please insert your name!";
}
if (count($errors) == 0)
{
header("Location: save_entries.php");
exit();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<title>Guestbook</title>
</head>
<body>
<form action="save_entries.php" method="POST">
<div>
<table class="entryForm">
<tbody>
<tr>
<td></td>
<td class="error">
<?php
if(isset($errorMeldung['name']))
echo $errorMeldung['name'];
?>
</td>
</tr>
<tr>
<td class="labels">
<label for="name">Your Name:
<span>*</span>
</label>
</td>
<td class="fields">
<input type="text" name="name" id="name"
value="" maxlength="64" />
</td>
</tr>
<tr>
<td class="labels">
</td>
<td class="fields">
<input type="submit" class="submit button1"
value="Submit" />
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>
</code></pre>
| 3 | 1,294 |
Split a single linked list into 2 SIngly linked lists -one containing nodes with even data and other containing nodes with odd data
|
<p>I tried coding the above problem but I'm getting a segmentation error.Below is the code that I've written :</p>
<pre><code> #include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct oddeven
{
int data;
struct oddeven *link;
};
typedef struct oddeven m;
int main()
{
int z;
m *head=NULL,*ptr,*current;
m *x,*y,*q,*head1=NULL,*current1,*head2=NULL,*current2;
while(1)
{
int ch;
ptr=(m*)malloc(sizeof(m));
printf("Enter the data: ");
scanf("%d",&ptr->data);
ptr->link=NULL;
if(head==NULL)
{
head=ptr;
current=ptr;
}
else
{
current->link=ptr;
current=ptr;
}
printf("Do you want to continue?Y=1/N=0");
scanf("%d",&ch);
if(ch!=1)
break;
}
x=head;
while(x!=NULL)
{
z=x->data;
if(z%2==0)
{
ptr=(m*)malloc(sizeof(m));
ptr->data=z;
ptr->link=NULL;
if(head1==NULL)
{
head1=ptr;
current1=ptr;
}
else
{
current1->link=ptr;
current1=ptr;
}
}
else
{
ptr=(m*)malloc(sizeof(m));
ptr->data=z;
ptr->link=NULL;
if(head2=NULL)
{
head2=ptr;
current2=ptr;
}
else
{
current2->link=ptr;
current2=ptr;
}
}
x=x->link;
}
y=head1;
q=head2;
while (y!=NULL)
{
printf("%d\t",y->data);
y=y->link;
}
printf("\n");
while (q!=NULL)
{
printf("%d\t",q->data);
q=q->link;
}
}
</code></pre>
<p>I can't figure out where am I going wrong. Any help would be much appreciated.
It takes the inputs but after that it says segmentation error. Split the given single linked list into two where I can store the odd vales and even values separately .I tried different methods but couldn't get it to work.</p>
| 3 | 2,145 |
How to make End Date 1 day after the Start Day on android datePicker
|
<p>i have a project that should bring end date after the start date on android datepicker.
(user will chose any date on start date and when user click end date what ever user choose end date should be one day after start date)</p>
<p>for this purpose i have a Kotlin code as in below;</p>
<pre><code>private fun showDatePickerDialog(type: Int) {
calendar = Calendar.getInstance()
year = calendar!!.get(Calendar.YEAR)
month = calendar!!.get(Calendar.MONTH)
dayOfMonth = calendar!!.get(Calendar.DAY_OF_MONTH)
datePickerDialog = DatePickerDialog(
requireContext(), R.style.MyDatePickerStyle,
{ datePicker, year, month, day ->
if (type == 0){
var month = month + 1
var startMonthConverted = ""+month
var startDayConverted = ""+day
if(month<10){
startMonthConverted = "0$startMonthConverted"
}
if(day<10){
startDayConverted= "0$startDayConverted"
}
binding.txtStartDate.setText("$year-$startMonthConverted-$startDayConverted")
} else {
var month = month + 1
var monthConverted = ""+month
var dayConverted = ""+day
if(month<10){
monthConverted = "0$monthConverted";
}
if(day<10){
dayConverted = "0$dayConverted"
}
binding.txtEndDate.setText("$year-$monthConverted-$dayConverted")
}
},
year,
month,
dayOfMonth
)
if (type == 0) {
val startDay = Calendar.getInstance()
startDay.add(Calendar.DAY_OF_YEAR, 2);
datePickerDialog!!.datePicker.minDate = startDay.timeInMillis
} else {
val endDay = Calendar.getInstance()
endDay.add(Calendar.DATE, 2)
// datePickerDialog!!.datePicker.minDate = endDay.timeInMillis
datePickerDialog!!.getDatePicker().setMinDate(endDay.getTimeInMillis());
}
val df: DateFormat = SimpleDateFormat("'T'HH:mm:ss.SSS")
currentTime = df.format(Calendar.getInstance().timeInMillis)
Log.d("TAG", "currentTime:$currentTime ")
datePickerDialog!!.show()
//set OK/Cancel buttons color
//set OK/Cancel buttons color
datePickerDialog!!.getButton(Dialog.BUTTON_POSITIVE)
.setTextColor(android.graphics.Color.BLACK)
datePickerDialog!!.getButton(Dialog.BUTTON_NEGATIVE)
.setTextColor(android.graphics.Color.BLACK)
}
</code></pre>
| 3 | 1,308 |
Chart.js Show label/tooltip for single point when multiple points coincide
|
<p>I have a Chart.js scatter plot where data points from two different datasets occasionally coincide/overlap. They have the same x and y coordinate. On default, when the points are hovered, the tooltip shows info for both data points. My desired behavior is to get the information for the first overlapping point only. I can achieve this using tooltips' mode set to 'single'.</p>
<pre><code>var config = {
options: {
tooltips: {
mode: "single"
}
}
}
</code></pre>
<p>Although this works fine, my question/problem arises because chart.js' documentation states that mode 'single' is <a href="https://www.chartjs.org/docs/latest/general/interactions/modes.html#single-deprecated" rel="nofollow noreferrer">deprecated</a>. It suggests using mode 'nearest' with intersect set to 'true' would achieve the same result, however <a href="https://jsfiddle.net/f5epdn2w/" rel="nofollow noreferrer">it doesn't</a>.</p>
<p>Below is a reproduction of the issue:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</head>
<body>
<canvas></canvas>
</body>
<script>
var config = {
type: "scatter",
data: {
labels: ["label1", "label2"],
datasets: [{label: "label1", data:[{x: 1, y:1},{x: 2, y:2},{x: 3, y:3},{x: 4, y:4},{x: 5, y:2}], backgroundColor: "rgb(155,0,0)"},{label: "label2", data:[{x: 1, y:1},{x: 2, y:4},{x: 3, y:3},{x: 4, y:6},{x: 5, y:8}], backgroundColor: "rgb(0,0,155)"}]
},
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
yAxes: [{
type: "linear",
scaleLabel: {
display: true,
labelString: "labels",
fontStyle: "bold"
},
ticks: {
autoSkip: true,
maxTicksLimit: 7
}
}],
xAxes: [{
type: "linear",
beginAtZero: true
}]
},
tooltips: {
mode: "nearest",
intersect: true
}
}
}
var chart = new Chart(document.querySelector("canvas"), config);
</script>
</html></code></pre>
</div>
</div>
</p>
<p>And here is the desired behavior with the deprecated 'single' argument:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</head>
<body>
<canvas></canvas>
</body>
<script>
var config = {
type: "scatter",
data: {
labels: ["label1", "label2"],
datasets: [{label: "label1", data:[{x: 1, y:1},{x: 2, y:2},{x: 3, y:3},{x: 4, y:4},{x: 5, y:2}], backgroundColor: "rgb(155,0,0)"},{label: "label2", data:[{x: 1, y:1},{x: 2, y:4},{x: 3, y:3},{x: 4, y:6},{x: 5, y:8}], backgroundColor: "rgb(0,0,155)"}]
},
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
yAxes: [{
type: "linear",
scaleLabel: {
display: true,
labelString: "labels",
fontStyle: "bold"
},
ticks: {
autoSkip: true,
maxTicksLimit: 7
}
}],
xAxes: [{
type: "linear",
beginAtZero: true
}]
},
tooltips: {
mode: "single"
}
}
}
var chart = new Chart(document.querySelector("canvas"), config);
</script>
</html></code></pre>
</div>
</div>
</p>
<p>Any ideas on how to resolve this issue? Especially for people who might run into this issue if/when 'single' is removed. Thank you, cheers.</p>
| 3 | 2,499 |
is there a javascript method for telling us if a input range slider value is going up vs down?
|
<p>I'm trying to group input range sliders or 'faders' together so that one 'Group Fader' can control two or more faders while keeping their respective relative values intact.
So if fader One has a value of '50' and fader Two has a value of '75' When we group them together and increase the Group Fader by +20, faders one and two will move simultaneously and have their new new respective values 70 and 95.</p>
<p>I'm playing a shell game with variables and losing.. this is beyond my 'scope'=) hoping there's an easier way. Go easy on me this is my first question.</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>const faderOne = document.getElementById('one'),
faderTwo = document.getElementById('two'),
groupFader = document.getElementById('grouped'),
output1 = document.getElementById('output1'),
output2 = document.getElementById('output2'),
output3 = document.getElementById('output3'),
output4 = document.getElementById('output4'),
groupBtn = document.getElementById('grouped-btn')
let locked
faderOne.addEventListener('input', showOutput)
faderTwo.addEventListener('input', showOutput)
groupFader.addEventListener('input', gang)
groupBtn.addEventListener('click', function toggleGrouped() {
locked = locked ? false : true;
console.log('grouped = ', locked)
let groupValue = '0';
output3.innerHTML = groupValue;
})
function showOutput() {
let oneValue = faderOne.value,
twoValue = faderTwo.value,
groupValue = groupFader.value;
output1.innerHTML = oneValue;
output2.innerHTML = twoValue;
output3.innerHTML = groupValue;
//console.log(oneValue, twoValue);
}
showOutput();
// if the group feature is 'enabled' (checkbox checked)
//then the Group Fader would control both Fader One and Fader Two respectively. Keeping their relative values intact during any movements the group faders makes up or down
// some way to disable the group fader function and return to the original ungrouped state. or separate function
//let groupLast = groupFader.value;
let groupLast = 0
function gang() {
let groupValue = '0'
let groupUp = groupValue
let groupDown = groupValue
let groupNew = groupFader.value
if (locked !== true) {
output4.innerText = 'You must enable group to use the Group Fader.'
// Lock? GROUP FADER value at 127 (0-255) to accommodate potential values up and down
// or hide display of GROUP FADER until checkbox 'enabled'.?
groupValue = '0'
} else if (locked === true) {
//console.log('gang faders')
//release Group Fader value
groupValue = groupFader.value;
output3.innerHTML = groupValue;
output4.innerText = 'Group Fader is active.'
//variable for 'previous' Group Fader Value --- is new value higher or lower?
console.log('group', groupValue)
console.log('groupLast', groupLast)
if (groupNew > groupLast) {
//console.log(control)
//REPLACE stepUp!
document.getElementById("one").stepUp(1);
document.getElementById("two").stepUp(1);
groupUp = groupFader.value
groupNew = groupUp
console.log('groupUp', groupUp)
output1.innerHTML = one.value
output2.innerHTML = two.value
} else if (groupNew < groupLast) {
groupDown = groupFader.value
//REPLACE stepDown!
console.log('groupDown', groupDown)
groupNew = groupDown
document.getElementById("one").stepDown(1);
document.getElementById("two").stepDown(1);
} else if (locked !== true) {
document.getElementById('output4').innerText = 'You must enable group to use the Group Fader.'
groupValue = '0'
return;
}
groupLast = groupNew
console.log('new', groupNew)
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font: 1.3rem system-ui;
background-color: #ccc;
}
input.fader {
width: 50%;
}
.level {
font-size: 0.75rem;
color: #222;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class='fader' type='range' id='one' value='64' min='0' max='127'>
<span id='output1' class='level'></span><label for='one'> Fader One</label>
<br>
<input class='fader' type='range' id='two' value='64' min='0' max='127'>
<span id='output2' class='level'></span><label for='two'> Fader Two</label>
<br>
<input type="checkbox" id="grouped-btn" name="grouped" value="false">
<label for="grouped-btn"> group enable/disable </label>
<br>
<input class='fader' type='range' id='grouped' value='0' min='-127' max='127'>
<span id='output3' class='level'></span><label for='grouped'>Group Fader</label><br>
<span id='output4' class='level'></span></code></pre>
</div>
</div>
</p>
| 3 | 1,762 |
Unable to get child of Current User Id for RecyclerView
|
<p>I want to set RecyclerView with Child of Current User Id by using <code>getCurrentUser().getUid()</code>.The data structure you can see in image below, <a href="https://i.stack.imgur.com/PTLbH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PTLbH.png" alt="enter image description here"></a></p>
<p>In image above, <strong>SQyOq80egYehjqx4sgiyeNcW8P02</strong> is <strong>current userId</strong> and I want to get all child of those id and show in RecyclerView. In above image, the child is <strong>wed5qPTCdcQVzVlRcBrMo1NX43v1</strong> and their value is <strong>Sep 29, 2018</strong>. My question is how to get those childern values separately and show in RecyclerView. As an example, I wrote code for <strong>Date</strong> (the value of current userId), which gives fatal error. I know error in Model class which I am unable to understand. </p>
<p><strong>Note:</strong> this line gives error. <code>Log.d("sdfsdfdgfdfsdfd", blogPost.getDate());</code></p>
<p>Activity:</p>
<pre><code> protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Friends").child(uid);
FirebaseRecyclerOptions<BlogPost> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<BlogPost>()
.setQuery(query, BlogPost.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<BlogPost, BlogPostHolder>(firebaseRecyclerOptions) {
@Override
protected void onBindViewHolder(@NonNull BlogPostHolder blogPostHolder, int position, @NonNull BlogPost blogPost) {
Log.d("sdfsdfdgfdfsdfd", blogPost.getDate());
blogPostHolder.setBlogPost(blogPost);
}
@Override
public BlogPostHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new BlogPostHolder(view);
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
@Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
if (firebaseRecyclerAdapter!= null) {
firebaseRecyclerAdapter.stopListening();
}
}
private class BlogPostHolder extends RecyclerView.ViewHolder {
private TextView userDateTextView;
BlogPostHolder(View itemView) {
super(itemView);
userDateTextView = itemView.findViewById(R.id.user_date);
}
void setBlogPost(BlogPost blogPost) {
String date = blogPost.getDate();
userDateTextView.setText(date);
}
}
}
</code></pre>
<p>Model:</p>
<pre><code>public class BlogPost {
public String date;
public BlogPost() {}
public BlogPost(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
</code></pre>
| 3 | 1,453 |
Permission denied (missing INTERNET permission?) when using exoplayer
|
<p>I am beginner in android i try to use ExoPlayer to show video but i have a problem when trying to run the elumater it crashes and give me that error in the logcat "Unexpected exception loading stream "</p>
<p><strong>This is my Logcat error</strong></p>
<pre class="lang-html prettyprint-override"><code>10-17 17:31:12.619 8321-8631/com.example.abdelmagied.bakingapp E/LoadTask: Unexpected exception loading stream
java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:464)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java)
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:427)
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:351)
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:193)
at com.google.android.exoplayer2.upstream.DefaultDataSource.open(DefaultDataSource.java:123)
at com.google.android.exoplayer2.source.ExtractorMediaPeriod$ExtractingLoadable.load(ExtractorMediaPeriod.java:623)
at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:295)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.android_getaddrinfo(Native Method)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
</code></pre>
<p><strong>This is my manifest file</strong></p>
<pre class="lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abdelmagied.bakingapp">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".recipeDetailsActivity" />
<activity android:name=".recipeFragment" />
<activity android:name=".stepDetailActivity"></activity>
</application>
</manifest>
</code></pre>
<p><strong>Activity containing Exoplayer</strong></p>
<pre class="lang-html prettyprint-override"><code>package com.example.abdelmagied.bakingapp;
import android.app.NotificationManager;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.example.abdelmagied.bakingapp.recipeContents.steps;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.AdaptiveVideoTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import butterknife.BindView;
import butterknife.ButterKnife;
public class stepDetailActivity extends AppCompatActivity implements ExoPlayer.EventListener {
private SimpleExoPlayer mExoPlayer;
private SimpleExoPlayerView mPlayerView;
private static MediaSessionCompat mMediaSession;
private PlaybackStateCompat.Builder mStateBuilder;
@BindView(R.id.description)
public TextView descrip;
private static final String TAG = stepDetailActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_detail);
steps myrecipes = (steps) getIntent().getParcelableExtra("stepDetails");
mPlayerView = (SimpleExoPlayerView) findViewById(R.id.player);
initializeMediaSession();
initializePlayer(Uri.parse("https://d17h27t6h515a5.cloudfront.net/topher/2017/April/58ffd9cb_4-press-crumbs-in-pie-plate-creampie/4-press-crumbs-in-pie-plate-creampie.mp4"));
descrip.setText(myrecipes.getDescription());
}
private void initializePlayer(Uri mediaUri) {
if (mExoPlayer == null) {
// Create an instance of the ExoPlayer.
TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
mExoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
mPlayerView.setPlayer(mExoPlayer);
// Prepare the MediaSource.
String userAgent = Util.getUserAgent(this, "Bakingapp");
MediaSource mediaSource = new ExtractorMediaSource(mediaUri, new DefaultDataSourceFactory(
this, userAgent), new DefaultExtractorsFactory(), null, null);
mExoPlayer.prepare(mediaSource);
mExoPlayer.setPlayWhenReady(true);
// Set the ExoPlayer.EventListener to this activity.
mExoPlayer.addListener(this);
}
}
/**
* Initializes the Media Session to be enabled with media buttons, transport controls, callbacks
* and media controller.
*/
private void initializeMediaSession() {
// Create a MediaSessionCompat.
mMediaSession = new MediaSessionCompat(this, TAG);
// Enable callbacks from MediaButtons and TransportControls.
mMediaSession.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
// Do not let MediaButtons restart the player when the app is not visible.
mMediaSession.setMediaButtonReceiver(null);
// Set an initial PlaybackState with ACTION_PLAY, so media buttons can start the player.
mStateBuilder = new PlaybackStateCompat.Builder()
.setActions(
PlaybackStateCompat.ACTION_PLAY |
PlaybackStateCompat.ACTION_PAUSE |
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
PlaybackStateCompat.ACTION_PLAY_PAUSE);
mMediaSession.setPlaybackState(mStateBuilder.build());
// MySessionCallback has methods that handle callbacks from a media controller.
mMediaSession.setCallback(new MySessionCallback());
// Start the Media Session since the activity is active.
mMediaSession.setActive(true);
}
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if((playbackState == ExoPlayer.STATE_READY) && playWhenReady){
mStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING,
mExoPlayer.getCurrentPosition(), 1f);
} else if((playbackState == ExoPlayer.STATE_READY)){
mStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED,
mExoPlayer.getCurrentPosition(), 1f);
}
mMediaSession.setPlaybackState(mStateBuilder.build());
}
@Override
public void onPlayerError(ExoPlaybackException error) {
}
@Override
public void onPositionDiscontinuity() {
}
/**
* Media Session Callbacks, where all external clients control the player.
*/
private class MySessionCallback extends MediaSessionCompat.Callback {
@Override
public void onPlay() {
mExoPlayer.setPlayWhenReady(true);
}
@Override
public void onPause() {
mExoPlayer.setPlayWhenReady(false);
}
@Override
public void onSkipToPrevious() {
mExoPlayer.seekTo(0);
}
}
}
</code></pre>
<p><strong>This is my XML layout</strong></p>
<pre class="lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.abdelmagied.bakingapp.stepDetailActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.exoplayer2.ui.SimpleExoPlayerView
android:id="@+id/player"
android:layout_width="match_parent"
android:layout_height="300dp"
>
</com.google.android.exoplayer2.ui.SimpleExoPlayerView>
<ScrollView
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id = "@+id/description"
android:text = "som mu"
android:textSize = "20dp"
/>
</ScrollView>
</LinearLayout>
</RelativeLayout>
</code></pre>
| 3 | 4,811 |
Scraping Data from a table with Scrapy but not Scraped Items
|
<p>I'm trying out Scrapy for first time.After doing fair bit of research I got the basics. Now I was trying to get data of a table. It isn't working. <strong>not Scraped any data</strong>. Check below for source codes.</p>
<p>settings.py </p>
<pre><code>BOT_NAME = 'car'
SPIDER_MODULES = ['car.spiders']
NEWSPIDER_MODULE ='car.spiders'
DEFAULT_ITEM_CLASS = 'car.items.Car58Item'
ITEM_PIPELINES = {'car.pipelines.JsonLinesItemExporter': 300}
</code></pre>
<p>items.py </p>
<pre><code>from scrapy.item import Item,Field
class Car58Item(Item):
# define the fields for your item here like:
# name = scrapy.Field()
url = Field()
tip = Field()
name = Field()
size = Field()
region = Field()
amt = Field()
</code></pre>
<p>car_spider.py</p>
<pre><code># -*- coding=utf-8 -*-
from __future__ import absolute_import
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider,Rule,Spider
from car.items import Car58Item
class CarSpider (CrawlSpider):
name ='car'
allowed_domains = ['58.com']
start_urls = ['http://quanguo.58.com/ershouche']
rules = [Rule(LinkExtractor(allow=('/pn\d+')),'parse_item')] #//页面读取策略
def parse_item(self,response):
trs = response.xpath("//div[@id='infolist']/table[@class='tbimg']/tr")[1:-2]
items = []
#for tr in sel.xpath("id('infolist')/table/tr"):
for tr in trs:
item = Car58Item()
item['url'] = tr.xpath("td[@class='img']/a/@href").extract()
item['tip'] = tr.xpath("td[@class='t']/a/font/text()").extract()
item['name'] = tr.xpath("td[@class='t']/a[1]/text()").extract()
item['size'] = tr.xpath("td[@class='t']/p").extract()
item['region'] = tr.xpath("td[@class='tc']/a/text()").extract()
item['amt'] = tr.xpath("td[@class='tc']/b/text()").extract()
items.append(item)
return items
</code></pre>
<p>pipelines.py </p>
<pre><code># -*- coding: utf-8 -*-
import json
import codecs
class JsonLinesItemExporter(object):
def __init__(self):
self.file = codecs.open('car.json','w',encoding='utf-8')
def process_item(self, items, spider):
line = json.dumps(dict(items),ensure_ascii=False) + "\n"
self.file.write(line)
return items
def spider_closed(self,spider):
self.file.close()
</code></pre>
<p>i running scrapy in shell </p>
<pre><code> [mayuping@i~/PycharmProjects/car] $**scrapy crawl car**
2016-05-18 10:35:36 [scrapy] INFO: Scrapy 1.0.6 started (bot: car)
2016-05-18 10:35:36 [scrapy] INFO: Optional features available: ssl, http11
2016-05-18 10:35:36 [scrapy] INFO: Overridden settings: {'DEFAULT_ITEM_CLASS': 'car.items.Car58Item', 'NEWSPIDER_MODULE': 'car.spiders', 'SPIDER_MODULES': ['car.spiders'], 'BOT_NAME': 'car'}
2016-05-18 10:35:36 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, LogStats, CoreStats, SpiderState
2016-05-18 10:35:36 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2016-05-18 10:35:36 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2016-05-18 10:35:36 [scrapy] INFO: Enabled item pipelines: JsonLinesItemExporter
2016-05-18 10:35:36 [scrapy] INFO: Spider opened
2016-05-18 10:35:36 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-05-18 10:35:36 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2016-05-18 10:35:37 [scrapy] DEBUG: Redirecting (301) to <GET http://quanguo.58.com/ershouche/> from <GET http://quanguo.58.com/ershouche>
2016-05-18 10:35:39 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/> (referer: None)
2016-05-18 10:35:40 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn2/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:42 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn7/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:42 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn6/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:42 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn12/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:43 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn11/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:44 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn9/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:45 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn8/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:45 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn5/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:46 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn10/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:46 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn4/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:46 [scrapy] DEBUG: Crawled (200) <GET http://quanguo.58.com/ershouche/pn3/> (referer: http://quanguo.58.com/ershouche/)
2016-05-18 10:35:47 [scrapy] INFO: Closing spider (finished)
2016-05-18 10:35:47 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 5550,
'downloader/request_count': 13,
'downloader/request_method_count/GET': 13,
'downloader/response_bytes': 339809,
'downloader/response_count': 13,
'downloader/response_status_count/200': 12,
'downloader/response_status_count/301': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2016, 5, 18, 2, 35, 47, 45187),
'log_count/DEBUG': 14,
'log_count/INFO': 7,
'request_depth_max': 1,
'response_received_count': 12,
'scheduler/dequeued': 13,
'scheduler/dequeued/memory': 13,
'scheduler/enqueued': 13,
'scheduler/enqueued/memory': 13,
'start_time': datetime.datetime(2016, 5, 18, 2, 35, 36, 733155)}
2016-05-18 10:35:47 [scrapy] INFO: Spider closed (finished)
</code></pre>
<p>but not scrapy any data...</p>
<pre><code>[mayuping@i~/PycharmProjects/car] $more car.json
</code></pre>
<p>zero items output in car.json.</p>
<p>thanks</p>
| 3 | 2,738 |
error in custom list adapter class
|
<p>I am trying to get server responce and store it in different string array but when i call adapter class till now it is fine but in adapter class will give me error.</p>
<pre><code> class viewticket extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(UserLogedIn.this);
pdialog.setMessage("Loading....");
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
pdialog.show();
}
@Override
protected String doInBackground(String... params) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("userid", u_id));
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URLMyTicket, ServiceHandler.POST, param);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try {
contacts = new JSONArray(jsonStr);
int a=contacts.length();
Log.v(TAG,""+a);
String[] id = new String[contacts.length()];
String[] prob = new String[contacts.length()];
String[] desc = new String[contacts.length()];
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String aa = c.getString(TAG_ID);
String bb = c.getString(TAG_PROB);
String cc = c.getString(TAG_DESC);
Log.v(TAG, "TAG_ID" + aa);
Log.v(TAG,"TAGPROB"+bb);
Log.v(TAG,"TAGDESC"+cc);
id[i] = aa;
prob[i]=bb;
desc[i]=cc;
Log.v(TAG, "aaaaa" + id[i]);
Log.v(TAG,"bbbbb"+prob[i]);
Log.v(TAG,"ccc"+desc[i]);
Ticket_adapter adapter=new Ticket_adapter(this,id,prob,desc);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
System.out.print("hiiiiiiiiiiii" );
e.printStackTrace();
}
}
if(jsonStr==null)
{
// Toast.makeText(UserLogedIn.this, "hiiiiiiiiiiiiiiiiiiiii", Toast.LENGTH_SHORT).show();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Dismiss the progress dialog
pdialog.hide();
pdialog.dismiss();
}
}
</code></pre>
<p>Now the problem in the adapter class that is it give me error at super() method
Ticket_adapter.java</p>
<pre><code> public class Ticket_adapter extends ArrayAdapter<String> {
UserLogedIn.viewticket context;
String[] id;
String[] prob;
String[] desc;
public Ticket_adapter(UserLogedIn.viewticket context, String[] id,String[] prob,String[] desc) {
super(context, R.id.list_item,id);//error cannot resolve method super
this.context=context;
this.id=id;
this.prob=prob;
this.desc=desc;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.my_list, null, true);
TextView idtxt=(TextView)convertView.findViewById(R.id.uid);
TextView probtxt=(TextView)convertView.findViewById(R.id.prob);
TextView desctxt=(TextView)convertView.findViewById(R.id.ticket);
idtxt.setText(id[position]);
probtxt.setText(prob[position]);
desctxt.setText(desc[position]);
return convertView;
}
}
</code></pre>
<p>Error:</p>
<blockquote>
<p>Error:(21, 9) error: no suitable constructor found for
ArrayAdapter(UserLogedIn.viewticket,int,String[]) constructor
ArrayAdapter.ArrayAdapter(Context,int,int) is not applicable (argument
mismatch; UserLogedIn.viewticket cannot be converted to Context)
constructor ArrayAdapter.ArrayAdapter(Context,int,String[]) is not
applicable (argument mismatch; UserLogedIn.viewticket cannot be
converted to Context) constructor
ArrayAdapter.ArrayAdapter(Context,int,List) is not applicable
(argument mismatch; UserLogedIn.viewticket cannot be converted to
Context)</p>
</blockquote>
| 3 | 2,297 |
Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
|
<p>I'm trying to create a sign up form with an input for a users address. The address input uses the google autocomplete address api.</p>
<p>I'd like to be able to keep it as a <code>Formik</code> field, so I can use <code>Yup</code> validation on it.</p>
<p>The address input component looks like</p>
<pre><code>// Google.jsx
import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
/* global google */
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.autocompleteInput = React.createRef();
this.autocomplete = null;
this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
}
componentDidMount() {
this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
{"types": ["address"]});
this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
}
handlePlaceChanged(){
const place = this.autocomplete.getPlace();
console.log(place);
}
render() {
return (
<Field ref={this.autocompleteInput} id="autocomplete" type="text" name="address" placeholder="" />
);
}
}
export default SearchBar;
</code></pre>
<p>And my <code>Form</code> component looks like:</p>
<pre><code>import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import SearchBar from "./Google";
const LoginSchema = Yup.object().shape({
fName: Yup.string().required("Please enter your first name"),
address: Yup.string().required("invalid address"),
});
class Basic extends React.Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col-lg-12">
<Formik
initialValues={{
fName: "",
postal: "",
}}
validationSchema={LoginSchema}
onSubmit={(values) => {
console.log(values);
console.log("form submitted");
}}
>
{({ touched, errors, isSubmitting, values }) =>
!isSubmitting ? (
<div>
<div className="row mb-5">
<div className="col-lg-12 text-center">
<h1 className="mt-5">LoKnow Form</h1>
</div>
</div>
<Form>
<div className="form-group">
<label htmlFor="fName">First Name</label>
<Field
type="text"
name="fName"
className={`mt-2 form-control
${touched.fName && errors.fName ? "is-invalid" : ""}`}
/>
<ErrorMessage
component="div"
name="fName"
className="invalid-feedback"
/>
</div>
<div className="form-group">
<label htmlFor="address">Address</label>
<Field name="address" component={SearchBar} placeholder="" />
<ErrorMessage
component="div"
name="address"
className="invalid-feedback"
/>
</div>
<button
type="submit"
className="btn btn-primary btn-block mt-4"
>
Submit
</button>
</Form>
</div>
) : (
<div>
<h1 className="p-3 mt-5">Form Submitted</h1>
<div className="alert alert-success mt-3">
Thank for your connecting with us.
</div>
</div>
)
}
</Formik>
</div>
</div>
</div>
);
}
}
export default Basic;
</code></pre>
<p>This returns an error of "Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?".</p>
<p>Which is coming from my address input component at:</p>
<pre><code><Field ref={this.autocompleteInput} id="autocomplete" type="text" name="address" placeholder="" />
</code></pre>
<p>Everything else is working, I just need to get past this last hurdle and I'll be good from here.</p>
<p>I will begin looking into the docs, but I'm unfortunately in a rush to get this done so I figured I'd try my luck here!</p>
<p>Any help is greatly appreciated! Thank you!</p>
| 3 | 2,984 |
How to generate object ids when $unwinding with aggregate in mongodb
|
<p>I'm having the following query</p>
<pre><code>db.getCollection('matches').aggregate([{
"$lookup": {
"from": "player",
"localField": "players.account_id",
"foreignField": "account_id",
"as": "players2"
}
}, {
"$addFields": {
"players": {
"$map": {
"input": "$players",
"in": {
"$mergeObjects": [
"$$this", {
"$arrayElemAt": [
"$players2", {
"$indexOfArray": [
"$players.account_id",
"$$this.account_id"
]
}
]
}
]
}
}
}
}
}, {
"$set": {
"players.match_id": "$match_id",
"players.radiant_win": "$radiant_win"
}
}, {
"$unwind": "$players"
}, {
"$replaceRoot": {
"newRoot": "$players"
}
}, {
"$project": {
"_id": 1,
"match_id": 1,
"account_id": 1,
"hero_id": 1,
"radiant_win": 1
}
}
])
</code></pre>
<p>which is supposed to match an inner array with another collection, merge the objects in the arrays by the matching and then unwrap ($unwind) the array into a new collection.</p>
<p>Unfortunately, I'm getting duplicate Object ids which is sort of a problem for when I want to export this collection.</p>
<p>How can I ensure unique Object_Ids for the aggregation?</p>
<p>Thanks in advance!</p>
| 3 | 1,062 |
how to calculate total based on check box checked.?
|
<p>I'm trying to calculate checked total amount based on checkbox select, if checkbox select then total value should add. i have added screenshot below also in that i had explained clearly please go through that. in my main project what happen is 'checked total' showing in every child table if i click in other table, all table's checked total will change, but u want to show individual table check total.</p>
<p>how can do this, i have uploaded code below</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module('MyApp', [])
app.controller('MyController', function($scope) {
$scope.Customers = [{
CustomerId: 1,
Name: "Prashant Olekar",
Country: "United States",
Orders: [{
OrderId: 10248,
Freight: 32.38,
amount: 10000,
ShipCountry: 'France'
},
{
OrderId: 10249,
Freight: 12.43,
amount: 10000,
ShipCountry: 'Japan'
},
{
OrderId: 10250,
Freight: 66.35,
amount: 10000,
ShipCountry: 'Russia'
}
]
},
{
CustomerId: 2,
Name: "Hemant K",
Country: "India",
Orders: [{
OrderId: 10266,
Freight: 77.0,
amount: 10000,
ShipCountry: 'Argentina'
},
{
OrderId: 10267,
Freight: 101.12,
amount: 10000,
ShipCountry: 'Australia'
},
{
OrderId: 10268,
Freight: 11.61,
amount: 10000,
ShipCountry: 'Germany'
}
]
},
{
CustomerId: 3,
Name: "Richard",
Country: "France",
Orders: [{
OrderId: 10250,
Freight: 65.83,
amount: 10000,
ShipCountry: 'Brazil'
}]
},
{
CustomerId: 4,
Name: "Robert Schidner",
Country: "Russia",
Orders: [{
OrderId: 10233,
Freight: 89.11,
amount: 10000,
ShipCountry: 'Belgium',
},
{
OrderId: 10234,
Freight: 51.30,
amount: 10000,
ShipCountry: 'Canada'
},
{
OrderId: 10235,
Freight: 46.11,
amount: 10000,
ShipCountry: 'Austria'
}
]
}
];
$scope.innertotalvalue = function (itemOrder) {
if (itemOrder != undefined) {
var innertotalvalue = 0;
for (j = 0; j < itemOrder.Orders.length; j++) {
if (itemOrder.Orders[j].amount != 0) {
innertotalvalue = innertotalvalue + itemOrder.Orders[j].amount;
}
}
}
return innertotalvalue;
}
$scope.chkselect_onchange = function(c, item) {
var totalvalue = 0;
var ordercount = 0;
var customercount = 0;
angular.forEach(c, function(cust) {
angular.forEach(cust.Orders, function(order) {
if (cust.select == true) {
if (order.amount != 0) {
order.select = true;
} else {
order.select = false;
}
} else {
order.select = false;
}
})
})
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div ng-app="MyApp" ng-controller="MyController">
<div class="container" style="margin-top:40px;">
<div class="row">
<div class="col-md-12">
<table class="table table-condensed table-bordered table-hover">
<thead>
<tr>
<td></td>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
<th>Orders</th>
</tr>
</thead>
<tbody ng-repeat="c in Customers">
<tr>
<td>
<input id="mainCheck" type="checkbox" ng-change="chkselect_onchange(Customers,c)" ng-model="c.select" /></td>
<td>{{c.CustomerId}}</td>
<td>{{c.Name}}</td>
<td>{{c.Country}}</td>
<td>
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th></th>
<th>Order Id</th>
<th>Freight</th>
<th>ShipCountry</th>
<th>Amount</th>
</tr>
</thead>
<tbody ng-repeat="o in c.Orders">
<tr>
<td>
<input id="subCheck" type="checkbox" ng-change="chklotselect_onchange(Customers)" ng-model="o.select" /></td>
<td>{{o.OrderId}}</td>
<td>{{o.Freight}}</td>
<td>{{o.ShipCountry}}</td>
<td>{{o.amount}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">Checked Total:______</td>
<td></td>
<td colspan="2"><span class="pull-right">Total:{{innertotalvalue(c)}}</span> </td>
</tr>
</tfoot>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| 3 | 3,810 |
Inconsistent Imports in React (create-react-app)
|
<p>returning to React for the first time in a while and having some strange issues I'm having trouble resolving. It seems like my imports are behaving inconsistently and I'm not sure why that might be. Here's the file in question:</p>
<pre><code>import React from 'react';
import axios from 'axios';
import {VanillaPuddingApi} from '../components/constants';
class Clients extends React.Component {
constructor(props){
super(props)
this.state={
clients: []
}
}
componentDidMount(){
debugger;
alert(VanillaPuddingApi)
axios
.get(`${VanillaPuddingApi}/clients`)
.then(({data}) => {
debugger;
})
.catch((errors)=>{
console.log(errors)
})
}
render() {
return (
<div>
{VanillaPuddingApi}
</div>
);
}
}
export default Clients;
</code></pre>
<p>This file is rendered properly on the page by the <code>App.js</code> file from the default create-react-app directory. Additionally, the value of <code>VanillaPuddingApi</code> is properly rendered on the DOM. The first debugger in the <code>componentDidMount()</code> call is problematic- if I check the value of <code>VanillaPuddingApi</code> in the console on that line, I get the following error message:</p>
<pre><code>`Uncaught ReferenceError: VanillaPuddingApi is not defined
at eval (eval at componentDidMount (Clients.js:15), <anonymous>:1:1)
at Clients.componentDidMount (Clients.js:15)
at ReactCompositeComponent.js:264
at measureLifeCyclePerf (ReactCompositeComponent.js:75)
at ReactCompositeComponent.js:263
at CallbackQueue.notifyAll (CallbackQueue.js:76)
at ReactReconcileTransaction.close (ReactReconcileTransaction.js:80)
at ReactReconcileTransaction.closeAll (Transaction.js:209)
at ReactReconcileTransaction.perform (Transaction.js:156)
at batchedMountComponentIntoNode (ReactMount.js:126)
at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:143)
at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
at Object.batchedUpdates (ReactUpdates.js:97)
at Object._renderNewRootComponent (ReactMount.js:319)
at Object._renderSubtreeIntoContainer (ReactMount.js:401)
at Object.render (ReactMount.js:422)
at Object../src/index.js (index.js:7)
at __webpack_require__ (bootstrap d489f093a1a431f7a956:669)
at fn (bootstrap d489f093a1a431f7a956:87)
at Object.0 (test.js:11)
at __webpack_require__ (bootstrap d489f093a1a431f7a956:669)
at bootstrap d489f093a1a431f7a956:715
at bundle.js:719`
</code></pre>
<p>Yet, on the very next line, this value is alerted out as expected. The real issue here is that Axios isn't working. When trying to run the <code>axios.get</code> line manually in the debugger, I get the same error as above. I did some digging and found people with similar issues who had issues with their webpack.config.js files, but mine looks unlike theirs did and this doesn't seem to explain my local importing issue.</p>
<pre><code>//webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.pug$/,
use: [
"pug-loader?self",
]
},
{
test: /\.css$/,
use: [
"style-loader",
"css-loader"
],
}
]
}
};
</code></pre>
<p>and also my package.json file:</p>
<pre><code>//package.json
{
"name": "vanilla-pudding-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.16.2",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"react-scripts": "1.0.13"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
</code></pre>
<p>and finally </p>
<pre><code>// components.constants
export const VanillaPuddingApi = "http://localhost:5000/"
</code></pre>
<p>Any help much appreciated, thank you.</p>
| 3 | 1,508 |
Android Custom XML layout for SQLite
|
<p>So I have been working on a project app that reads from a database and prints the contents of the DB into a list view. I now want to print more then just one column, I want to add two buttons and an edittext to the row that is being printed. I have created the new xml file that I want to use but when i try to set the new layout to be this xml file it doesnt work. Can anyone explain or show me how to fix my problem?</p>
<p>This is the XML layout I want to use for each row
</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="@+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:paddingBottom="5dp"
android:hint="@string/hint"/>
<Button
android:id="@+id/plusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/plusButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:id="@+id/edit1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/hint"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/minusButton"
android:layout_toStartOf="@+id/minusButton"
android:layout_marginRight="30dp" />
<Button
android:id="@+id/minusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/minusButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</code></pre>
<p>And this is the class where I am displaying the contents of the SQLite database, the error occurs on line 100 when i try to change the android.R.layout to the row.xml file</p>
<pre><code>package com.example.rory.dbtest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.pinchtapzoom.R;
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, addassignment.class);
startActivity(i);
}
});
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
db.open();
ArrayList<String> data_list=new ArrayList<String>();
ListView lv=(ListView)findViewById(R.id.listView1);
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do {
data_list.add(c.getString(2));
//data_list.add(c.getString(1));
//DisplayRecord(c);
} while (c.moveToNext());
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.row, data_list);
lv.setAdapter(aa);
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
@Override
public int getCount() {
return 0;
}
@Override
public Object getItem(int arg0) {
return null;
}
@Override
public long getItemId(int arg0) {
return 0;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
public void DisplayRecord(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"Item: " + c.getString(1) + "\n" +
"Litres: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}
}
</code></pre>
<p>My new custom adapter class
package com.example.rory.dbtest;</p>
<pre><code>import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.pinchtapzoom.R;
/**
* Created by Rory on 07/11/2014.
*/
public class MyCustomAdapter extends CursorAdapter {
DBAdapter db = new DBAdapter(this);
private LayoutInflater cursorInflater;
public MyCustomAdapter(Context context, Cursor c) {
super(context, c);
cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return cursorInflater.inflate(R.layout.row, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textViewTitle = (TextView) view.findViewById(R.id.row);
String title = cursor.getString( cursor.getColumnIndex( DATABASE_TABLE.KEY_ITEM ) )
textViewTitle.setText(title);
}
}
</code></pre>
| 3 | 2,714 |
ContextMenu in a ListView/GridView
|
<p>Inside a ListView, I have a GridView and am trying to set things up so that when the user right clicks a 'row' in the ListView, I'm able to access the original data object.
I think its the gridview part of the ListView that is making this a bit more difficult.</p>
<p>I've created a sample that demonstrates where I'm having difficulties. When the user right clicks the row eg Person1, I'd like to able to access the PersonClass data object in the MenuItem_Click handler. I've tried playing with PlacementTarget but all I get is null objects or objects of type MenuItem.</p>
<pre><code><Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ContextMenu Name="cm" x:Key="TestContextMenu">
<MenuItem Header="Context1" Click="MenuItem_Click"/>
<MenuItem Header="Context2"/>
<MenuItem Header="Context3"/>
</ContextMenu>
</Window.Resources>
<Grid>
<ListView Margin="20" Name="TestListView" SelectionMode="Multiple">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="ContextMenu" Value="{StaticResource TestContextMenu}" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="FirstName" Width="200" DisplayMemberBinding="{Binding Path=FirstName}"/>
<GridViewColumn Header="Surname" Width="200" DisplayMemberBinding="{Binding Path=Surname}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
</code></pre>
<p>Code:</p>
<pre><code>Class MainWindow
Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim Person1 As New PersonClass("John", "Fletcher")
Dim Person2 As New PersonClass("Bob", "Smith")
Dim ListOfPersons As New List(Of PersonClass)
ListOfPersons.Add(Person1)
ListOfPersons.Add(Person2)
TestListView.ItemsSource = ListOfPersons
End Sub
Private Sub MenuItem_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
MsgBox(e.OriginalSource.ToString)
MsgBox(sender.ToString)
MsgBox(e.Source.ToString)
End Sub
End Class
Public Class PersonClass
Private _firstName As String
Private _surname As String
Public Property FirstName() As String
Get
Return _firstName
End Get
Set(ByVal Value As String)
_firstName = Value
End Set
End Property
Public Property Surname() As String
Get
Return _surname
End Get
Set(ByVal Value As String)
_surname = Value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(FirstName As String, Surname As String)
Me.FirstName = FirstName
Me.Surname = Surname
End Sub
End Class
</code></pre>
| 3 | 1,423 |
PEM encoded certificate error when trying to import new Composer card
|
<p>I am having some problems setting my network up in Composer. It is a single organisation and i have been following and adapting the multi-org tutorial <a href="http://Multi%20org%20tutorial" rel="nofollow noreferrer">https://hyperledger.github.io/composer/v0.19/tutorials/deploy-to-fabric-multi-org</a> to try and get TLS working.</p>
<p>When i try and import the card i get the following error:</p>
<p>Error: Failed to create client from connection profile. Error: PEM encoded certificate is required.
Command failed</p>
<p>I have checked the TLS certs in my connection.json file:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
"name": "my-network",
"x-type": "hlfv1",
"version": "1.0.0",
"client": {
"organization": "Org1",
"connection": {
"timeout": {
"peer": {
"endorser": "300",
"eventHub": "300",
"eventReg": "300"
},
"orderer": "300"
}
}
},
"channels": {
"mychannel": {
"orderers": [
"orderer.my-network"
],
"peers": {
"peer0.org1.my-network": {
"endorsingPeer": true,
"chaincodeQuery": true,
"eventSource": true
},
"peer1.org1.my-network": {
"endorsingPeer": true,
"chaincodeQuery": true,
"eventSource": true
},
"peer2.org1.my-network": {
"endorsingPeer": true,
"chaincodeQuery": true,
"eventSource": true
}
}
}
},
"organizations": {
"Org1": {
"mspid": "Org1MSP",
"peers": [
"peer0.org1.my-network",
"peer1.org1.my-network",
"peer2.org1.my-network"
],
"certificateAuthorities": [
"ca.org1.my-network"
]
}
},
"orderers": {
"orderer.my-network": {
"url": "grpcs://localhost:7050",
"grpcOptions": {
"ssl-target-name-override": "orderer.my-network"
},
"tlsCACerts": {
"pem": "-----BEGIN CERTIFICATE-----\nMIICNTCCAdugAwIBAgIQKU7mM3knkhRfWjNtvaGaFDAKBggqhkjOPQQDAjBsMQsw\nCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy\nYW5jaXNjbzEUMBIGA1UEChMLbG9nLW5ldHdvcmsxGjAYBgNVBAMTEXRsc2NhLmxv\nZy1uZXR3b3JrMB4XDTE4MTIwMjE3NTAwNloXDTI4MTEyOTE3NTAwNlowbDELMAkG\nA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFu\nY2lzY28xFDASBgNVBAoTC2xvZy1uZXR3b3JrMRowGAYDVQQDExF0bHNjYS5sb2ct\nbmV0d29yazBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABMtii2eOX2OjBtn9a0sT\nQBItTcmtxjmb2Rh4zf0140rZz0NipSeUpNjAxO2KH8CkYvqcByMJ6qz8gmQ9McAC\n7x2jXzBdMA4GA1UdDwEB/wQEAwIBpjAPBgNVHSUECDAGBgRVHSUAMA8GA1UdEwEB\n/wQFMAMBAf8wKQYDVR0OBCIEIKPPDTwOmt+IBPVylKfQ3ceqOrSiJBHclABKn5v2\n4Y6MMAoGCCqGSM49BAMCA0gAMEUCIQC5mQ5fJsj20JdX2F5dWpR+YQprbj+dIcST\noCM1L8lHYAIgI0Oq5VO6ucOMMw5e9CDsiCYU40sMAlgAJEYX/5AaZ1M=\n-----END CERTIFICATE-----\n"
}
}
},
"peers": {
"peer0.org1.my-network": {
"url": "grpcs://localhost:7051",
"grpcOptions": {
"ssl-target-name-override": "peer0.org1.my-network"
},
"tlsCACerts": {
"pem": "-----BEGIN CERTIFICATE-----\nMIICSDCCAe+gAwIBAgIQUzZZpkSRmpv6cj8Bta1BezAKBggqhkjOPQQDAjB2MQsw\nCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy\nYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5sb2ctbmV0d29yazEfMB0GA1UEAxMWdGxz\nY2Eub3JnMS5sb2ctbmV0d29yazAeFw0xODEyMDIxNzUwMDZaFw0yODExMjkxNzUw\nMDZaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH\nEw1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmxvZy1uZXR3b3JrMR8wHQYD\nVQQDExZ0bHNjYS5vcmcxLmxvZy1uZXR3b3JrMFkwEwYHKoZIzj0CAQYIKoZIzj0D\nAQcDQgAEIdyjFaWd9I3kU+Kdh9z+vJttthzyFLPgcoXBWAT18zX7r7fRLxcBMF9d\nQazzpz2A55YG5rCm5NAeV3ugkHy5AaNfMF0wDgYDVR0PAQH/BAQDAgGmMA8GA1Ud\nJQQIMAYGBFUdJQAwDwYDVR0TAQH/BAUwAwEB/zApBgNVHQ4EIgQgYtzVJNNdNjo+\n4FVhytdhGQr1fT6PbXfV0mKt3AU2g48wCgYIKoZIzj0EAwIDRwAwRAIgH7ADGx8D\nZsyTbeZ12S+1tMRmGo1tx6xpPzUGYx7hcGcCICDps+r+lvHeTaKVpENDPJaj5hcd\nOXkvHWYb2/sMguGc\n-----END CERTIFICATE-----\n"
}
},
"peer1.org1.my-network": {
"url": "grpcs://localhost:8051",
"grpcOptions": {
"ssl-target-name-override": "peer1.org1.my-network"
},
"tlsCACerts": {
"pem": "-----BEGIN CERTIFICATE-----\nMIICSDCCAe+gAwIBAgIQUzZZpkSRmpv6cj8Bta1BezAKBggqhkjOPQQDAjB2MQsw\nCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy\nYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5sb2ctbmV0d29yazEfMB0GA1UEAxMWdGxz\nY2Eub3JnMS5sb2ctbmV0d29yazAeFw0xODEyMDIxNzUwMDZaFw0yODExMjkxNzUw\nMDZaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH\nEw1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmxvZy1uZXR3b3JrMR8wHQYD\nVQQDExZ0bHNjYS5vcmcxLmxvZy1uZXR3b3JrMFkwEwYHKoZIzj0CAQYIKoZIzj0D\nAQcDQgAEIdyjFaWd9I3kU+Kdh9z+vJttthzyFLPgcoXBWAT18zX7r7fRLxcBMF9d\nQazzpz2A55YG5rCm5NAeV3ugkHy5AaNfMF0wDgYDVR0PAQH/BAQDAgGmMA8GA1Ud\nJQQIMAYGBFUdJQAwDwYDVR0TAQH/BAUwAwEB/zApBgNVHQ4EIgQgYtzVJNNdNjo+\n4FVhytdhGQr1fT6PbXfV0mKt3AU2g48wCgYIKoZIzj0EAwIDRwAwRAIgH7ADGx8D\nZsyTbeZ12S+1tMRmGo1tx6xpPzUGYx7hcGcCICDps+r+lvHeTaKVpENDPJaj5hcd\nOXkvHWYb2/sMguGc\n-----END CERTIFICATE-----\n"
}
},
"peer2.org1.my-network": {
"url": "grpcs://localhost:9051",
"gprcOptions": {
"ssl-target-name-override": "peer2.org1.my-network"
},
"tlsCerts": {
"pem": "-----BEGIN CERTIFICATE-----\nMIICSDCCAe+gAwIBAgIQUzZZpkSRmpv6cj8Bta1BezAKBggqhkjOPQQDAjB2MQsw\nCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy\nYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5sb2ctbmV0d29yazEfMB0GA1UEAxMWdGxz\nY2Eub3JnMS5sb2ctbmV0d29yazAeFw0xODEyMDIxNzUwMDZaFw0yODExMjkxNzUw\nMDZaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH\nEw1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmxvZy1uZXR3b3JrMR8wHQYD\nVQQDExZ0bHNjYS5vcmcxLmxvZy1uZXR3b3JrMFkwEwYHKoZIzj0CAQYIKoZIzj0D\nAQcDQgAEIdyjFaWd9I3kU+Kdh9z+vJttthzyFLPgcoXBWAT18zX7r7fRLxcBMF9d\nQazzpz2A55YG5rCm5NAeV3ugkHy5AaNfMF0wDgYDVR0PAQH/BAQDAgGmMA8GA1Ud\nJQQIMAYGBFUdJQAwDwYDVR0TAQH/BAUwAwEB/zApBgNVHQ4EIgQgYtzVJNNdNjo+\n4FVhytdhGQr1fT6PbXfV0mKt3AU2g48wCgYIKoZIzj0EAwIDRwAwRAIgH7ADGx8D\nZsyTbeZ12S+1tMRmGo1tx6xpPzUGYx7hcGcCICDps+r+lvHeTaKVpENDPJaj5hcd\nOXkvHWYb2/sMguGc\n-----END CERTIFICATE-----\n"
}
}
},
"certificateAuthorities": {
"ca.org1.my-network": {
"url": "http://localhost:7054",
"caName": "ca_peerOrg1",
"httpOptions": {
"verify": false
}
}
}
}</code></pre>
</div>
</div>
</p>
<p>I have not included couchdb yet, the docker-compose-cli.yaml is below:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code># Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
version: '2'
networks:
byfn:
services:
ca.org1.my-network:
container_name: ca_peerOrg1
image: hyperledger/fabric-ca
environment:
- FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
- FABRIC_CA_SERVER_CA_NAME=ca-org1
- FABRIC_CA_SERVER_TLS_ENABLED=true
- FABRIC_CA_SERVER_TLS_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org1.my-network-cert.pem
- FABRIC_CA_SERVER_TLS_KEYFILE=/etc/hyperledger/fabric-ca-server-config/cc074f628fe7cb97e8147a8824fa564ddced245c324be7fb7660ee6fccf9cea2_sk
ports:
- "7054:7054"
command: sh -c 'fabric-ca-server start --ca.certfile /etc/hyperledger/fabric-ca-server-config/ca.org1.my-network-cert.pem --ca.keyfile /etc/hyperledger/fabric-ca-server-config/cc074f628fe7cb97e8147a8824fa564ddced245c324be7fb7660ee6fccf9cea2_sk -b admin:adminpw -d'
volumes:
- ./crypto-config/peerOrganizations/org1.my-network/ca/:/etc/hyperledger/fabric-ca-server-config
networks:
- byfn
# Should be either 3, 5 or 7 zookeepers to avoid split-brain scenarios, and larger than 1 to avoid a single point of failure
zookeeper0:
container_name: zookeeper0
image: hyperledger/fabric-zookeeper
environment:
- ZOO_MY_ID=1
- ZOO_SERVERS=server.1=zookeeper0:2888:3888 server.2=zookeeper1:2888:3888 server.3=zookeeper2:2888:3888
ports:
- 2181
- 2888
- 3888
networks:
- byfn
zookeeper1:
container_name: zookeeper1
image: hyperledger/fabric-zookeeper
environment:
- ZOO_MY_ID=2
- ZOO_SERVERS=server.1=zookeeper0:2888:3888 server.2=zookeeper1:2888:3888 server.3=zookeeper2:2888:3888
ports:
- 2181
- 2888
- 3888
networks:
- byfn
zookeeper2:
container_name: zookeeper2
image: hyperledger/fabric-zookeeper
environment:
- ZOO_MY_ID=3
- ZOO_SERVERS=server.1=zookeeper0:2888:3888 server.2=zookeeper1:2888:3888 server.3=zookeeper2:2888:3888
command: /bin/bash -c 'sleep 6000000000000000000'
ports:
- 2181
- 2888
- 3888
networks:
- byfn
# Should be at least 4 nodes in the kafka cluster for crash tollerance
kafka0:
image: hyperledger/fabric-kafka
container_name: kafka0
environment:
- KAFKA_LOG_RETENTION_MS=-1
- KAFKA_MESSAGE_MAX_BYTES=103809024
- KAFKA_REPLICA_FETCH_MAX_BYTES=103809024
- KAFKA_BROKER_ID=0
- KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
- KAFKA_UNCLEAN_LEADER_ELECTION_ENABLE=false
- KAFKA_DEFAULT_REPLICATION_FACTOR=3
- KAFKA_MIN_INSYNC_REPLICAS=2
- KAFKA_ZOOKEEPER_CONNECT=zookeeper0:2181,zookeeper1:2181,zookeeper2:2181
ports:
- 9092
depends_on:
- zookeeper0
- zookeeper1
- zookeeper2
links:
- zookeeper0:zookeeper0
- zookeeper1:zookeeper1
- zookeeper2:zookeeper2
networks:
- byfn
kafka1:
image: hyperledger/fabric-kafka
container_name: kafka1
environment:
- KAFKA_LOG_RETENTION_MS=-1
- KAFKA_MESSAGE_MAX_BYTES=103809024
- KAFKA_REPLICA_FETCH_MAX_BYTES=103809024
- KAFKA_BROKER_ID=1
- KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
- KAFKA_UNCLEAN_LEADER_ELECTION_ENABLE=false
- KAFKA_DEFAULT_REPLICATION_FACTOR=3
- KAFKA_MIN_INSYNC_REPLICAS=2
- KAFKA_ZOOKEEPER_CONNECT=zookeeper0:2181,zookeeper1:2181,zookeeper2:2181
ports:
- 9092
depends_on:
- zookeeper0
- zookeeper1
- zookeeper2
links:
- zookeeper0:zookeeper0
- zookeeper1:zookeeper1
- zookeeper2:zookeeper2
networks:
- byfn
kafka2:
image: hyperledger/fabric-kafka
container_name: kafka2
environment:
- KAFKA_LOG_RETENTION_MS=-1
- KAFKA_MESSAGE_MAX_BYTES=103809024
- KAFKA_REPLICA_FETCH_MAX_BYTES=103809024
- KAFKA_BROKER_ID=2
- KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
- KAFKA_UNCLEAN_LEADER_ELECTION_ENABLE=false
- KAFKA_DEFAULT_REPLICATION_FACTOR=3
- KAFKA_MIN_INSYNC_REPLICAS=2
- KAFKA_ZOOKEEPER_CONNECT=zookeeper0:2181,zookeeper1:2181,zookeeper2:2181
ports:
- 9092
depends_on:
- zookeeper0
- zookeeper1
- zookeeper2
links:
- zookeeper0:zookeeper0
- zookeeper1:zookeeper1
- zookeeper2:zookeeper2
networks:
- byfn
kafka3:
image: hyperledger/fabric-kafka
container_name: kafka3
environment:
- KAFKA_LOG_RETENTION_MS=-1
- KAFKA_MESSAGE_MAX_BYTES=103809024
- KAFKA_REPLICA_FETCH_MAX_BYTES=103809024
- KAFKA_BROKER_ID=3
- KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
- KAFKA_UNCLEAN_LEADER_ELECTION_ENABLE=false
- KAFKA_DEFAULT_REPLICATION_FACTOR=3
- KAFKA_MIN_INSYNC_REPLICAS=2
- KAFKA_ZOOKEEPER_CONNECT=zookeeper0:2181,zookeeper1:2181,zookeeper2:2181
ports:
- 9092
depends_on:
- zookeeper0
- zookeeper1
- zookeeper2
links:
- zookeeper0:zookeeper0
- zookeeper1:zookeeper1
- zookeeper2:zookeeper2
networks:
- byfn
orderer.my-network:
extends:
file: base/docker-compose-base.yaml
service: orderer.my-network
container_name: orderer.my-network
depends_on:
- kafka0
- kafka1
- kafka2
- kafka3
links:
- kafka0:kafka0
- kafka1:kafka1
- kafka2:kafka2
- kafka3:kafka3
networks:
- byfn
peer0.org1.my-network:
container_name: peer0.org1.my-network
extends:
file: base/docker-compose-base.yaml
service: peer0.org1.my-network
networks:
- byfn
peer1.org1.my-network:
container_name: peer1.org1.my-network
extends:
file: base/docker-compose-base.yaml
service: peer1.org1.my-network
networks:
- byfn
peer2.org1.my-network:
container_name: peer2.org1.my-network
extends:
file: base/docker-compose-base.yaml
service: peer2.org1.my-network
networks:
- byfn
cli:
container_name: cli
image: hyperledger/fabric-tools
tty: true
environment:
- GOPATH=/opt/gopath
- CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
- CORE_LOGGING_LEVEL=DEBUG
- CORE_PEER_ID=cli
- CORE_PEER_ADDRESS=peer0.org1.my-network:7051
- CORE_PEER_LOCALMSPID=Org1MSP
- CORE_PEER_TLS_ENABLED=true
- CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.my-network/peers/peer0.org1.my-network/tls/server.crt
- CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.my-network/peers/peer0.org1.my-network/tls/server.key
- CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.my-network/peers/peer0.org1.my-network/tls/ca.crt
- CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.my-network/users/Admin@org1.my-network/msp
working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
command: /bin/bash
# command: /bin/bash -c './scripts/script.sh ${CHANNEL_NAME} ${DELAY} ${LANG}; sleep $TIMEOUT'
volumes:
- /var/run/:/host/var/run/
- ./../chaincode/:/opt/gopath/src/github.com/chaincode
- ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
- ./scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/
- ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts
depends_on:
- orderer.my-network
- peer0.org1.my-network
- peer1.org1.my-network
- peer2.org1.my-network
networks:
- byfn</code></pre>
</div>
</div>
</p>
<p>I am not using the byfn.sh to start the network, but manually with:</p>
<p>docker-compose -f docker-compose-cli.yaml up -d</p>
<p>I have not loaded any sample chaincode. I have joined the orderer and three peers to the channel in the CLI.</p>
<p>Is there something i am missing with the certificate authority when starting the network?</p>
<p>Bit stuck at getting this going so any help would be very much appreciated.</p>
<p>Many thanks.</p>
| 3 | 9,456 |
Include pymssql in py2app
|
<p>I'm trying to package an app and include <code>pymssql</code> with it. </p>
<p>Here's my setup.py:</p>
<pre><code>"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['AppName.py']
DATA_FILES = ['pic1.jpg', 'pic2.jpeg']
OPTIONS = {'argv_emulation': True,
'packages': ['tkinter', '_mssql', 'pymssql']
}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
</code></pre>
<p>When I only include <code>_mssql</code> it gives this error:</p>
<pre><code>error: cannot copy tree '/path_to_venv/lib/python3.4/site-packages/_mssql.so': not a directory
</code></pre>
<p>When I try with <code>pymssql</code> (or both) it gives this error:</p>
<pre><code>Traceback (most recent call last):
File "setup.py", line 20, in <module>
setup_requires=['py2app'],
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/distutils/core.py", line 148, in setup
dist.run_commands()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/path_to_venv/lib/python3.4/site-packages/py2app/build_app.py", line 659, in run
self._run()
File "/path_to_venv/lib/python3.4/site-packages/py2app/build_app.py", line 865, in _run
self.run_normal()
File "/path_to_venv/lib/python3.4/site-packages/py2app/build_app.py", line 939, in run_normal
mf = self.get_modulefinder()
File "/path_to_venv/lib/python3.4/site-packages/py2app/build_app.py", line 814, in get_modulefinder
debug=debug,
File "/path_to_venv/lib/python3.4/site-packages/modulegraph/find_modules.py", line 341, in find_modules
find_needed_modules(mf, scripts, includes, packages)
File "/path_to_venv/lib/python3.4/site-packages/modulegraph/find_modules.py", line 266, in find_needed_modules
path = m.packagepath[0]
TypeError: 'NoneType' object is not subscriptable
</code></pre>
<p>Another note:</p>
<p>I can package the app fine without including either <code>pymssql</code> or <code>_mssql</code> in the setup file and when I try and run the app, here's the error I get in the OS Console:</p>
<pre><code>1/12/16 10:00:48.618 AM AppName[72301]: Traceback (most recent call last):
1/12/16 10:00:48.618 AM AppName[72301]: File "/path_to_app/dist/AppName.app/Contents/Resources/__boot__.py", line 351, in <module>
1/12/16 10:00:48.618 AM AppName[72301]: _run()
1/12/16 10:00:48.619 AM AppName[72301]: File "/path_to_app/dist/AppName.app/Contents/Resources/__boot__.py", line 336, in _run
1/12/16 10:00:48.619 AM AppName[72301]: exec(compile(source, path, 'exec'), globals(), globals())
1/12/16 10:00:48.619 AM AppName[72301]: File "/path_to_app/dist/AppName.app/Contents/Resources/AppName.py", line 9, in <module>
1/12/16 10:00:48.619 AM AppName[72301]: import pymssql
1/12/16 10:00:48.619 AM AppName[72301]: File "_mssql.pxd", line 10, in init pymssql (pymssql.c:10984)
1/12/16 10:00:48.619 AM AppName[72301]: ImportError: No module named '_mssql'
</code></pre>
| 3 | 1,358 |
Zurb Foundation top-bar not working on small screens
|
<p>I just started using foundations and frankly, its been a while since i built my last website. so please be pacient with me.</p>
<p>I deal with an issue with my menu (top-bar) now for over a day and can not find a clue what is going wrong.</p>
<p>The thing is, I really just need a basic menu, which is toggeling to the standard burger-menu on small screens, so far so good, it should work like demonstrated in the documentation right? But unfortunatly it does not and I cant figure out why.</p>
<p>I hope you can help me. I add my code without contents below. The file lies in a subdirectory, thats why all directory references are with ../ at the beginning.</p>
<p>Thanks a lot already!
Ina</p>
<pre><code><!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Inas | Ernährungs Coaching</title>
<link rel="stylesheet" href="../css/foundation.css" />
<link rel="stylesheet" href="../css/additionals.css" />
<script src="../js/vendor/modernizr.js"></script>
</head>
<body>
<div id="wrap">
<div id="header">
<div class="row">
<div class="large-12 columns clearfix">
<!-- a header -->
</div>
</div>
<br>
<div class="row">
<div class="small-12 columns">
<!-- Navigation -->
<div class="contain-to-grid sticky">
<nav class="top-bar data-topbar" >
<ul class="title-area" >
<li class="name">
<h1></h1>
</li>
<li class="toggle-topbar menu-icon"><a href="#"><span>Men&uuml;</span></a>
</li>
</ul>
<section class="top-bar-section">
<ul>
<li><a href="index.php">Start</a></li>
<li class="divider"><li>
<li><a href="index.php?page=angebot">Angebot</a></li>
<li class="divider"><li>
<li><a href="index.php?page=aktuelles">Aktuelles</a></li>
<li class="divider"><li>
<li><a href="index.php?page=mich">&Uuml;ber Mich</a></li>
<li class="divider"><li>
<li><a href="index.php?page=kontakt">Kontakt</a></li>
</ul>
</section>
</nav>
</div><!-- /navigation -->
</div>
</div>
</div>
<div id="main">
<!-- some content -->
</div>
<div id="footer">
<!-- a footer -->
</div>
</div>
<script src="../js/vendor/jquery.js"></script>
<script src="../js/foundation.js"></script>
<script src="../js/foundation/foundation.topbar.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>
</code></pre>
| 3 | 2,108 |
Is it possible to make an image move with the cursor when it gets near, and have collision?
|
<p>I am creating a maze game. I got provided with how I would make an image not able to enter a div with jQuery. I also have a code with the image following the cursor. In the second code, I made it so that the image would only go to the mouse if it was a certain distance away. With the collision, the code from the second code got messed up, and now the image teleports to the cursor, instead of how I want it to act. How can I fix this? I am flexible if you need to use pure js or jquery UI. I highly prefer jQuery.</p>
<h1>jQuery from first code:</h1>
<pre><code>function collisionCheck(ax,ay) {
var collide = false;
var aminY = ay;
var aminX = ax;
var amaxX = aminX + $('#image').width();
var amaxY = aminY + $('#image').height();
$('.maze').each(function(){
collide = false;
var bminY = $(this).offset().top - $(window).scrollTop();
var bminX = $(this).offset().left - $(window).scrollLeft();
var bmaxX = bminX + $(this).width();
var bmaxY = bminY + $(this).height();
if (amaxX < bminX) collide = true; // a is left of b
if (aminX > bmaxX) collide = true; // a is right of b
if (amaxY < bminY) collide = true; // a is above b
if (aminY > bmaxY) collide = true; // a is below b
if (!collide) {
return collide;
}
});
return collide;
}
$(document).ready(function(){
$(document).mousemove(function(e) {
startMove = true;
var cursorY = e.pageY;
var cursorX = e.pageX;
if (collisionCheck(cursorX, cursorY)) {
$('html').removeClass('showCursor');
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$("#drop").mouseenter(function(){
alert("Success");
});
});
</code></pre>
<h1>jQuery from the second code:</h1>
<pre><code>var startMove;
$(document).mousemove(function(e) {
var DIFF_SNAP = 10;
var DIFF_UNSNAP = 100;
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) {
startMove = true;
$('html').removeClass('showCursor');
} else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) {
startMove = false;
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
$("#drop").mouseenter(function(){
if(startMove)
alert("Success");
});
</code></pre>
<p>1st jsfiddle: <a href="https://jsfiddle.net/8pc3u7t9/1/" rel="nofollow">https://jsfiddle.net/8pc3u7t9/1/</a><br>
2nd jsfiddle: <a href="https://jsfiddle.net/3x7cgLdr/26/" rel="nofollow">https://jsfiddle.net/3x7cgLdr/26/</a></p>
| 3 | 1,489 |
HTML + Hiding element from table based on value from another column
|
<p>I am trying to hide a button in a table column based on another column value, there's a table column field call "Archive" and if that value is true, I want to hide a button from another column. The code below I have however only hides the button in the first row and ignore subsequent rows. Please kindly assist. Thanks.</p>
<pre><code><table class="table table-striped table-bordered">
<tr>
<td width="8%" class="table_pink" style="background-color:#ED4085">Name</td>
<td width="8%" class="table_pink" style="background-color:#ED4085">Email</td>
<td width="8%" class="table_pink" style="background-color:#ED4085">Country</td>
<td width="8%" class="table_pink" style="background-color:#ED4085">Time</td>
<td width="5%" class="table_pink" style="background-color:#ED4085">WrongAtQuestion</td>
<td width="5%" class="table_pink" style="background-color:#ED4085">Winner?</td>
<td width="5%" class="table_pink" style="background-color:#ED4085">CreatedDateTime</td>
<td width="5%" class="table_pink" style="background-color:#ED4085">Hidden</td>
<td width="20%" class="table_pink" style="background-color:#ED4085">Action</td>
</tr>
@foreach (var item in Model)
{
if (item.Archive)
{
<script type="text/javascript">
$('#hideButton').hide();
</script>
}
<tr>
<td>@item.Name</td>
<td>@item.Email</td>
<td>@item.Country</td>
<td>@item.Time</td>
<td>@item.WrongAtQuestion</td>
<td>@item.IsWinner</td>
<td>@item.CreatedDateTime</td>
<td>@item.Archive</td>
<td><a class="btn btn-primary" href="#" id="hideButton" onclick="deleteEntry('@item.Id', '@item.Name'); return false;"><i class="icon-white icon-trash"></i> Hide from Leaderboard</a></td>
</tr>
}
</table>
</code></pre>
| 3 | 1,123 |
What is a SMART WAY to deal with a lot of repeated If statements checks?
|
<p>In my attempt to create a searching tool for a database that I created in the context of my undergrad thesis, I am required to make a lot of checks on the values that the user has entered, and according to those values, generate and execute the appropriate <code>MySQL query</code>. An example follows:</p>
<p><code>HTML Code</code></p>
<pre><code>(part of the whole table)
<tr id="tablerow" class="">
<th id="selectth">
<select class="selection" name="Attributes" id="Attributes">
<!-- List of all the available attributes for the user to select for the searching queries -->
<option disabled>Options</option>
<option value="Name" id="p_Name">Name</option>
<option value="ID" id="p_Id">Patient ID</option>
<option value="Sex" id="p_Sex">Sex</option>
<option value="Email" id="p_Email">Patient Email</option>
<option value="Age" id="p_Age">Age ></option>
<option value="Agesmaller">Age < </option>
<option value="Race" id="p_Race">Race</option>
<option value="PhoneNumber" id="p_Phonenum">Phone Number</option>
<option value="Comorbidities" id="p_Comorbidities">Comorbidities</option>
<option value="EDSS" id="p_eddsscore">EDSS Score</option>
<option value="Pregnant" id="p_Pregnant">Is Pregnant</option>
<option value="Onsetlocalisation" id="p_Onsetlocalisation">Onset Localisation</option>
<option value="Smoker" id="p_Smoker">Is a Smoker</option>
<option value="onsetsymptoms" id="p_onsetsymptoms">Onset Symptoms</option>
<option value="MRIenhancing" id="p_MRIenhancing">MRI Enhancing Lesions</option>
<option value="MRInum" id="p_MRInum">MRI Lesion No.</option>
<option value="MRIonsetlocalisation" id="p_MRIonsetlocalisation">MRI Onset Localisation</option>
</select>
</th>
</code></pre>
<p>and as another part of that same table, I have a button that allows the user to create a second row of input in order to make a more specific search, with 2 attributes, either with AND or with an OR statement.
<code><button type="button" id="new_row_btn" onclick="addRow()" name="new_row">Add an extra row</button></code></p>
<p>I would like to keep this post sort in order to receive an answer, so I won't include the addRow() JavaScript function, <strong>but if it is necessary</strong> please comment it and I will edit this ASAP.</p>
<p>My question is the following, I have those 2 inputs, and I want to check if the user has entered anything on the second row of inputs (in the "advanced" one) and then based on the new value execute the appropriate query.</p>
<p>The PHP code as of now looks something like this:</p>
<p><code>PHP Code</code></p>
<pre><code>if($option == 'Name' && $newoption == 'Email' && !empty($newEmail)){
$sql = "SELECT patients.Patient_id,patients.Patient_name,patients.DOB,patients.Phonenum,patients.Email,MSR.Sex FROM patients,MSR WHERE patients.Patient_id = MSR.NDSnum AND Doctor_ID = $usersid AND patients.Email = '$newEmail' $and_or patients.Patient_name LIKE '%$entry%' ORDER BY Patient_id";
$result = $pdo->query($sql);
if ($result->rowCount() > 0) {
while ($row = $result->fetch()) { ?>
<table id="standard">
<tr>
<th>Patient ID</th>
<th>Name</th>
<th>Date of Birth</th>
<th>Phone Number</th>
<th>Email</th>
<th>Sex</th>
<th>Previous Visits</th>
</tr>
<tr>
<td><?php echo $row['Patient_id']; ?></td>
<td> <?php echo $row['Patient_name']; ?> </td>
<td><?php echo $row['DOB']; ?></td>
<td><?php echo $row['Phonenum']; ?></td>
<td><?php echo $row['Email']; ?></td>
<td><?php echo $row['Sex']; ?></td>
<td><?php echo "<a href='/application/previousvisit-bootstrap.php?id=" . $row['Patient_id'] . "'>Previous Visits</a>"; ?></td>
</tr>
</table>
<div class="line"></div>
<?php }
} else {
echo "No patient exists with this information. Name+Email";
}
} if ($option == 'Name' && $newoption == 'Age' && !empty($newAge)){
$sql = "SELECT * FROM patients WHERE timestampdiff(year,dob,curdate()) > '$entry' $and_or patients.Patient_name LIKE '%$entry%' AND Doctor_ID = $usersid ORDER BY Patient_id";
$result = $pdo->query($sql);
if ($result->rowCount() > 0) {
while ($row = $result->fetch()) { ?>
<table id="standard">
<tr>
<th>Patient Id</th>
<th>Patient Name</th>
<th>Date of Birth</th>
<th>Phone Number</th>
<th>Email</th>
<th>Previous Visits</th>
</tr>
<tr>
<td><?php echo $row['Patient_id']; ?></td>
<td> <?php echo $row['Patient_name']; ?> </td>
<td><?php echo $row['DOB'] ?></td>
<td><?php echo $row['Phonenum']; ?></td>
<td><?php echo $row['Email']; ?></td>
<td><?php echo "<a href='/application/previousvisit-bootstrap.php?id=" . $row['Patient_id'] . "'>Previous Visits</a>"; ?></td>
</tr>
</table>
<div class="line"></div>
<?php }
} else {
echo "No patient exists with this information. Name+Age";
}
</code></pre>
<p>The above if statement goes on for about 20 more times... each time checks one attribute in relation to another.. for example
<code>Name+newID</code> or <code>ID+newName</code> or <code>Email+newSex</code>
Obviously I know that Im not done and that there are hundreds of possible combinations with those attributes, but I was wondering if there is some way to avoid all this and make it kinda easier....</p>
<p><strong>Im sorry for the long question!</strong> Any notes on how to make this a better question are welcome.</p>
<p>Thank you in advanced for you time.</p>
| 3 | 4,378 |
facebook meta og:image not showing in post
|
<p>I have the following meta tags</p>
<pre><code><meta data-n-head="true" data-hid="og-title" property="og:title" content=" | Skryit"><meta data-n-head="true" data-hid="og-description" property="og:description" content="">
<meta data-n-head="true" data-hid="og-type" property="og:type" content="website">
<meta data-n-head="true" data-hid="og-url" property="og:url" content="https://www.skryit.com/vonawesome/posts/f5449c93-1666-4a80-adce-9648cfa75715">
<meta data-n-head="true" data-hid="og-image" property="og:image" content="https://api.skryit.com/media/f0759ad8-9d30-4e28-8d23-a4e3fc198114.png">
</code></pre>
<p>I am trying to get facebook's share to pull the correct meta image <code>og:image</code>, but it isn't.</p>
<p>I was debugging with <a href="https://developers.facebook.com/tools/debug/sharing/?q=https%3A%2F%2Fwww.skryit.com%2Fvonawesome%2Fposts%2Ff5449c93-1666-4a80-adce-9648cfa75715%2F" rel="nofollow noreferrer">facebook debugger</a></p>
<p>I get the following </p>
<pre><code>Provided og:image, https://api.skryit.com/media/f0759ad8-9d30-4e28-8d23-a4e3fc198114.png
could not be downloaded. This can happen due to several different reasons such as your server
using unsupported content-encoding. The crawler accepts deflate and gzip content encodings.
</code></pre>
<p>but it isn't true. Checking the network tab it is using gzip.</p>
<p>Then I started checking nginx.</p>
<p>This is my configuration (partial)</p>
<pre><code>server {
listen 443 ssl http2;
listen [::]:443 ssl http2 ipv6only=on;
ssl_certificate /etc/letsencrypt/live/domain/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/domain/privkey.pem;
ssl_protocols TLSv1.3;# Requires nginx >= 1.13.0 else use TLSv1.2
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/nginx/dhparam.pem; # openssl dhparam -out /etc/nginx/dhparam.pem 4096
ssl_ciphers EECDH+AESGCM:EDH+AESGCM;
ssl_ecdh_curve secp384r1; # Requires nginx >= 1.1.0
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off; # Requires nginx >= 1.5.9
ssl_stapling on; # Requires nginx >= 1.3.7
ssl_stapling_verify on; # Requires nginx => 1.3.7
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
gzip on;
gzip_types text/plain application/xml text/css application/javascript;
gzip_min_length 1000;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
alias /home/proj/staticfiles/;
}
location /media/ {
alias /home/proj/media/;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
proxy_ssl_server_name on;
}
}
</code></pre>
<p>I checked nginx logs and found this in <code>error.log</code></p>
<pre><code> 2019/12/11 23:35:32 [crit] 8037#8037: *232 SSL_do_handshake() failed (SSL: error:14209102:SSL routines:tls_early_post_process_client_hello:unsupported protocol) while SSL handshaking, client: 18.212.76.137, server: 0.0.0.0:443
2019/12/11 23:38:05 [crit] 9257#9257: *7 SSL_do_handshake() failed (SSL: error:14209102:SSL routines:tls_early_post_process_client_hello:unsupported protocol) while SSL handshaking, client: 173.252.83.9, server: 0.0.0.0:443
2019/12/11 23:38:06 [crit] 9257#9257: *8 SSL_do_handshake() failed (SSL: error:14209102:SSL routines:tls_early_post_process_client_hello:unsupported protocol) while SSL handshaking, client: 173.252.83.19, server: 0.0.0.0:443
2019/12/12 00:07:11 [crit] 9257#9257: *33 SSL_do_handshake() failed (SSL: error:14209102:SSL routines:tls_early_post_process_client_hello:unsupported protocol) while SSL handshaking, client: 18.212.76.137, server: 0.0.0.0:443
2019/12/12 00:07:54 [crit] 9257#9257: *34 SSL_do_handshake() failed (SSL: error:14209102:SSL routines:tls_early_post_process_client_hello:unsupported protocol) while SSL handshaking, client: 128.14.134.170, server: 0.0.0.0:443
2019/12/12 00:20:04 [crit] 9257#9257: *65 SSL_do_handshake() failed (SSL: error:14209102:SSL routines:tls_early_post_process_client_hello:unsupported protocol) while SSL handshaking, client: 184.105.139.69, server: 0.0.0.0:443
</code></pre>
<p>I have looked further for trying to resolve the above error. adding <code>proxy_ssl_server_name on</code> did nothing. I have looked at another solution but weren't really helpful in resolving the issue I had.</p>
| 3 | 1,917 |
Remove duplicate form select result
|
<h1>#edited</h1>
<p>Ok. I will delete all role permissions and add them again.</p>
<p>Is it possible to combine all 4 queries into one?</p>
<hr>
<p>I am creating a permission system.</p>
<p>Assumptions:</p>
<ul>
<li><p>Each user can have more than one role</p></li>
<li><p>Each role can have more than one permission</p></li>
<li><p>Permissions can also be assigned directly to the user (they have a higher priority than permissions for roles)</p></li>
</ul>
<p>The priority of permissions is:</p>
<ul>
<li><p>role permission</p></li>
<li><p>denial of role</p></li>
<li><p>user permission</p></li>
<li><p>denied to user</p></li>
</ul>
<p>Denying the user has the highest priority</p>
<hr>
<p>The matter in PHP is quite simple:</p>
<ul>
<li><p>I create an array with all permissions</p></li>
<li><p>I am getting permissions for a role (order by access)</p></li>
<li><p>I assign access, if it's denied, I overwrite access with denied</p></li>
<li><p>I do the same for user permissions</p></li>
<li><p>I assign access, if it's denied, I overwrite access with denied</p></li>
</ul>
<p>This way I have the whole array with permissions for a specific user, e.g. $ user['permission']['delete_post'] // output: false || true</p>
<p>I need to do permission inspection now. This means which user has access to e.g. 'delete_post'</p>
<p>I have this database scructure:
<img src="https://scontent-waw1-1.xx.fbcdn.net/v/t1.0-9/70590333_457218828340804_3608592236033343488_n.jpg?_nc_cat=102&_nc_oc=AQnGibnOo1is06WBQttvttJhQLXpd9A7yj3D_CQjVyet2V3qvQWm_e9cZqO4MBml2XM&_nc_ht=scontent-waw1-1.xx&oh=d49f23e8383b0992dcf01ebd8b6e7705&oe=5DFFE2A1" alt="DB structure">
Here fiddle with database: <a href="https://www.db-fiddle.com/f/sjhDVF9goxcvkpBVoxAE5M/1?fbclid=IwAR1C9NaWSDKw_qPp9JjUHw1gFiPI0aBqTQ49O-lT1cYeRrLFJA4iGt64zoU" rel="nofollow noreferrer">DB fiddle</a></p>
<p>I have problem with first query:</p>
<pre><code>**Query #1**
=============================================
List of all roles related to permission with id 3 */
SELECT DISTINCT role_id, access, permission_id FROM role_permissions WHERE permission_id=3 ORDER BY role_id, access DESC;
| role_id | access | permission_id |
| ------- | ------ | ------------- |
| 5 | 0 | 3 |
| 8 | 1 | 3 |
| 10 | 1 | 3 |
| 10 | 0 | 3 |
</code></pre>
<p>As expected I should get </p>
<pre><code>| role_id | access | permission_id |
| ------- | ------ | ------------- |
| 8 | 1 | 3 |
</code></pre>
<p>I cant add <code>WHERE permission_id=3 AND access=1</code>, because i getting result: role_id=8 and role_id=10, but role_id=10 doesn't really have access.</p>
| 3 | 1,165 |
combining get_absolute_url into a raw SQL statement in django
|
<p>Am working on a django application with uses several complex queries to return ranks, ratios and other complicated output. I've followed few exampled from the web which helped me find the best way to put it and retrieve data from the query set returned</p>
<p>Yet, I would like to find a way to inject custom details into a given record, for example in my case, am trying to associate the get_absolute_url() value into the returned record set</p>
<p>Below is an example which returns the most used interests, this query will always return a limited queryset, is there a way to extend the returned dictionary with the get_absolute_url() value of the model? </p>
<pre><code>def most_used_interests(self, limit_by=10):
cursor = connection.cursor()
cursor.execute("""
SELECT
i.name,
i.name_ar,
i.name_en,
ij.interest_id,
SUM (ij.C) item_count
FROM
(
SELECT
C .interest_id,
COUNT (b. ID) C
FROM
bargain_bargain b,
bargain_bargain_bargain_target C
WHERE
b. ID = C .bargain_id
GROUP BY
C .interest_id
UNION
SELECT
x.interest_id,
COUNT (P . ID) C
FROM
promotion_promotion P,
promotion_promotion_promo_target x
WHERE
x.promotion_id = P . ID
GROUP BY
x.interest_id
) ij, list_interest i
WHERE i.id=ij.interest_id
GROUP BY
ij.interest_id,
i.name,
i.name_ar,
i.name_en
ORDER BY
item_count DESC
LIMIT %s
""", [limit_by, ])
desc = cursor.description
if cursor.rowcount:
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
return None
</code></pre>
| 3 | 1,290 |
PHP emails from form scramble cyrillic characters
|
<p>Here's what this is all about. Since I am using PHP as of today I am facing this issue.
I have build a form , for the ISP company that I work for, which emails the form results. Customers fill out this form to request new service from us. Since the company is foreign (Bulgarian) 99% of people are going to fill it out in Cyrillic , so I tested it by filling it out myself and I got this email.</p>
<hr>
<p>From: ÐÑд </p>
<p>Phone number: 56 </p>
<p>Selected Services: </p>
<p>Internet: 100 || TV: comfort </p>
<p>Message: </p>
<p>ЪЕÐÐÐÐÐÐ </p>
<hr>
<p>So I made some research , checked out a few other posts about this in StackOverflow but none worked... most suggested to add
<code>$header .= "\nContent-type: text/plain; charset=\"utf-8\"";</code></p>
<p>One issue is that I'm not sure EXACTLY how to implement this solution, second is that it didn't work for the person who asked the question, not even in one of the questions I reviewed.</p>
<p>Here is the PHP code and the HTML one, hoping you can give me an EXACT way of fixing it, since I have barely no idea of syntax in PHP.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Online Request</title>
<meta content="php, contact, form, thinking" name="keywords">
<meta content="Contact us and let us know if we can help you out further." name="description">
<style>
input, textarea {
color: #fff;
padding: 5px;
margin: 10px;
font-family: Cambria, Cochin, serif;
font-size: medium;
font-weight: bold;
outline: none;
}
p {
font-family: Cambria, Cochin, serif;
font-size: large;
margin-bottom: -5px;
}
input[type=text], textarea {
width: 350px;
background-color: #000;
border: 1px solid #000;
}
input[type=submit] {
width: 100px;
background-color: #710000;
border: 1px solid #000;
font-size: large;
color: #FFFFFF;
}
input[type=submit]:hover {
background-color: #990000;
cursor: pointer;
}
input[type=submit]:active {
background-color: #4A6F00;
}
h1 {
text-size: 26px;
font-family: Arial;
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
color: #ff0000;}
body {
padding: 10px;
background-color: #F4F4F4;
}
.checkbox {
font-family: Cambria, Cochin, serif;
font-size: large;
margin-bottom: -5px;
}
</style>
</head>
<body>
<h1>Online Request</h1>
<form action="emailer.php" method="POST" accept-charset="UTF-8">
<div>
<p>Имена</p>
<input name="name" type="text"> <br>
</div>
<div>
<p>Телефон за връзка</p>
<input type="text" name="number" min="10" max="10">
<br>
</div>
<div>
<p> Вид услуга - Internet </p> <br/>
<input name="servicetypeINT" type="radio" value="30"><span class="checkbox"> Internet Value - 30Mpbs </span> <br/>
<input name="servicetypeINT" type="radio" value="60"><span class="checkbox"> Internet Mania - 60 Mbps </span><br/>
<input name="servicetypeINT" type="radio" value="100"><span class="checkbox"> Internet Extreme - 100Mbps</span> <br/>
<input name="servicetypeINT" type="radio" value="150"><span class="checkbox"> Internet Pro - 150Mpbs</span><br/>
</div>
<hr/>
<div>
<p>Вид услуга - Телевизия</p> <br/>
<input name="servicetypeTV" type="radio" value="anal"><span class="checkbox"> Аналогова телевизия - 50 канала </span> <br/>
<input name="servicetypeTV" type="radio" value="start"><span class="checkbox"> Start TV - 40+ Цифрови канала </span><br/>
<input name="servicetypeTV" type="radio" value="comfort"><span class="checkbox"> Confort TV - 160+ Цифрови канала</span> <br/>
<input name="servicetypeTV" type="radio" value="mania"><span class="checkbox"> Mania TV - 160+ Цифрови / 20+ HD канала</span><br/>
</div>
<div>
<p>Comment</p>
<textarea cols="30" name="comment" rows="9"></textarea>
<br> </div>
<div>
<input name="submit" type="submit" value="Изпрати"> </div>
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])) {
$to = "denislav@svishtov.net";
$subject = "New Internet and/or TV request";
// data the visitor provided
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$phone_field = filter_var($_POST['number']);
$selectedINT_field = filter_var($_POST['servicetypeINT']);
$selectedTV_field = filter_var($_POST['servicetypeTV']);
$comment = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
//constructing the message
$body = "
From: $name_field\n\n
Phone number: $phone_field\n\n
Selected Services:\n\nInternet: $selectedINT_field || TV: $selectedTV_field \n\n
Message:\n\n $comment ";
// ...and away we go!
mail($to, $subject, $body);
// redirect to confirmation
header('Location: confirmation.html');
} else {
// handle the error somehow
echo "Грешка в попълването на формата";
}
?>
</code></pre>
<p>Another interesting fact is that when I opened the file from my local machine (since if I try from the one hosted online, I will get the error echo) the Cyrillic text in the php code itself was displayed just like the email result...
But when I opened it from the host , by directly addressing it I got the error message right... in Bulgarian... without any gibberish.</p>
<p>The line of code in the PHP</p>
<pre><code>header('Content-Type: text/html; charset=utf-8');
</code></pre>
<p>seemed to convert the header message. I tried addressing <code>$name_field('Content-Type: text/html; charset=utf-8');</code></p>
<p>But result was <em>blank</em>, the php didn't function properly, I'm guessing since I gave it a wrong or inoperable line of code with that addressing of <code>$name_field</code>.</p>
<p>Question is, how do I address it properly and I'm I even on the right track with this approach?</p>
| 3 | 2,880 |
I would like not to use root as global
|
<p>Hello I am writing an avl tree and I have one issue . I am currently having a root as global since I use it in the class as well as in main , how can I write it without having it global?</p>
<pre><code>struct avl_node {
int data;
struct avl_node *left;
struct avl_node *right;
}*root;
class avlTree {
public:
int height(avl_node *temp)
{
int h = 0;
if (temp != NULL)
{
int l_height = height (temp->left);
int r_height = height (temp->right);
int max_height = max (l_height, r_height);
h = max_height + 1;
}
return h;
}
int diff(avl_node *temp)
{
int l_height = height (temp->left);
int r_height = height (temp->right);
int b_factor= l_height - r_height;
return b_factor;
}
avl_node *rr_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->right;
parent->right = temp->left;
temp->left = parent;
return temp;
}
avl_node *ll_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
avl_node *lr_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->left;
parent->left = rr_rotation (temp);
return ll_rotation (parent);
}
avl_node *rl_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->right;
parent->right = ll_rotation (temp);
return rr_rotation (parent);
}
avl_node* balance(avl_node *temp)
{
int bal_factor = diff (temp);
if (bal_factor > 1)
{
if (diff (temp->left) > 0)
temp = ll_rotation (temp);
else
temp = lr_rotation (temp);
}
else if (bal_factor < -1)
{
if (diff (temp->right) > 0)
temp = rl_rotation (temp);
else
temp = rr_rotation (temp);
}
return temp;
}
avl_node* insert(avl_node *root, int value)
{
if (root == NULL)
{
root = new avl_node;
root->data = value;
root->left = NULL;
root->right = NULL;
return root;
}
else if (value < root->data)
{
root->left = insert(root->left, value);
root = balance (root);
}
else if (value >= root->data)
{
root->right = insert(root->right, value);
root = balance (root);
}
return root;
}
void display(avl_node *ptr, int level)
{
int i;
if (ptr!=NULL)
{
display(ptr->right, level + 1);
printf("\n");
if (ptr == root)
cout<<"Root -> ";
for (i = 0; i < level && ptr != root; i++)
cout<<" ";
cout<<ptr->data;
display(ptr->left, level + 1);
}
}
void inorder(avl_node *tree)
{
if (tree == NULL)
return;
inorder (tree->left);
cout<<tree->data<<" ";
inorder (tree->right);
}
void preorder(avl_node *tree)
{
if (tree == NULL)
return;
cout<<tree->data<<" ";
preorder (tree->left);
preorder (tree->right);
}
void postorder(avl_node *tree)
{
if (tree == NULL)
return;
postorder ( tree ->left );
postorder ( tree ->right );
cout<<tree->data<<" ";
}
avlTree()
{
root = NULL;
}
};
int main()
{
int choice, item;
avlTree avl;
while (1)
{
cout<<"\n---------------------"<<endl;
cout<<"AVL Tree Implementation"<<endl;
cout<<"\n---------------------"<<endl;
cout<<"1.Insert Element into the tree"<<endl;
cout<<"2.Display Balanced AVL Tree"<<endl;
cout<<"3.InOrder traversal"<<endl;
cout<<"4.PreOrder traversal"<<endl;
cout<<"5.PostOrder traversal"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Enter your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
system("cls");
cout<<"Enter value to be inserted: ";
cin>>item;
root = avl.insert(root, item);
break;
case 2:
system("cls");
if (root == NULL)
{
cout<<"Tree is Empty"<<endl;
continue;
}
cout<<"Balanced AVL Tree:"<<endl;
avl.display(root, 1);
break;
case 3:
system("cls");
cout<<"Inorder Traversal:"<<endl;
avl.inorder(root);
cout<<endl;
break;
case 4:
system("cls");
cout<<"Preorder Traversal:"<<endl;
avl.preorder(root);
cout<<endl;
break;
case 5:
system("cls");
cout<<"Postorder Traversal:"<<endl;
avl.postorder(root);
cout<<endl;
break;
case 6:
exit(1);
break;
default:
system("cls");
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
</code></pre>
| 3 | 4,033 |
Google Map API not plotting array of markers
|
<p>I need some advice or a telling off because my code is wrong. I'm new to JQuery and google maps api. I have a JSON get to retrieve my data. I have declared an array and stored (hopefully this is the correct way to do this).</p>
<p>update** - Thanks to @geocodezip I have updated my code to allow correct population of array.</p>
<p>When I run my application the map loads fine but no markers.
I have changed my Google maps initializeMap() to the asynchronous version </p>
<pre><code>function initializeMap() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</code></pre>
<p><a href="http://i.stack.imgur.com/wBFau.png" rel="nofollow">My array in console.log image</a></p>
<p>I now have an array populated, but still no markers on my map.</p>
<p>This is my whole script. Maybe there are some major flaws. </p>
<pre><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//define variables
var geocoder;
var citylat = 0;
var citylng = 0;
var carparksArray = [];
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction()
{
alert("Geocoder failed");
}
function initialize()
{
geocoder = new google.maps.Geocoder();
}
//get city of current location and runs codeAddress()
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ latLng: latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
$.each(arrAddress, function (i, address_component) {
if (address_component.types[0] == "postal_town") {
itemPostalTown = address_component.address_components[0].long_name;
document.getElementById("town").value = itemPostalTown;
codeAddress();
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
//get latlong of city and runs getCarParks()
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("town").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
citylat = results[0].geometry.location.lat();
citylng = results[0].geometry.location.lng();
getCarParksLatLng();
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//sets map up
function initializeMap() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
//loads map
function loadScript() {
var script = document.createElement("script");
script.src = "http://maps.googleapis.com/maps/api/js?callback=initializeMap";
document.body.appendChild(script);
}
//get carparks names
function getCarParksLatLng() {
var town = document.getElementById("town").value;
var carparkList = "<p>";
var uri = "http://localhost/api/carparks?$filter=Town%20eq%20%27" + town + "%27";
$.getJSON(uri,
function (data) {
carparksArray = [];
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparksArray.push([val.Name, val.Latitude, val.Longitude]);
});
console.log(carparksArray);
});
loadScript();
}
$(document).ready(initialize)
</script>
</code></pre>
| 3 | 2,888 |
QUEUE and 'IF' 'ELSE' 'WHILE' statements from scratch and running functions
|
<p>I'm making a game engine in javascript, and needed some way to code some actions.</p>
<p>The code is here:</p>
<pre><code><!DOCTYPE html> <html> <body> <script>
var engine={}, actions={}; engine.atomStack=new Array();
events = {
1: ["action1|5","action2|2;2","action1|2"],
2: ["action2|5;2","action2|2;2"],
3: ["action2|5;2","action1|2"] };
engine.runatomStack = function(){
while(engine.atomStack.length > 0){
var actionToRun = engine.atomStack.shift();
actionToRun[0](actionToRun[1]); } };
eventActivate = function(event) {
for (var i = 0; i < events[event].length ; i++) {
var actionAndParam = events[event][i].split('|');
translateActions(actionAndParam[0],actionAndParam[1]); } };
engine.action1 = function( param ) {
console.log("executed action 1, param "+param[0]); }
engine.action2 = function( param ) {
console.log("executed action 2, params "+param[0]+" "+param[1]); }
actions.action1 = function( param ) {
var params = param.split(';');
engine.atomStack.push([engine.action1,params]); }
actions.action2 = function( param ) {
var params = param.split(';');
params[1]=parseInt(params[1],10)+2
engine.atomStack.push([engine.action2,params]); }
translateActions = function(action, param) { actions[action](param); };
</script> </body> </html>
</code></pre>
<p>Something happens, and I need to run the actions inside an event. I call eventActivate passing the event that should happen. The function translateAction read this information and calls the function that set up the actions. My logic is based that a level contain events, an event can contain actions, and each different action contain atoms.</p>
<p>Example: at some point you call eventActivate(1) and that will push the relative events on the stack. Then from time to time the engine is used and calls engine.runatomStack() to execute whatever is there.</p>
<pre><code>//engine.atomStack is Array [ ]
eventActivate(2)
//engine.atomStack is Array [ Array[2], Array[2] ]
engine.runatomStack()
//prints:
// "executed action 2, params 5 4" example.html:18
// "executed action 2, params 2 4" example.html:18
//engine.atomStack is Array [ ]
</code></pre>
<p>Ok, so my engine start to grow and all and now I think I need to add IF/ELSE statements and WHILE/BREAK loops. I have some ideas on implementation but wanted help to what's works best using this queue. Sorry if it's duplicate, but couldn't find help using Google.</p>
<p>I thought something like, if I had events:</p>
<pre><code>4: ["action2|5;2","IF|condition","action2|2;2","END|"]
5: ["action2|5;2","IF|condition","action2|2;2","ELSE|","action1|2","END|"]
</code></pre>
<p>I'm not sure how exactly to go, what's works best...</p>
<p>Link to jsFiddle version: <a href="http://jsfiddle.net/e3b0kocc/" rel="nofollow">http://jsfiddle.net/e3b0kocc/</a></p>
| 3 | 1,042 |
How to get offsetTop of element in regards to the document and not its parent?
|
<p>I had trouble wording my question, but here's the detail ! I've been struggling with how to get my navigation bullets (spans) to be highlighted when the current element is in viewport. I've initially tried using the same logic as a sidemenu tutorial I previously used elsewhere (by Web Cifar on youtube), but it doesn't quite work here.
If I console(log) the .bullet-slider class, they correctly show up. What the problem is, from what I gather, is the offsetTop of my const bulletSlide can't be calculated because the parentElement is another div and not the document (is this right?). I've looked into using an Intersection Observer instead, but being new to javascript I'm struggling in how I could implement it into my existing structure.</p>
<p>Any help and/or tips would be greatly appreciated ! Thank you !</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>/**
* By Alvaro Trigo - horizontal scroll
*/(function(){
init();
var g_containerInViewport;
function init(){
setStickyContainersSize();
bindEvents();
}
function bindEvents(){
window.addEventListener("wheel", wheelHandler);
}
function setStickyContainersSize(){
document.querySelectorAll('.sticky-container').forEach(function(container){
const stikyContainerHeight = container.querySelector('.main').scrollWidth;
container.setAttribute('style', 'height: ' + stikyContainerHeight + 'px');
});
}
function isElementInViewport (el) {
const rect = el.getBoundingClientRect();
return rect.top <= 0 && rect.bottom > document.documentElement.clientHeight;
}
function wheelHandler(evt){
const containerInViewPort = Array.from(document.querySelectorAll('.sticky-container')).filter(function(container){
return isElementInViewport(container);
})[0];
if(!containerInViewPort){
return;
}
var isPlaceHolderBelowTop = containerInViewPort.offsetTop < document.documentElement.scrollTop;
var isPlaceHolderBelowBottom = containerInViewPort.offsetTop + containerInViewPort.offsetHeight > document.documentElement.scrollTop;
let g_canScrollHorizontally = isPlaceHolderBelowTop && isPlaceHolderBelowBottom;
if(g_canScrollHorizontally){
containerInViewPort.querySelector('.main').scrollLeft += evt.deltaY;
}
}
})();
const bulletSlide = document.querySelectorAll('.bullet-slide');
const bulletGreen = document.querySelectorAll('.bullet-grn');
const bulletPink = document.querySelectorAll('.bullet-pink');
/*bullet highlight */
window.addEventListener('scroll', ()=> {
let current = '';
bulletSlide.forEach(bulletSlide => {
const sectionTop = bulletSlide.offsetTop;
const sectionHeight = bulletSlide.clientHeight;
if (scrollY >= (sectionTop - sectionHeight / 3)) {
current = bulletSlide.getAttribute('id');
}
;
})
bulletGreen.forEach( span => {
span.classList.remove('.bullet-grn-active');
if(span.classList.contains(current)){
span.classList.add('.bullet-grn-active');
}
})
bulletPink.forEach( span => {
span.classList.remove('.bullet-pink-active');
if(span.classList.contains(current)){
span.classList.add('.bullet-pink-active');
}
})
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
scroll-behavior: smooth;
}
body {
min-height: 100%;
overflow-x: hidden;
}
.frame {
min-height: 100vh;
min-width: 100vw;
padding-top: 20px;
}
.bg-grn {
background: #CCD5AE;
}
.bg-lp {
background: #E6C2CB;
}
.main {
overflow-x: hidden;
display: flex;
position: sticky;
top:0;
}
.main-slide {
min-width: 100vw;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.wrapper {
max-width: 600px;
margin: 0 auto;
}
.col-2 {
display: grid;
grid-template-columns: repeat(2, 1fr);
justify-content: space-between;
align-items: center;
gap: 80px;
}
.left-div {
display: flex;
flex-direction: column;
gap: 20px;
justify-content: center;
}
.col-1-3 {
display: grid;
grid-template-columns: 1fr 2fr;
align-items: center;
height: 100%;
gap: 60px;
}
.bullets {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
background-color: white;
margin-right: 10px;
cursor: pointer;
}
/* divider */
.divider {
height: 40vh;
width: 100vw;
background-color: #FFD6C2;
display: flex;
align-items: center;
}
.div-wrapper {
max-width: 600px;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
gap: 20px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
<div class="sticky-container frame bg-grn">
<div class="main">
<div id="etudes" class="main-slide bullet-slide">
<div class="col-2 wrapper">
<div class="left-div">
<div class="slide-bullets">
<span class="etudes bullets bullet-grn"></span>
<span class="micro bullets bullet-grn"></span>
</div>
<h2 class="title bk">Les études</h2>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. At hic esse iusto excepturi. Rerum assumenda obcaecati voluptas velit, hic autem!</p>
</div>
<div>
<div id="dates-etudes">
<p><span class="date">2017</span>Master en Marketing et Vente</p>
<p><span class="date">2015</span>Licence Langues Étrangères Appliquées</p>
<p><span class="date">2014</span>DUETI Business and Administration</p>
<p><span class="date">2013</span>DUT Techniques de Commercialisation</p>
</div>
</div>
</div>
</div>
<div id="micro" class="main-slide bullet-slide">
<div class="col-2 wrapper">
<div class="left-div">
<div class="slide-bullets">
<span class="etudes bullets bullet-grn"></span>
<span class="micro bullets bullet-grn"></span>
</div>
<h2 class="title bk">La micro-entreprise</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos error hic totam provident delectus! Aliquid error debitis amet quos eaque?</p>
</div>
<div id="paper-container">
<p class="div-title">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Itaque, corporis! !</p>
</div>
</div>
</div>
</div>
</div>
</section>
<div class="divider">
<div class="div-wrapper">
<h3 class="div-title">Depuis janvier 2022</h3>
<p class="div-p">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nisi ipsum eveniet voluptatem quis est nulla soluta ipsam voluptas fugiat odit..</p>
</div>
</div>
<section>
<div class="sticky-container frame bg-lp">
<div class="main">
<div id="pas1" class="main-slide bullet-slide">
<div class="col-1-3 wrapper">
<div class="left-div">
<div class="slide-bullets">
<span class="pas1 bullets bullet-pink"></span>
<span class="pas2 bullets bullet-pink"></span>
<span class="pas3 bullets bullet-pink"></span>
<span class="pas4 bullets bullet-pink"></span>
</div>
<h2 class="title">Mes premiers pas dans le web design</h2>
</div>
<div>
<div class="title-para">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Enim numquam vero recusandae provident, sapiente tempora sequi modi laboriosam velit dolorum!</p>
<div class="bg-pink-ptn">
<h4>Les axes de réflexion</h4>
<div class="list col-2">
<ul>
<li>l'aspect graphique et esthétique</li>
<li>l'objectif du site</li>
<li>le contenu & son organisation</li>
</ul>
<ul>
<li>les fonctionnalités</li>
<li>l'évolution prévue</li>
<li>la gestion du site</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pas2" class="main-slide bullet-slide">
<div class="col-1-3 wrapper">
<div class="left-div">
<div class="slide-bullets">
<span class="pas1 bullets bullet-pink"></span>
<span class="pas2 bullets bullet-pink"></span>
<span class="pas3 bullets bullet-pink"></span>
<span class="pas4 bullets bullet-pink"></span>
</div>
<h2 class="title">Mes premiers pas dans le web design</h2>
</div>
<div class="title-para">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati consequatur molestias ab maxime, dolor dolorum esse incidunt dolores nulla alias?</p>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Atque ex perferendis molestias sequi et aliquid nam corrupti quis voluptatum enim.</span></p>
</div>
</div>
</div>
<div id="pas3" class="main-slide bullet-slide">
<div class="col-1-3 wrapper">
<div class="left-div">
<div class="slide-bullets">
<span class="pas1 bullets bullet-pink"></span>
<span class="pas2 bullets bullet-pink"></span>
<span class="pas3 bullets bullet-pink"></span>
<span class="pas4 bullets bullet-pink"></span>
</div>
<h2 class="title">Mes premiers pas dans le web design</h2>
</div>
<div class="title-para">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos, ratione? Iure deleniti mollitia ea provident labore alias quo minus placeat? Voluptates veritatis praesentium debitis officiis ducimus quae consectetur, qui laudantium modi eveniet aspernatur fugit, veniam rerum dolorum id temporibus provident!</p>
</div>
</div>
</div>
<div id="pas4" class="main-slide bullet-slide">
<div class="col-1-3 wrapper">
<div class="left-div">
<div class="slide-bullets">
<span class="pas1 bullets bullet-pink"></span>
<span class="pas2 bullets bullet-pink"></span>
<span class="pas3 bullets bullet-pink"></span>
<span class="pas4 bullets bullet-pink"></span>
</div>
<h2 class="title">Mes premiers pas dans le web design</h2>
</div>
<div class="title-para">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam molestiae, minima quo voluptas deleniti aliquid blanditiis beatae! Officiis, eos commodi!</p>
</div>
</div>
</div>
</div>
</div> </code></pre>
</div>
</div>
</p>
| 3 | 7,492 |
ASP.NET MVC Mismatch error on a google chart
|
<p>I'm running into an javascript error with google charts. I've got this to work with a different query but I need the result of the query below to be displayed. The problem as of now is that the chart is not appearing. Any thoughts on debugging this?</p>
<pre><code>Uncaught (in promise) Error: Type mismatch. Value 1 does not match type string in column index 0
</code></pre>
<p>Here's my Controller: </p>
<pre><code> #region Total Hours Per Month
var querythpmpro = (from r in db.HolidayRequestForms
where r.EmployeeID == id
group r by r.MonthOfHoliday into g
select new { Value = g.Key, Count = g.Sum(h => h.HoursTaken) }
).OrderBy(e => e.Value);
var resultthpmpro = querythpmpro.ToList();
var datachartthpmpro = new object[resultthpmpro.Count];
int Q = 0;
foreach (var i in resultthpmpro)
{
datachartthpmpro[Q] = new object[] { i.Value, i.Count};
Q++;
}
string datathpmpro = JsonConvert.SerializeObject(datachartthpmpro, Formatting.None);
ViewBag.datajthpmpro = new HtmlString(datathpmpro);
#endregion
</code></pre>
<p>And my script: </p>
<pre><code> <script>
var datathpmpro = '@ViewBag.datajthpmpro';
var datassthpmpro = JSON.parse(datathpmpro);
</script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChartA);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChartA() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Value');
data.addColumn('number', 'Count');
data.addRows(datassthpmpro);
// Set chart options
var options = {
'title': 'Holiday Hours Taken Per Month',
'width': 600,
'height': 350,
'hAxis': {title: 'Month Number'},
'vAxis': {title: 'Holiday Hours Taken'},
'is3D': true,
'legend': 'none'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chartTHPMpro_div'));
chart.draw(data, options);
}
</code></pre>
<p></p>
<p>I'd like the result to have a google chart appear that uses the query above. </p>
| 3 | 1,056 |
How are remote actors created on joining of new nodes in akka?
|
<p>Explaining my Akka cluster setup:</p>
<ul>
<li>I have remote actors in a multi node Akka cluster.</li>
<li>Actors are behind Router which is of Singleton Type.</li>
<li>Singleton Router is behind a Cluster Singleton Proxy.</li>
<li>Also, on a side note, I have N type of actors, each doing a different kind of task and managed by a different Router.</li>
</ul>
<p>Code snippet(Java)</p>
<pre><code>Config config = ConfigFactory.parseString(
"akka.remote.netty.tcp.port=" + 2551).withFallback(
ConfigFactory.load());
ActorSystem system = ActorSystem.create("CalcSystem", config);
Address[] addresses = {
AddressFromURIString.parse("akka.tcp://CalcSystem@127.0.0.1:2551"),
AddressFromURIString.parse("akka.tcp://CalcSystem@127.0.0.1:2552"),
AddressFromURIString.parse("akka.tcp://CalcSystem@127.0.0.1:2553")
};
ActorRef router = system.actorOf(
ClusterSingletonManager.props(new ClusterRouterPool(new RoundRobinPool(2),
new ClusterRouterPoolSettings(100, 3,
false, "")).props(
new RemoteRouterConfig(new RoundRobinPool(6), addresses).props(
Worker.createWorker())),PoisonPill.getInstance(),settings),"workerRouter");
ClusterSingletonProxySettings proxySettings = ClusterSingletonProxySettings.create(system);
ActorRef routerProxy = system.actorOf(ClusterSingletonProxy.props("/user/workerRouter", proxySettings), "routerProxy");
</code></pre>
<p>My doubt is regarding how make the list of Address a dynamic one? The current hardcoded list of Address won't work in production.</p>
<p>As soon as new nodes join in the cluster, Routers/ClusterSingletonManager should be able to recognize that and create remote actors on that new node(It could be a brand new node added to an already existing cluster or it could be the case of whole cluster booting up, for the very first time or in the case of new code deployments)</p>
<p>As far as my seed nodes are concerned, they are mentioned in the akka.conf file.</p>
<pre><code>akka {
actor {
provider = "akka.cluster.ClusterActorRefProvider"
}
cluster {
seed-nodes = [
"akka.tcp://CalcSystem@127.0.0.1:2551"]
}
}
</code></pre>
| 3 | 1,036 |
Got Solution How to store the cookies in login and delete the cookies in logout action
|
<pre><code>My Problem is solved
</code></pre>
<p>I am doing an application that is getting cookies from server side. I want to store the cookies and delete the cookies at logout function but I don't know how to do this.
Based on this cookies my app has to show some additional benefits to the user so I want to save this cookies.
This is login request:</p>
<pre><code>- (IBAction)enterButtonAction:(id)sender {
NSString *post =[NSString stringWithFormat:@"user[email]=%@&user[password]=%@",userNameTF.text,passWordTF.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)postData.length];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:postData];
NSURLConnection * connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection != nil) {
NSLog(@"Connection Successfull");
self.responseData = [NSMutableData alloc];
[connection start];
}else {
NSLog(@"Failed");
}
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError * parseError = nil;
NSMutableDictionary * _jsonDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&parseError];
NSLog(@"%@",_jsonDictionary);
NSString * roleString = [_jsonDictionary objectForKey:@"role"];
if ([roleString isEqualToString:@"user"]) {
UIStoryboard * storyBD = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UITabBarController * obj = [storyBD instantiateViewControllerWithIdentifier:@"tab"];
[self.navigationController pushViewController:obj animated:YES];
}
else {
[self alertStatus:@"Please Enter 'Correct Email & Password'" :nil];
}
}
</code></pre>
<p>//// Solution is this one it is working now very fine there is no need to store or delete the cookies every thing will handle this code </p>
<pre><code>NSString *post =[NSString stringWithFormat:@"user[email]=%@&user[password]=%@",userNameTF.text,passWordTF.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)postData.length];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setValue:@"myCookie" forHTTPHeaderField:@"Set-cookie"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:postData];
NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
@"http://yourwebsite.com", NSHTTPCookieDomain,
@"\\", NSHTTPCookiePath,
@"myCookie", NSHTTPCookieName,
@"1234", NSHTTPCookieValue,
nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
NSArray* cookieArray = [NSArray arrayWithObject:cookie];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
[request setAllHTTPHeaderFields:headers];
NSURLConnection * connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection != nil) {
NSLog(@"Connection Successfull");
self.responseData = [NSMutableData alloc];
[connection start];
}else {
[sharedAppDelegate dismissGlobalHUD];
NSLog(@"Failed");
}
</code></pre>
| 3 | 1,875 |
iOS Segue opening two view controllers (assuming two table cells clicked)
|
<p>When I click a table cell in my application it opens two view controllers. Which it seems to assume that I have clicked two cells, since it opens the cell before and the one I have clicked.</p>
<p>The first 3 cells are pretty much static, every other cell underneath the "ingredients" heading are dynamic. Hence why indexPath - 3</p>
<p>I created the segue between the table view and the view controller in the interface builder.</p>
<p>Table View:</p>
<p><img src="https://i.stack.imgur.com/uC2EL.png" alt="enter image description here"></p>
<p>First view controller/segue:</p>
<p><img src="https://i.imgur.com/SNnhhMl.png" alt="enter image description here"></p>
<p>Second view controller segue:</p>
<p><img src="https://i.stack.imgur.com/I0JqX.png" alt="enter image description here"></p>
<p>Code for the segue:</p>
<pre><code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedIngredient = self.selectedProduct.ingredientsArray[indexPath.row - 3];
[self performSegueWithIdentifier:@"ingViewSegue" sender:self];
NSLog(@"selected ingredient %@", self.selectedIngredient);
}
#pragma mark segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
IngredientWebViewController *webView = segue.destinationViewController;
webView.selectedIngredient = self.selectedIngredient;
}
</code></pre>
<p>Number of rows in table:</p>
<pre><code>#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_selectedProduct.ingredientsArray count] + 3;
}
</code></pre>
<p>Code to populate table:</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0)
{
TitleCell* titleCell = (TitleCell*)[self.tableView dequeueReusableCellWithIdentifier:@"TitleCell" forIndexPath:indexPath];
titleCell.nameLabel.text = self.selectedProduct.productName;
titleCell.brandLabel.text = self.selectedProduct.productBrand;
return titleCell;
}
else if(indexPath.row == 1)
{
return [self.tableView dequeueReusableCellWithIdentifier:@"RatingCell" forIndexPath:indexPath];
}
else if(indexPath.row == 2)
{
return [self.tableView dequeueReusableCellWithIdentifier:@"IngredientHeaderCell" forIndexPath:indexPath];
}
else
{
IngredientsCell* ingCell = (IngredientsCell*)[self.tableView dequeueReusableCellWithIdentifier:@"IngredientCell" forIndexPath:indexPath];
ingCell.ingredientNameLabel.text = self.selectedProduct.ingredientsArray[indexPath.row - 3];
if([self.selectedProduct.ratingsArray[indexPath.row -3] isEqual: @"4"])
{
ingCell.ingredientsImage.image = [UIImage imageNamed:@"icon_safe.png"];
}
else if([self.selectedProduct.ratingsArray[indexPath.row -3] isEqual: @"3"])
{
ingCell.ingredientsImage.image = [UIImage imageNamed:@"icon_low.png"];
}
else if([self.selectedProduct.ratingsArray[indexPath.row -3] isEqual: @"2"])
{
ingCell.ingredientsImage.image = [UIImage imageNamed:@"icon_med.png"];
}
else if([self.selectedProduct.ratingsArray[indexPath.row -3] isEqual: @"1"])
{
ingCell.ingredientsImage.image = [UIImage imageNamed:@"icon_high.png"];
}
else
{
ingCell.ingredientsImage.image = [UIImage imageNamed:@"icon_safe.png"];
}
return ingCell;
}
}
</code></pre>
<p>Code to alter cell height:</p>
<pre><code>-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0)
{
UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier:@"TitleCell"];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height + 1;
}
else if(indexPath.row == 1)
{
UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier:@"RatingCell"];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return 118;
}
else if(indexPath.row == 2)
{
UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier:@"IngredientHeaderCell"];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height + 1;
}
else
{
UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier:@"IngredientCell"];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return 60;
}
}
</code></pre>
| 3 | 1,908 |
VBA Array is being transposed into the second column of a range, not sure why?
|
<p>I have the below VBA code which calculates a number of output values and stores them in as an array (beginning_gross_facility_balance being one of the examples).</p>
<p>when I try to print the resulting array values into excel (to output2 range, which is C16:J515 in an excel tab, the array is exported/printed into column D and from row 17.</p>
<p>currently, i = 1 and j = 25</p>
<p>grateful if someone could shine some light on why this is happening/how can I ensure that the output is copied into the first column and first row of the range</p>
<p>Sub AssetProjection2()</p>
<p>Application.ScreenUpdating = False</p>
<pre><code>'pluming variables
Dim i As Integer
Dim j As Integer
Dim Period As Integer
Dim numberOfLoans As Integer
numberOfLoans = WorksheetFunction.CountA(Range("LoanCount")) - 1
ReDim tape(numberOfLoans)
Dim pool_lag As Double
Dim total_gross_facility_limit As Double
Dim beginning_gross_facility_balance(500, 500) As Double
Dim interest_rate As Double
Dim arrangement_fee As Double
Dim admin_fee As Double
Dim Audit_fee As Double
Dim insurance_fee As Double
Dim exit_fee As Double
Dim loan_term As Double
Dim loan_remaining_term As Double
Dim default_flag As String
Dim GDV As Double
'only relevant for loans with no seasoning
Dim first_tranche_percentage As Double
Dim seasoning As Double
Dim adjustment_factor As Double
Dim development_fees As Double
Dim lag As Double
Dim sev As Double
'temps/ output variables on a loan by loan basis (so i can call info from any period and any loan)
Dim pmt As Double
Dim Recovery As Double
Dim TempDefault(500, 500) As Double
'end of period balance is the cumulative gross facility at any given point, at maturity, this should match total gross loan limit
Dim end_of_period_gross_balance(500, 500) As Double
Dim periodic_interest(500, 500) As Double
Dim cumulative_retained_interest(500, 500) As Double
Dim periodic_gross_drawdown(500, 500) As Double
Dim periodic_net_advance(500, 500) As Double
Dim cumulative_net_advance(500, 500) As Double
'the loan redeems in one go, then principal and interest redemptions are split for transparency
Dim total_facility_repayment(500, 500) As Double
Dim principal_redemption(500, 500) As Double
Dim interest_redemption(500, 500) As Double
'pristine/stressed variables
Dim prin As Double
Dim prepay As Double
'scenarios
Dim DefScen As Integer
Dim PrepScen As Integer
Dim SevScen As Integer
Dim LagScen As Integer
Dim IRScen As Integer
'ouput variables
'the below is currently not being used
Dim oBegBalance(500) As Double
Dim oEndBalance(500) As Double
Dim oDefault(500) As Double
Dim oInterest(500) As Double
Dim oPrincipal(500) As Double
Dim oPrepayment(500) As Double
Dim oRecovery(500) As Double
Dim oAccrued(500) As Double
Dim oCumTheoreticalDef(500) As Double
'initialise CF time
Period = 1
pool_lag = Range("total_lag").Value
'this loop will project asset cashflows assuming non-seasonality, then the next loop will look-up the figures for each loan based on the loan's seasonality
For i = 1 To numberOfLoans
SevScen = Range("severity_scen").Cells(i + 1)
LagScen = Range("lag_scen").Cells(i + 1)
'IR scenario currently not in use, when floating interest is modelled, this will be already plugged in
IRScen = Range("IR_scen").Cells(i + 1)
interest_rate = Range("interest_rate").Cells(i + 1)
loan_remaining_term = Range("loan_remaining_term").Cells(i + 1)
loan_term = Range("loan_term").Cells(i + 1)
seasoning = loan_term - loan_remaining_term
first_tranche_percentage = Range("first_tranche_percentage").Cells(i + 1)
total_gross_facility_limit = Range("total_gross_limit").Cells(i + 1)
adjustment_factor = 1.1
admin_fee = Range("admin_fee").Cells(i + 1)
default_flag = Range("default_flag").Cells(i + 1)
For j = 1 To loan_term + pool_lag
lag = Range("LagScenarios").Cells(loan_term + j + 4, LagScen)
sev = Range("severityScenarios").Cells(loan_term + j + 4, SevScen)
If j = 1 Then
arrangement_fee = Range("arrangement_fee").Cells(i + 1)
Audit_fee = Range("Audit_fee").Cells(i + 1)
insurance_fee = Range("insurance_fee").Cells(i + 1)
Else
arrangement_fee = 0
Audit_fee = 0
insurance_fee = 0
End If
If j = loan_term Then
exit_fee = Range("exit_fee").Cells(i + 1)
Else
exit_fee = 0
End If
development_fees = arrangement_fee + Audit_fee + insurance_fee + admin_fee
Recovery = 0
'term is original term, not really used anywhere at the moment, only as a static figure to work out seasonality for input curves
loan_term = Range("loan_term").Cells(i + 1)
'remaining term doesnt need to be dynamic as the PMT formula takes the current J into account to work out the dynamic remaining term
loan_remaining_term = Range("loan_remaining_term").Cells(i + 1)
interest_rate = Range("interest_rate").Cells(i + 1)
If j = 1 Then
beginning_gross_facility_balance(i, j) = total_gross_facility_limit * first_tranche_percentage
Else
beginning_gross_facility_balance(i, j) = end_of_period_gross_balance(i, j - 1)
End If
'gross drawdown. if first disbursment, it's first_tranche_percentage, else, it's a fixed figure such that from month 2 to maturity, the total gross facility equals the gross loan limit. for the model, I will start with a basic number and learn how to apploy a goal seek/solver figure
'draws happen at the beginning of the period and so every period's accrued interest is on the end of period balance J - 1 + period J further draw (J=1 has end of previous period as 0 bcs the loan is new
If j = 1 Then
periodic_gross_drawdown(i, j) = 0
Else
If j < loan_term Then
periodic_gross_drawdown(i, j) = (total_gross_facility_limit - periodic_gross_drawdown(i, 1)) / (loan_term - 2) / adjustment_factor
Else
periodic_gross_drawdown(i, j) = 0
End If
End If
If j = 1 Then
periodic_net_advance(i, j) = beginning_gross_facility_balance(i, j) - development_fees
Else
periodic_net_advance(i, j) = periodic_gross_drawdown(i, j) - development_fees
End If
If j = 1 Then
cumulative_net_advance(i, j) = periodic_net_advance(i, j)
Else
cumulative_net_advance(i, j) = cumulative_net_advance(i, j - 1) + periodic_net_advance(i, j)
End If
periodic_interest(i, j) = (beginning_gross_facility_balance(i, j) + periodic_gross_drawdown(i, j)) * interest_rate
end_of_period_gross_balance(i, j) = beginning_gross_facility_balance(i, j) + periodic_interest(i, j)
If j = loan_term And default_flag = "N" Then
total_facility_repayment(i, j) = end_of_period_gross_balance(i, j)
principal_redemption(i, j) = cumulative_net_advance(i, j)
interest_redemption(i, j) = total_facility_repayment(i, j) - principal_redemption(i, j)
Else
total_facility_repayment(i, j) = 0
principal_redemption(i, j) = 0
interest_redemption(i, j) = 0
End If
If j = loan_term + lag And default_flag = "Y" Then
Recovery = total_facility_repayment(i, j - lag) * (1 - sev) 'accrue some defaulted int rate or keep it simple?
Else
Recovery = 0
End If
Next j
Next i
'write it out
'Range("beginning_balance_output") = WorksheetFunction.Transpose(beginning_gross_facility_balance)
Range("output2") = WorksheetFunction.Transpose(beginning_gross_facility_balance)
' Range("output2").Columns(3) = WorksheetFunction.Transpose(periodic_net_advance)
'Range("output2").Columns(4) = WorksheetFunction.Transpose(cumulative_net_advance)
' Range("output2").Columns(5) = WorksheetFunction.Transpose(total_facility_repayment)(end_of_period_gross_balance)
End Sub
</code></pre>
| 3 | 3,427 |
jvm options -XX:+SafepointTimeout -XX:SafepointTimeoutDelay look don't work
|
<p>I detected on a server long safepoints (>10sec!) in jvm safepoint.log:</p>
<pre><code>6534.953: no vm operation [ 353 0 4 ] [ 0 0 14179 0 0 ] 0
7241.410: RevokeBias [ 357 0 1 ] [ 0 0 14621 0 0 ] 0
8501.278: BulkRevokeBias [ 356 0 6 ] [ 0 0 13440 0 2 ] 0
9667.681: no vm operation [ 349 0 8 ] [ 0 0 15236 0 0 ] 0
12094.170: G1IncCollectionPause [ 350 0 4 ] [ 0 0 15144 1 24 ] 0
13383.412: no vm operation [ 348 0 4 ] [ 0 0 15783 0 0 ] 0
13444.109: RevokeBias [ 349 0 2 ] [ 0 0 16084 0 0 ] 0
</code></pre>
<p>On my laptop I've played with -XX:SafepointTimeoutDelay=2
and it works good, printing bad threads:</p>
<pre><code># SafepointSynchronize::begin: Timeout detected:
...
# SafepointSynchronize::begin: (End of list)
<writer thread='11267'/>
vmop [threads: total initially_running wait_to_block] [time: spin block sync cleanup vmop] page_trap_count
567.766: BulkRevokeBias [ 78 1 2 ] [ 0 6 6 0 0 ] 0
</code></pre>
<p>So I've added to options to the server:
<strong>-XX:+SafepointTimeout -XX:SafepointTimeoutDelay=1000</strong>
to see which threads cause the problem, <strong>but I don't see any prints, while I still see long safepoint times</strong>.</p>
<p>Why doesn't it applied on the server?</p>
<p>Here is the actual server config (taken from safepoint.log):</p>
<pre><code>Java HotSpot(TM) 64-Bit Server VM (25.202-b08) for linux-amd64 JRE (1.8.0_202-b08), built on Dec 15 2018 12:40:22 by &quot;java_re&quot; with gcc 7.3.0
...
-XX:+PrintSafepointStatistics
-XX:PrintSafepointStatisticsCount=10
-XX:+UnlockDiagnosticVMOptions
-XX:+LogVMOutput
-XX:LogFile=/opt/pprb/card-pro/pci-pprb-eip57/logs/safepoint.log
-XX:+SafepointTimeout
-XX:SafepointTimeoutDelay=1000
...
</code></pre>
| 3 | 1,310 |
Where is my error (R Programming)
|
<p>The below code works <code>when i=0</code> and having problem <code>when i=2</code>. <br>Below is the error:</p>
<blockquote>
<p>"Error in while (Net_Present_value$NPV[year] <= 0) { :
missing value where TRUE/FALSE needed" in second iteration</p>
</blockquote>
<pre><code> vaaa=10000
concession<-data.frame("case1"=integer(vaaa),"case2"=integer(vaaa),"case3"=integer(vaaa))
#discount
discount<-c(10,11,12)
discount_sd<-c(2,2.5,2)
#volume
volume_growth<-c(15,16,17)
volume_growth_sd<-c(2.5,2,3)
#Cost
C_cost<-c(-3000000,-3500000,-4000000) # Construction cost in dollar
volume<-c(600000,700000,800000) #quantity of licence to be converted to smart driving licence
#cost per unit
cost_to_produce<-c(8,7,8) #including all cost such as material, operation and maintenance
cost_to_driver<c(11,12,13)
Net_Present_value<-data.frame(year=integer(25),value=double(25),NPV=double(25))
cash_flow<-data.frame(year=integer(25),value=double(25))
for(i in 1:3){
bstrap_discount <- rnorm(vaaa,discount[i],discount_sd[i])
#Volume
bstrap_volume <- rnorm(vaaa,volume_growth[i],volume_growth_sd[i])
for( iteration in 1:vaaa){
year<-1
#Net_Present_value=0
#cash_flow=0
Net_Present_value$NPV[year]<-C_cost[i]
cash_flow$value[year]<-C_cost[i]
new_volume<-volume[i]
print(iteration)
while(Net_Present_value$NPV[year]<=0){
#print(Net_Present_value$NPV[year])
year<-year+1
if(year==2){ #everybody should change old to new driving license
Revenue<-volume[i]*(cost_to_driver[i]-cost_to_produce[i])
NPV<-Revenue/(1+bstrap_discount[iteration]/100)^(year)
}
else if(year>2){
temp_vol<-new_volume
new_volume<-temp_vol*bstrap_volume[iteration]/100+temp_vol
Revenue<-(new_volume-temp_vol)*(cost_to_driver[i]-cost_to_produce[i])
NPV<-Revenue/(1+bstrap_discount[iteration]/100)^(year)
}
Net_Present_value$year[year]<-year
Net_Present_value$NPV[year]=Net_Present_value$NPV[year-1]+NPV
cash_flow$year[year]<-year
cash_flow$value[year]<-Revenue
}
concession$count[iteration]<-iteration
if(i==1)
concession$case1[iteration]<-year
else if (i==2)
concession$case2[iteration]<-year
else if (i==3)
concession$case3[iteration]<-year
}
}
</code></pre>
| 3 | 1,302 |
Downloading only first item from web service - Android
|
<p>I want to download items from a web service to Android app (Web service output - XML). I'm using Android Download Manager class for downloading part. </p>
<p>When I click download button , it only downloads the first item from XML list. This is what I tried. Help me to download all files. </p>
<pre><code> try {
URL url = new URL("http://localhost/WebService/gettext.aspx? ");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("image");
iname = new TextView[nodeList.getLength()];
itime = new TextView[nodeList.getLength()];
int listlength = nodeList.getLength();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
itime[i] = new TextView(this);
iname[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("iname");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
iname[i].setText(((Node) nameList.item(0)).getNodeValue());
NodeList itimeList = fstElmnt.getElementsByTagName("itime");
Element websiteElement = (Element) itimeList.item(0);
itimeList = websiteElement.getChildNodes();
itime[i].setText("ITime = "
+ ((Node) itimeList.item(0)).getNodeValue());
imgName=iname[i].getText().toString().trim();
//Image folder.
dwnload_file_path = "http://localhost/WebService/Images/"+URLEncoder.encode(iname[i].getText().toString(),"UTF-8");
String servicestring = Context.DOWNLOAD_SERVICE;
downloadmanager = (DownloadManager) getSystemService(servicestring);
Uri uri = Uri.parse(dwnload_file_path);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir("/Download",imgName.toString());
downloadId = downloadmanager.enqueue(request);
}
} catch (Exception e) {
System.out.println("EEEEEEEEE "+ e.toString());
//Toast.makeText(getBaseContext(),"35",Toast.LENGTH_SHORT).show();
}
</code></pre>
<p>This is the XML output from web service.</p>
<pre><code><!-- language: xml -->
<image>
<iname>abdf.jpg</iname>
<itime>10000</itime>
<iname>bcdf.jpg</iname>
<itime>10000</itime>
<iname>cd.jpg</iname>
<itime>10000</itime>
<iname>efe.jpg</iname>
<itime>10000</itime>
<iname>ggef.jpg</iname>
<itime>10000</itime>
<iname>hiefef.jpg</iname>
<itime>10000</itime>
<iname>mmfer.jpg</iname>
<itime>10000</itime>
<iname>nnnef.jpg</iname>
<itime>10000</itime>
<iname>erer.jpg</iname>
<itime>10000</itime>
</image>
</code></pre>
| 3 | 1,450 |
Sprite Kit delay on runAction completion?
|
<p>I'm building a game with Sprite Kit that implements A* Pathfinding. I'm using a grid system (blocks) that the character uses to calculate the path, it works great. My problem is the animation.</p>
<p>I'm using a NSMutableArray to hold the steps and removes a step each time the move has been completed (runAction completion). It works but the animation freezes for a microsecond between completion and the new move making it look "choppy", its not a smooth move...</p>
<p>I've tried a lot of things and the only thing that works is to change the duration to about 1.5 seconds to move 32px (its going to be a sloooooow game ;) ). When I want the duration I need (0.7) the problem is there.</p>
<p>I really hope someone can help me.</p>
<p>Here is some code:</p>
<pre><code>-(void)animateChar {
self.currentStepAction = nil;
if (self.pendingMove != nil) {
tileMap *moveTarget = pendingMove;
self.pendingMove = nil;
self.shortestPath = nil;
[self moveToward:moveTarget];
return;
}
if (self.shortestPath == nil) {
return;
}
// WE HAVE REACHED OUR BLOCK! CHECK IF ITS CLICKED OR STROLLING
if ([self.shortestPath count] == 0) {
self.shortestPath = nil;
self.moving = FALSE;
self.strolling = FALSE;
if (self.minionBlock) {
CGPoint diff = ccpSub(self.minionBlock.position, self.parentBlock.position);
if (abs(diff.x) > abs(diff.y)) {
if (diff.x > 0) { [self runAnimation:_faceRight speed:0.3]; } else { [self runAnimation:_faceLeft speed:0.3]; }
} else {
if (diff.y > 0) { [self runAnimation:_faceUp speed:0.3]; } else { [self runAnimation:_faceDown speed:0.3]; }
}
// SET TIMER FOR REMOVING THE BLOCK. EVERY 0.5 SECONDS IT REMOVES X ENDURANCE.
self.blockTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(pickBlock) userInfo:nil repeats:YES];
} else {
[self setMinionBusy:FALSE];
[self runAnimation:_waiting speed:0.3];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(selectRandBlockAndMove) userInfo:nil repeats:NO];
}
return;
}
ShortestPathStep *s = [self.shortestPath objectAtIndex:0];
// CHECK HOLE ON NEXT DOWN
tileMap *checkHole = [s.theBlock getNeighbor:1];
if ([checkHole isBlockType] == 2) { // THERE IS A HOLE, WE CANT REACH!
if ([_scene getRecentBlock] == self.minionBlock) { [_scene controlHud:1]; }
[self removeBlockBar];
[self.minionBlock setOccupied:FALSE];
self.minionBlock = nil;
self.currentStepAction = nil;
self.pendingMove = nil;
self.shortestPath = nil;
[self runAnimation:_waiting speed:0.3];
[self addBubble:1];
if (!self.stuck) {
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(selectRandBlockAndMove) userInfo:nil repeats:NO];
}
return;
}
CGPoint futurePosition = s.theBlock.position;
CGPoint currentPosition = self.parentBlock.position;
CGPoint diff = ccpSub(futurePosition, currentPosition);
if (abs(diff.x) > abs(diff.y)) {
if (diff.x > 0) { [self runAnimation:_faceRight speed:0.2]; } else { [self runAnimation:_faceLeft speed:0.2]; }
} else {
if (diff.y > 0) { [self runAnimation:_faceUp speed:0.2]; } else { [self runAnimation:_faceUp speed:0.2]; }
}
self.parentBlock = s.theBlock;
currentStepAction = [SKAction moveTo:s.theBlock.position duration:1.2];
[self runAction:currentStepAction completion:^{
[self animateChar];
}];
[self.shortestPath removeObjectAtIndex:0];
}
</code></pre>
| 3 | 1,538 |
Trouble to access attributes by using glVertexArrayAttribFormat / glVertexArrayVertexBuffer
|
<p>I have this code :</p>
<pre><code>Upp::Vector<float> verticesTriangle{
1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f,
};
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
//Setting up the VAO Attribute format
glVertexArrayAttribFormat(VAO, 0, 3, GL_FLOAT, GL_FALSE, 0); //Will be colors (R G B in float)
glVertexArrayAttribFormat(VAO, 1, 2, GL_FLOAT, GL_FALSE, 3); //Will be texture coordinates
glVertexArrayAttribFormat(VAO, 2, 3, GL_FLOAT, GL_FALSE, 5); //Normals
glVertexArrayAttribFormat(VAO, 3, 3, GL_FLOAT, GL_FALSE, 8); //Will be my position
glEnableVertexArrayAttrib(VAO, 0);
glEnableVertexArrayAttrib(VAO, 1);
glEnableVertexArrayAttrib(VAO, 2);
glEnableVertexArrayAttrib(VAO, 3);
//Generating a VBO
glGenBuffers(1, &VBOCarre);
glBindBuffer(GL_ARRAY_BUFFER, VBOCarre);
glBufferStorage(GL_ARRAY_BUFFER, sizeof(float) * verticesTriangle.GetCount(), verticesTriangle, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
//Binding the VBO to be read by VAO
glVertexArrayVertexBuffer(VAO, 0, VBOCarre, 0 * sizeof(float), 11 * sizeof(float));
glVertexArrayVertexBuffer(VAO, 1, VBOCarre, 3 * sizeof(float), 11 * sizeof(float));
glVertexArrayVertexBuffer(VAO, 2, VBOCarre, 5 * sizeof(float), 11 * sizeof(float));
glVertexArrayVertexBuffer(VAO, 3, VBOCarre, 8 * sizeof(float), 11 * sizeof(float));
//Bind VAO
glBindVertexArray(VAO);
</code></pre>
<p>I have no problem retrieving the first attribute in my shader however, when I trying to retrieve others, It dont work. To test it, I have setup an float array and a simple shader program and I try to retrieve my position to draw a triangle.
Here is how my datas are ordered :</p>
<p><a href="https://i.stack.imgur.com/OhBjo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OhBjo.png" alt="how my datas are ordered" /></a></p>
<p>Here is my vertex shader :</p>
<pre><code>#version 400
layout (location = 0) in vec3 colors;
layout (location = 1) in vec2 textCoords;
layout (location = 2) in vec3 normals;
layout (location = 3) in vec3 positions;
out vec3 fs_colors;
void main()
{
gl_Position = vec4(positions.x, positions.y, positions.z, 1.0);
// gl_Position = vec4(colors.x, colors.y, colors.z, 1.0); //This line work, proofing my
// first attribute is sended well to my shader
fs_colors = colors;
}
</code></pre>
<p><strong>The problem is, except the first attribute, all others seems to not be sent to the shader. What am I missing ?!</strong></p>
| 3 | 1,084 |
Parameters not being read even though they appear to be passed
|
<p>I'm making a form that creates more than one record for the user depending on how many items the user decides to check off in the form using checkboxes.</p>
<p>Currently, I'm running into an error where <code>param is missing or the value is empty: itemrecord</code> even though in the log, it appears that <code>params</code> are passing through:</p>
<pre><code>{"utf8"=>"✓", "authenticity_token"=>"m2NMruoFRr6lpsuVMK9UthlY0bsJsPmf1LWce2uKaH4=", ":item_name"=>["Backpack", "Water filter"], "commit"=>"Go!"}
</code></pre>
<p>Model relationship is that a <code>User has_many :inventories</code></p>
<p>Controller code:</p>
<pre><code>def create
@itemrecord = @current_user.inventories.build
items_to_be_saved = []
inventory_params.each do |i|
items_to_be_saved << ({ :signup_id => @current_user.id, :item_name => i })
end
if Inventory.create items_to_be_saved
flash[:success] = "Thanks!"
redirect_to root_path
else
render new_inventory_path
end
end
def inventory_params
params.require(:itemrecord).permit(:item_name)
end
</code></pre>
<p>View code:</p>
<pre><code> <%= form_for @itemrecord do |f| %>
<!-- In case you're wondering, the @wishlist below is basically a hash of categories of items and items. This hash is updated in the controller, and then used by multiple views to create the same table of items. -->
<% @wishlist.each do |category, list| %>
<div class="col-xs-2">
<div class="form-group box">
<h5> <%="#{category}"%> </h5>
<% list.each do |thing| %>
<%= check_box_tag ":item_name[]", "#{thing}" %>
</br>
<% end %>
</div>
</div>
<% end %>
<%= f.submit "Go!", class: "btn btn-primary btn-large btn-block" %>
</div>
<% end %>
</code></pre>
<p>By the way I also tried changing <code>:item_name</code> to <code>:item_names</code> to account for the array based on what else I read on SO, but that didn't fix it either</p>
| 3 | 1,057 |
fetching data from json and unable to display proper graph in extjs
|
<p>I am unable to display graph in extjs after fetching values from .json file.</p>
<p>Please find the attached code.</p>
<p>chart.json</p>
<pre><code> { "graphobject":
[
{ 'name': 'abc', 'data': 7 },
{ 'name': 'xyz', 'data': 5 },
{ 'name': 'mnop', 'data': 2 },
{ 'name': 'qrst', 'data':27 },
{ 'name': 'cde', 'data':20 }
]
}
</code></pre>
<p>abc.js</p>
<pre><code> Ext.require([
'Ext.data.*',
'Ext.chart.*',
'Ext.util.Point'
]);
Ext.onReady(function () {
var tore = new Ext.data.JsonStore({
url: 'chart.json',
autoLoad: false,
root: 'graphobject',
fields: ['name', 'data']
});
Ext.create('Ext.chart.Chart', {
renderTo: Ext.getBody(),
width: 500,
height: 300,
animate: true,
store: tore,
axes: [
{
type: 'Numeric',
position: 'left',
label: {
renderer: Ext.util.Format.numberRenderer('0,0')
},
title: 'Sample Values',
grid: true,
minimum: 0
},
{
type: 'Category',
position: 'bottom',
title: 'Sample Metrics'
}
],
series: [
{
type: 'line',
highlight: {
size: 7,
radius: 7
},
axis: 'left',
xField: 'name',
yField: 'data',
markerConfig: {
type: 'cross',
size: 4,
radius: 4,
'stroke-width': 0
}
},
]
});
});
</code></pre>
<p>Now i am able to get line graph,but values are not proper.</p>
<p>can you please help me to fetch proper graph in extjs.</p>
<p>Thanks in advance..</p>
| 3 | 1,719 |
Nodejs microservice to SQL Server database connection timout
|
<p>I am using <a href="https://loopback.io/doc/en/lb3/" rel="nofollow noreferrer">loopback3</a> for creating Nodejs microservice.</p>
<p>I have total 7 to 8 micro services. All the micro services connecting to different SQL Server databases running on same instance (192.168.20.25:1433). I am building docker images for the micro services and running them using Kubernetes Pods on openshift cluster.</p>
<p>All of the micro services are connecting to 192.168.20.25:1433 SQL Server database properly.</p>
<p>But one of the micro services is facing the database connection timeout issue. But same code when I run on a virtual machine using "npm start" command then it's able to connect to the same db.</p>
<p>Difference here is I am running code with docker images and kubernetes pods, it's giving DB connection timeout issue. And when I am running code without docker images and kubernetes pods as normal npm start command then it works.</p>
<p>Any idea what could be the issue? Thanks in advance for help.</p>
<p>Below is the error log:</p>
<pre><code>loopback:connector:mssql Connection error: ConnectionError: Failed to connect to 192.168.20.25:1433 in 15000ms
at Connection.<anonymous> (/home/normaluser/node_modules/mssql/lib/tedious/connection-pool.js:68:17)
at Object.onceWrapper (events.js:520:26)
at Connection.emit (events.js:400:28)
at Connection.connectTimeout (/home/normaluser/node_modules/mssql/node_modules/tedious/lib/connection.js:1195:10)
at Timeout._onTimeout (/home/normaluser/node_modules/mssql/node_modules/tedious/lib/connection.js:1157:12)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7) {
code: 'ETIMEOUT',
originalError: ConnectionError: Failed to connect to 192.168.20.25:1433 in 15000ms
at ConnectionError (/home/normaluser/node_modules/mssql/node_modules/tedious/lib/errors.js:13:12)
at Connection.connectTimeout (/home/normaluser/node_modules/mssql/node_modules/tedious/lib/connection.js:1195:54)
at Timeout._onTimeout (/home/normaluser/node_modules/mssql/node_modules/tedious/lib/connection.js:1157:12)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7) {
code: 'ETIMEOUT'
}
}
2022-06-27T05:37:41.095Z loopback:datasource Connector is initialized for dataSource DB
2022-06-27T05:37:41.095Z strong-globalize ~~~ lang = en a2487abefef4259c2131d96cdb8543b1 ["ConnectionError: Failed to connect to 192.168.20.25:1433 in 15000ms"] /home/normaluser/node_modules/strong-globalize/lib/globalize.js
Connection fails: ConnectionError: Failed to connect to 192.168.20.25:1433 in 15000ms
It will be retried for the next request.
/home/normaluser/node_modules/mssql/lib/tedious/connection-pool.js:68
err = new ConnectionError(err)
^
ConnectionError: Failed to connect to 192.168.20.25:1433 in 15000ms
at Connection.<anonymous> (/home/normaluser/node_modules/mssql/lib/tedious/connection-pool.js:68:17)
at Object.onceWrapper (events.js:520:26)
at Connection.emit (events.js:400:28)
at Connection.connectTimeout (/home/normaluser/node_modules/mssql/node_modules/tedious/lib/connection.js:1195:10)
at Timeout._onTimeout (/home/normaluser/node_modules/mssql/node_modules/tedious/lib/connection.js:1157:12)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! transaction-service@1.0.0 start: `node .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the transaction-service@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code></pre>
<p>dockerfile:</p>
<pre><code>#For Linux Instances
FROM node:14-alpine
# Create normal user
RUN adduser -D normaluser
USER normaluser
# Create app directory
WORKDIR /home/normaluser
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
# If you are building your code for production
# RUN npm install --only=production
RUN npm install
# Bundle app source
COPY . .
EXPOSE 3002
#SET ENV To Production
#ENV NODE_ENV=production
CMD [ "npm", "start" ]
</code></pre>
<p>kubernetes pod YAML file:</p>
<pre><code>
apiVersion: apps/v1
kind: Deployment
metadata:
name: xyz-transaction-dev
namespace: xyz-dev
spec:
replicas: 1
selector:
matchLabels:
name: xyz-transaction-dev
template:
metadata:
labels:
name: xyz-transaction-dev
spec:
containers:
- name: xyz-transaction-dev
image: <image registry url>:v1.63
imagePullPolicy: Always
envFrom:
- secretRef:
name: transaction-secret
- secretRef:
name: global-secret
resources:
requests:
cpu: "60m"
memory: "150Mi"
limits:
cpu: "150m"
memory: "250Mi"
ports:
- containerPort: 3002
protocal: TCP
---
apiVersion: v1
kind: Service
metadata:
name: transaction
namespace: xyz-dev
spec:
ports:
- port: 3002
name: 3002-tcp
protocal: TCP
targetPort: 3002
selector:
name: xyz-transaction-dev
</code></pre>
| 3 | 2,119 |
Executing playbooks in groupings created in hosts.yaml file
|
<p>Ansible Version: 2.8.3</p>
<p>I have the following <code>hosts.yaml</code> file for use in Ansible</p>
<p>I have applications that I want to deploy on potentially both <strong>rp_1</strong> and <strong>rp_2</strong></p>
<pre class="lang-yaml prettyprint-override"><code>---
all:
vars:
docker_network_name: devopsNet
http_protocol: http
http_host: ansiblenode01_new.example.com
http_url: "{{ http_protocol }}://{{ http_host }}:{{ http_port }}/{{ http_context }}"
hosts:
ansiblenode01_new.example.com:
ansiblenode02_new.example.com:
children:
##################################################################
rp_1:
children:
httpd:
hosts:
ansiblenode01_new.example.com:
vars:
number_of_tools: 6
outside_port: 443
jenkins:
hosts:
ansiblenode01_new.example.com:
vars:
http_port: 4444
http_context: jenkins
artifactory:
hosts:
ansiblenode01_new.example.com:
vars:
http_port: 8000
http_context: artifactory
rp_2:
children:
httpd:
hosts:
ansiblenode02_new.example.com:
vars:
number_of_tools: 4
outside_port: 7090
jenkins:
hosts:
ansiblenode02_new.example.com:
vars:
http_port: 7990
http_context: jenkins
artifactory:
hosts:
ansiblenode02_new.example.com:
vars:
http_port: 8000
http_context: artifactory
</code></pre>
<p>The following python wrapper script is calling ansible-playbook in a loop to deploy the applications</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python
import yaml
import os
import getpass
with open('hosts.yaml') as f:
var = yaml.load(f)
sudo_pass = getpass.getpass(prompt="Please enter sudo password: ")
# Running individual ansible-playbook deployment for each application listed and uncommented under 'applications' object.
for network in var['all']['children']:
for app in var['all']['children'][network]['children']:
os.system('ansible-playbook deploy.yml --extra-vars "application='+app+' ansible_sudo_password='+sudo_pass+'"')
</code></pre>
<p>The problem I recognize is that both Ansible and Python will use the hosts.yaml file, but not use it the way I thought it would as I'm not too familiar with Ansible.</p>
<p>The hosts.yaml was written in a format that is required by Ansible.</p>
<p>The Python script will open the yaml file, make a dictionary out of it, and step through the dictionary and look for the application names to pass to the command line call. The problem is then that Python only passes the name of the app as a string to the invocation of <code>ansible-playbook</code>, the dictionary structure obviously doesn't get passed, so Ansible will then open the <code>hosts.yaml</code> file as well, but all it does is step through the yaml and look for the first occurrence of the app name that was passed as an argument when <code>ansible-playbook</code> was invoked, completely disregarding the structure I've created in the yaml file.</p>
<p>So basically only the <code>rp_1</code> group in the yaml file will be executed since Ansible, I think reads through the yaml from top down and stops at the first occurrence, therefore all or parts of the <code>rp_2</code> group will never be processed by Ansible if the group contains all or some of the same apps as <code>rp_1</code>, therefore running the same deployment twice.</p>
<p>Is there a way to invoke Ansible or some ways to set the playbooks up so that Ansible will recognize that in my hosts file, I have networks (<code>rp_1</code>, <code>rp_2</code>) that I want to setup and executes the playbooks in the grouping that I've created in the yaml file?</p>
| 3 | 1,615 |
Why does my code not work when a character is in the second row of the array?
|
<p>I have some code with a method that is trying to return the opposing character label of a 2d array's position.</p>
<p>Let's suppose the array and it's labels for each position are like below:</p>
<pre><code>{{3,3,3,3}, {3,3,3,3}}
a,b,c,d e,f,g,h
</code></pre>
<p>If b is entered, f is returned. I have it working right if a, b, c, or d is entered, but it doesn't work right if e, f, g, or h is entered and I can't figure out why.</p>
<pre><code>public class ByteTest {
public static void main(String[] args) {
int[][] testArray = {{3,3,3,3}, {3,3,3,3}};
// a b c d e f g h
char slectdPit = 'e';
int total = (int)slectdPit;
int total97 = total - 97;
System.out.println(myGetOpposingPit(slectdPit, testArray));
}
public static char myGetOpposingPit(char b, int[][] ints) {
char retChar = 'z';
int retVal = 0;
int charPosi = 0;
int total97 = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < ints[0].length; j++) {
charPosi = (int)b;
total97 = charPosi - 97;
if (total97 <= ints[0].length) {
if (total97 == j) {
retVal = (charPosi + ints[0].length);
retChar = (char)retVal;
}
}
else if (total97 > ints[0].length) {
if (total97 == (j + (ints[0].length))) {
retVal = (charPosi - ints[0].length);
retChar = (char)retVal;
}
}
}
}
return retChar;
}
}
</code></pre>
<p>I've made an if statement </p>
<pre><code> else if (total97 > ints[0].length) {
if (total97 == (j + (ints[0].length))) {
retVal = (charPosi - ints[0].length);
retChar = (char)retVal;
}
</code></pre>
<p>That's supposed to get find labels that are in the second row of the array, and assign returnedChar with <code>characterPosition</code> - array row length, so if the character ran through <code>myGetOpposingPit</code> is g, it'd be <code>charPosi (103) minus ints[0].length (4), equaling 99</code>, which gets <code>ascii</code> converted into 'c'.</p>
<p>Doesn't work though, <code>z</code> gets returned. So one of my if statements isn't running or something.</p>
| 3 | 1,252 |
Jwt token always return 401 .net core 3.1 web api
|
<p>I'm new at the Jwt. I create new web api running on 3.1 version and my configuration like that ;</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mysupersecretkeytosharewithnooneandalwaysinsideapp"));
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "Management",
ValidateIssuer = true,
ValidAudience = "Management",
ValidateAudience = true,
ValidateLifetime = true,
IssuerSigningKey = symmetricKey,
ValidateIssuerSigningKey = true,
};
services.AddCors();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = tokenValidationParameters;
});
services.AddHttpContextAccessor();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(q => q.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
</code></pre>
<p>And my token generator class like that ;</p>
<pre><code> public static string GenerateToken(string jwtKey, string jwtExpireMinutes)
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier,"C280298D-D896-49E2-96AD-5C82243F9048"),
new Claim(ClaimTypes.Email,"mfa@gmail.com"),
};
var keyByte = Encoding.UTF8.GetBytes(jwtKey);
var signInKey = new SymmetricSecurityKey(keyByte);
var expireMinutes = DateTime.Now.AddMinutes(Convert.ToDouble(jwtExpireMinutes));
var token = new JwtSecurityToken(claims: claims, expires: expireMinutes, signingCredentials: new SigningCredentials(signInKey, SecurityAlgorithms.HmacSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
</code></pre>
<p>I tried on Postman and I'm getting token successfuly but with this token When I call my method it returns 401 unauthorized.</p>
<p>Controller has these attributes ;</p>
<pre><code> [ApiController]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
</code></pre>
<p>These are the results ;</p>
<p><a href="https://i.stack.imgur.com/helAF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/helAF.png" alt="Successfuly token"></a></p>
<p><a href="https://i.stack.imgur.com/HLm4G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HLm4G.png" alt="401 Unauthorized"></a></p>
| 3 | 1,618 |
PHP MS SQL - Fatal Error: Call to undefined function sqlsvr_connect()
|
<p>Good morning. I am trying to set up a php development environment but I keep running in circles chasing down answers that have not worked by searching.</p>
<p>The error I get when trying to run the test php file in Php Designer or after saving it and running it in Chrome or Firefox to connect to my local MS SQL Express db is:</p>
<blockquote>
<p>Fatal Error: Call to undefined function sqlsvr_connect()</p>
</blockquote>
<p>I am using:</p>
<ol>
<li>Xampp Control Panel V3.2.2</li>
<li>Apache 2.0 Handler</li>
<li>PHP Version 7.2.5 (x86)</li>
<li>MS SQL Express 2017 RTM</li>
<li>Php Designer 8.1.2</li>
</ol>
<p><a href="https://i.stack.imgur.com/Uk8Ma.png" rel="nofollow noreferrer">What I think are the correct MS SQL drivers for PHP</a> php_pdo_sqlsrv_72_ts_x86.dll and php_sqlsrv_72_ts_x86.dll Both are stored in C:\xampp\php\ext</p>
<p>The code I'm using in the test.php:</p>
<pre><code>$serverName = "DESKTOP-1FK6JRL\\SQLEXPRESS"; //serverName\instanceName
$connectionInfo = array( "Database"=>"testdb", "UID"=>"myusername", "PWD"=>"MyPassword");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
</code></pre>
<p>This is my Apache error log:</p>
<pre><code>[Sat Jun 02 11:00:31.829695 2018] [ssl:warn] [pid 11940:tid 672] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Jun 02 11:00:31.910495 2018] [core:warn] [pid 11940:tid 672] AH00098: pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Sat Jun 02 11:00:31.918467 2018] [ssl:warn] [pid 11940:tid 672] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Jun 02 11:00:31.965356 2018] [mpm_winnt:notice] [pid 11940:tid 672] AH00455: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.5 configured -- resuming normal operations
[Sat Jun 02 11:00:31.965356 2018] [mpm_winnt:notice] [pid 11940:tid 672] AH00456: Apache Lounge VC15 Server built: Mar 28 2018 12:12:41
[Sat Jun 02 11:00:31.966316 2018] [core:notice] [pid 11940:tid 672] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'
[Sat Jun 02 11:00:31.972327 2018] [mpm_winnt:notice] [pid 11940:tid 672] AH00418: Parent: Created child process 22396
[Sat Jun 02 11:00:32.801001 2018] [ssl:warn] [pid 22396:tid 744] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Jun 02 11:00:32.873530 2018] [ssl:warn] [pid 22396:tid 744] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Jun 02 11:00:32.921373 2018] [mpm_winnt:notice] [pid 22396:tid 744] AH00354: Child: Starting 150 worker threads.
</code></pre>
<p>Here is my php.ini with the extension_dir set to extension_dir="C:\xampp\php\ext"</p>
<pre><code>extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
;extension=ldap
;extension=mbstring
;extension=exif ; Must be after mbstring as it depends on it
;extension=mysqli
;extension=oci8_12c ; Use with Oracle Database 12c Instant Client
;extension=odbc
;extension=openssl
;extension=pdo_firebird
extension=php_pdo_sqlsrv_72_ts_x86
extension=php_sqlsrv_72_ts_x86
;extension=php_pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
;extension=pdo_pgsql
;extension=pdo_sqlite
;extension=pgsql
;extension=shmop
</code></pre>
<p>Any help that anyone can give would be GREATLY appreciated. I have tried all types of combinations to no avail.</p>
| 3 | 1,439 |
How to share an annotation across multiple elements
|
<p>I have this in my XSD (excerpt):</p>
<pre><code><xs:choice maxOccurs="unbounded" minOccurs="0">
<xs:element name="int1">
<xs:complexType>
<xs:complexContent>
<xs:extension base="baseStructMember">
<xs:attribute name="min" type="xs:byte" use="optional" />
<xs:attribute name="max" type="xs:byte" use="optional" />
<xs:attribute name="step" type="xs:byte" use="optional">
<xs:annotation>
<xs:documentation xml:lang="en">
*** Description of the step goes here. ***
</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
<xs:element name="int2">
<xs:complexType>
<xs:complexContent>
<xs:extension base="baseStructMember">
<xs:attribute name="min" type="xs:short" use="optional" />
<xs:attribute name="max" type="xs:short" use="optional" />
<xs:attribute name="step" type="xs:short" use="optional" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
<xs:element name="int4">
<xs:complexType>
<xs:complexContent>
<xs:extension base="baseStructMember">
<xs:attribute name="min" type="xs:int" use="optional" />
<xs:attribute name="max" type="xs:int" use="optional" />
<xs:attribute name="step" type="xs:int" use="optional" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
</xs:choice>
</code></pre>
<p>I want to add annotation to <code>step</code> attributes. As you see, I added it in <code>int1</code>. All <code>step</code> attributes (also in <code>int2</code>, <code>int4</code>...) are of different types, but have same meaning, so the annotation should be same.</p>
<p>Is there any way I could share one annotation across all <code>step</code> attributes?</p>
<p>Or define <code>step</code> externally, together with annotation and reuse it (like with <code>attributeGroup</code>), but allow for different attribute types?</p>
| 3 | 1,077 |
Unable to upload webdatacommons example file into OpenRDF Sesame 2.7.0 (seemingly) because of encoded Chinese characters
|
<p>I just tried uploading the example <a href="http://webdatacommons.org/samples/data/ccrdf.html-rdfa.sample.nq" rel="nofollow">webdatacommons RDF file</a> </p>
<p>Into Sesame 2.7.0 and get a message: </p>
<pre><code>"'洪雄熊' was not recognised as a language literal, and could not be verified, with language zh_tw [line 3931]"
</code></pre>
<p>I checked that line in the file and it is as follows:</p>
<pre><code><http://bearhungfactory.mysinablog.com/index.php> <http://creativecommons.org/ns#attributionName> "\u6D2A\u96C4\u718A"@zh_tw <http://bearhungfactory.mysinablog.com/index.php> .
</code></pre>
<p>I was wondering if there is a way to relax validation in Sesame so I could upload these files anyway? If not, can you please suggest if there is any other workaround to upload
webdatacommons into Sesame? Or is there a SPARQL endpoint to this data that I can use?</p>
<p>Here is the full exception:</p>
<pre><code> WARNING: org.openrdf.workbench.exceptions.BadRequestException: '洪雄熊' was not recognised as a language literal, and could not be verified, with language zh_tw [line 3931]
org.openrdf.workbench.exceptions.BadRequestException: '洪雄熊' was not recognised as a language literal, and could not be verified, with language zh_tw [line 3931]
at org.openrdf.workbench.commands.AddServlet.add(AddServlet.java:117)
at org.openrdf.workbench.commands.AddServlet.doPost(AddServlet.java:69)
at org.openrdf.workbench.base.TransformationServlet.service(TransformationServlet.java:95)
at org.openrdf.workbench.base.BaseServlet.service(BaseServlet.java:137)
at org.openrdf.workbench.proxy.ProxyRepositoryServlet.service(ProxyRepositoryServlet.java:104)
at org.openrdf.workbench.proxy.WorkbenchServlet.service(WorkbenchServlet.java:222)
at org.openrdf.workbench.proxy.WorkbenchServlet.handleRequest(WorkbenchServlet.java:151)
at org.openrdf.workbench.proxy.WorkbenchServlet.service(WorkbenchServlet.java:119)
at org.openrdf.workbench.proxy.WorkbenchGateway.service(WorkbenchGateway.java:131)
at org.openrdf.workbench.base.BaseServlet.service(BaseServlet.java:137)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.openrdf.workbench.proxy.CookieCacheControlFilter.doFilter(CookieCacheControlFilter.java:63)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.openrdf.rio.RDFParseException: '洪雄熊' was not recognised as a language literal, and could not be verified, with language zh_tw [line 3931]
at org.openrdf.http.client.SesameHTTPClient.upload(SesameHTTPClient.java:646)
at org.openrdf.http.client.SesameHTTPClient.upload(SesameHTTPClient.java:563)
at org.openrdf.repository.http.HTTPRepositoryConnection.add(HTTPRepositoryConnection.java:412)
at org.openrdf.workbench.commands.AddServlet.add(AddServlet.java:114)
... 28 more
</code></pre>
<p>I am using a "Native Java Store RDF Schema and Direct Type Hierarchy" repository on Ubuntu 12.04 LTS, 64-bit with JDK 1.6 and Tomcat 7.0.</p>
<p>I'll appreciate any help or general advise with this. Thanks.</p>
| 3 | 1,672 |
Improving graph quality while exporting in r
|
<p>I have written following code for comparing between to different variables over a period. The code works fine but only problem is when i output the file as "jpeg" the lines are not smooth and my arrow is not as smooth as i like it to be in other words the graph feels very low quality. But when i output it as "pdf" i get smooth lines and graph is of higher quality. But pdf files are high in file size and i need to insert these graphs in word file. I find it relatively easy to append jpeg into the word file. So is it possible to improve image quality while being in jpeg format. I tried using <code>res</code> argument in <code>jpeg()</code> but it doesnot output the graph as it is displayed in the rstudio.</p>
<p>I will appreciate the help. Thanks!</p>
<p>code:</p>
<pre><code>library(shape)
library(Hmisc)
### samples ######
xaxs = seq(1,30,length=30)
precip = sample(200:800, 30)
ero = sample(0:10, 30, replace = T)
#########
svpth = getwd()
nm = "try.jpeg"
jpeg(paste0(svpth,"/",nm), width=950 , height =760, quality = 200, pointsize =15)
par(mar= c(5,4,2,4), oma=c(1,1,1,1))
plot(xaxs,precip, type = "p", pch=15, col="green", ylim = c(200,1000),
xlab = "Year" , ylab = "", cex.main=1.5, cex.axis=1.5, cex.lab=1.5)
lines(xaxs, precip,lty =1, col="green")
# xtick<-seq(0,30, by=1)
# axis(side = 1, at=xtick, labels = FALSE )
minor.tick(nx=5, ny=2, tick.ratio=0.5, x.args = list(), y.args = list())
mtext("Depth (mm)", side = 2, line = 2.7, cex = 1.5)
par(new=T)
plot(xaxs, (ero * 10), ylim = c(0,max(pretty(range((ero * 10))))+20), type = "p", pch=20, cex=1.5, col="red", axes = F, xlab = "", ylab = "")
lines(xaxs, (ero * 10),lty =2, col="red")
axis(side = 4, at=pretty(range((ero * 10))), cex.axis = 1.5)
# mtext("Erosion (t/ha/yr)", side = 4, line = 2.2, cex = 1.5)
mtext(expression(paste("Erosion (t ", ha^-1, yr^-1, ")")), side = 4, line = 2.7, cex = 1.5)
legend("topleft", legend = c("Precipitation","Erosion"), lty = c(1,2), pch = c(15,20), col = c("green","red"), cex = 1.6, bty = "n")
####arrow
Arrows(7, 85, 11, 90,lwd= 1.1)
Arrows(26, 85, 21, 90, lwd= 1.1)
txt = "High erosion rates in \nwheat-planting years"
xt = 16
yt = 85
text(xt, yt, labels = txt, family="serif", cex = 1.23)
sw = strwidth(txt)+1.4
sh = strheight(txt) +6
frsz = 0.38
rect(xt - sw/2 - frsz, yt - sh/2 - frsz, xt + sw/2 + frsz, yt + sh/2 + frsz-1)
# legend(15,80, legend = c("High erosion rates in \nwheat-planting years\n"),
# xjust = 0.5, yjust = 0.5)
dev.off()
</code></pre>
| 3 | 1,223 |
Upload doesn't work using Carrierwave in Rails 5
|
<p>So I was working on my app and trying to put on an uploader feature.</p>
<p>First I generated a course uploader and allowed jpeg, jpg, png and gif. </p>
<p>Next I've added the ff code mount on my course model:</p>
<pre><code> mount_uploader :thumb_image, CoursesUploader
mount_uploader :main_image, CoursesUploader
</code></pre>
<p>Next, I place the file upload form code on my new.html.erb file:</p>
<pre><code> <div class="field">
<%= f.file_field :main_image %>
</div>
<div class="field">
<%= f.file_field :thumb_image %>
</div>
</code></pre>
<p>And when I tried to submit my form with my images uploaded it did not even show the index page instead I refresh the page and then see if it got uploaded and the form was submitted successfully but it did not. </p>
<p>I also look at the strong params on my controller and these two items are there:</p>
<pre><code> # Never trust parameters from the scary internet, only allow the white list through.
def course_params
params.require(:course).permit(:title, :price, :body, :main_image, :thumb_image)
end
</code></pre>
<p>Any idea what am I missing here?</p>
<p>Here's something I got from my terminal after submission:</p>
<pre><code>Started POST "/courses" for 127.0.0.1 at 2019-01-16 20:52:20 +0800
Processing by CoursesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wlKpv8czsuC6AZjCctxYk203wry4cb0dnOYI9IoAkzRZNV2vB4/vREU5L5u4G7vh5ZhCbHZlJ6nHPN95qO+cbA==", "course"=>{"title"=>"Goody", "price"=>"33", "main_image"=>#<ActionDispatch::Http::UploadedFile:0x007f81e52eed48 @tempfile=#<Tempfile:/var/folders/3_/8bmsd3j13bxfdl1jp7gzvvsm0000gn/T/RackMultipart20190116-2359-17w6pb.jpg>, @original_filename="61230.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"course[main_image]\"; filename=\"61230.jpg\"\r\nContent-Type: image/jpeg\r\n">, "thumb_image"=>#<ActionDispatch::Http::UploadedFile:0x007f81e52eecd0 @tempfile=#<Tempfile:/var/folders/3_/8bmsd3j13bxfdl1jp7gzvvsm0000gn/T/RackMultipart20190116-2359-2mcy4i.jpg>, @original_filename="61230.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"course[thumb_image]\"; filename=\"61230.jpg\"\r\nContent-Type: image/jpeg\r\n">, "body"=>""}, "commit"=>"Create Course"}
(0.5ms) BEGIN
↳ app/controllers/courses_controller.rb:27
Course Exists (1.5ms) SELECT 1 AS one FROM "courses" WHERE "courses"."id" IS NOT NULL AND "courses"."slug" = $1 LIMIT $2 [["slug", "goody"], ["LIMIT", 1]]
↳ app/controllers/courses_controller.rb:27
(0.6ms) ROLLBACK
↳ app/controllers/courses_controller.rb:27
Rendering courses/new.html.erb within layouts/application
Rendered courses/new.html.erb within layouts/application (12.6ms)
Rendered shared/_application_nav.html.erb (6.2ms)
Rendered shared/_application_footer.html.erb (1.3ms)
Completed 200 OK in 394ms (Views: 356.6ms | ActiveRecord: 2.6ms)
</code></pre>
<p>UPDATE: FULL MODEL CONTENT</p>
<pre><code>class Course < ApplicationRecord
include DefaultsConcern
enum status: { draft: 0, published: 1 }
validates_presence_of :title, :price, :body, :main_image, :thumb_image
mount_uploader :thumb_image, CoursesUploader
mount_uploader :main_image, CoursesUploader
extend FriendlyId
friendly_id :title, use: :slugged
end
</code></pre>
<p>FULL FORM CONTENT:</p>
<pre><code><h1>New Form</h1>
<%= form_for(@course) do |f| %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :price %>
<%= f.number_field :price %>
</div>
<div class="field">
<%= f.file_field :main_image %>
</div>
<div class="field">
<%= f.file_field :thumb_image %>
</div>
<div class="field">
<%= f.label :body %>
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
</code></pre>
| 3 | 1,730 |
How to put a thread to sleep for microseconds? (invalid implementation for sleep_for in MinGW)
|
<p>Since <code>std::chrono::sleep_for</code> accepts microseconds, I expected it to be able to sleep for microseconds with some reasonable bias (sleep <em>a little</em> longer, <em>definitely</em> not shorter).</p>
<p>However, it turned out that I was wrong and it seems to be not possible with STL.
MSVC implementation of <code>sleep_for</code> makes the thread to sleep for a few milliseconds (!!!).
MinGW implementation bluntly ignores <code>sleep_for</code> command for microseconds, 1 millisecond, and have been noticed several times to wake up spuriously (though such behavior is not specified by the standard).</p>
<p>When MinGW is told to sleep for 1 millisecond, it sleeps unreasonably longer than 1 millisecond or MSVC.</p>
<p>Here is a code snippet that I use for testing</p>
<pre><code>#include <thread>
#include <condition_variable>
#include <chrono>
#include <iostream>
#include <locale>
struct separate_thousands : std::numpunct<char>
{
char_type do_thousands_sep() const override { return ','; } // separate with commas
string_type do_grouping() const override { return "\3"; } // groups of 3 digit
};
class StopWatch
{
std::chrono::steady_clock::time_point start_;
public:
StopWatch()
: start_(std::chrono::steady_clock::now())
{}
void Reset()
{
start_ = std::chrono::steady_clock::now();
}
std::chrono::nanoseconds Result() const
{
return std::chrono::steady_clock::now() - start_;
}
template <typename MetricPrefix>
std::chrono::duration<long long, MetricPrefix> Result(MetricPrefix) const
{
return std::chrono::duration_cast<
std::chrono::duration<long long, MetricPrefix>
>(Result());
}
template <typename MetricPrefix>
operator std::chrono::duration<long long, MetricPrefix>() const
{
return Result(MetricPrefix());
}
};
template <typename DurationType>
std::chrono::nanoseconds SleepFor(DurationType duration)
{
StopWatch sw{};
std::this_thread::sleep_for(duration);
return sw;
}
template <typename DurationType>
std::chrono::nanoseconds WaitFor(DurationType duration)
{
std::mutex cvMutex{};
std::condition_variable cv{};
StopWatch sw{};
std::unique_lock<std::mutex> ul{cvMutex};
cv.wait_for(ul, std::chrono::microseconds(1));
return sw;
}
int main()
{
std::cout.imbue(std::locale(std::cin.getloc(), new separate_thousands()));
StopWatch sw{};
std::chrono::nanoseconds durationNanosec = sw;
std::cout << "Duration between 2 \"std::chrono::steady_clock::now()\" calls: " <<
durationNanosec.count() << " nanoseconds" << std::endl;
std::cout << "Duration of sleep_for 1 microsecond "
<< SleepFor(std::chrono::microseconds(1)).count()
<< " nanoseconds" << std::endl;
std::cout << "Duration of sleep_for 5 microseconds "
<< SleepFor(std::chrono::microseconds(5)).count()
<< " nanoseconds" << std::endl;
std::cout << "Duration of sleep_for 100 microseconds "
<< SleepFor(std::chrono::microseconds(100)).count()
<< " nanoseconds" << std::endl;
std::cout << "Duration of sleep_for 500 microseconds "
<< SleepFor(std::chrono::microseconds(500)).count()
<< " nanoseconds" << std::endl;
std::cout << "Duration of sleep_for 1 milliseconds "
<< SleepFor(std::chrono::milliseconds(1)).count()
<< " nanoseconds" << std::endl;
// this executes far longer than 1 second on MinGW!
for (size_t i = 0; i != 1000; ++i)
{
std::chrono::nanoseconds duration = SleepFor(std::chrono::milliseconds(1));
if (duration < std::chrono::milliseconds(1))
{
std::cout << "Slept less than 1ms : " << duration.count() << " nanoseconds" << std::endl;
break;
}
}
// this executes far longer than 2 seconds on MinGW!
for (size_t i = 0; i != 1000; ++i)
{
std::chrono::nanoseconds duration = SleepFor(std::chrono::milliseconds(2));
if (duration < std::chrono::milliseconds(2))
{
std::cout << "Slept less than 2ms : " << duration.count() << " nanoseconds" << std::endl;
break;
}
}
std::cout << "Duration of sleep_for 10 milliseconds "
<< SleepFor(std::chrono::milliseconds(10)).count()
<< " nanoseconds" << std::endl;
std::cout << "Duration of condition_variable::wait_for 1 microsecond "
<< WaitFor(std::chrono::microseconds(1)).count()
<< " nanoseconds" << std::endl;
std::cout << "Duration of condition_variable::wait_for 5 microseconds "
<< WaitFor(std::chrono::microseconds(5)).count()
<< " nanoseconds" << std::endl;
std::cout << "Duration of condition_variable::wait_for 1 millisecond "
<< WaitFor(std::chrono::milliseconds(1)).count()
<< " nanoseconds" << std::endl;
std::cout << "Duration of condition_variable::wait_for 10 milliseconds "
<< WaitFor(std::chrono::milliseconds(10)).count()
<< " nanoseconds" << std::endl;
return 0;
}
</code></pre>
<p>With MinGW the output may be something like this:</p>
<pre><code>Duration between 2 "std::chrono::steady_clock::now()" calls: 100 nanoseconds
Duration of sleep_for 1 microsecond 700 nanoseconds
Duration of sleep_for 5 microseconds 300 nanoseconds
Duration of sleep_for 100 microseconds 400 nanoseconds
Duration of sleep_for 500 microseconds 200 nanoseconds
Duration of sleep_for 1 milliseconds 7,956,100 nanoseconds
Slept less than 2ms : 1,839,900 nanoseconds
Duration of sleep_for 10 milliseconds 20,629,600 nanoseconds
Duration of condition_variable::wait_for 1 microsecond 6,402,400 nanoseconds
Duration of condition_variable::wait_for 5 microseconds 14,985,800 nanoseconds
Duration of condition_variable::wait_for 1 millisecond 13,803,400 nanoseconds
Duration of condition_variable::wait_for 10 milliseconds 14,900,900 nanoseconds
</code></pre>
<p>With MSVC:</p>
<pre><code>Duration between 2 "std::chrono::steady_clock::now()" calls: 300 nanoseconds
Duration of sleep_for 1 microsecond 13,200 nanoseconds
Duration of sleep_for 5 microseconds 1,694,100 nanoseconds
Duration of sleep_for 100 microseconds 1,572,900 nanoseconds
Duration of sleep_for 500 microseconds 1,694,300 nanoseconds
Duration of sleep_for 1 milliseconds 1,645,000 nanoseconds
Duration of sleep_for 10 milliseconds 10,976,100 nanoseconds
Duration of condition_variable::wait_for 1 microsecond 46,100 nanoseconds
Duration of condition_variable::wait_for 5 microseconds 21,300 nanoseconds
Duration of condition_variable::wait_for 1 millisecond 28,700 nanoseconds
Duration of condition_variable::wait_for 10 milliseconds 22,500 nanoseconds
</code></pre>
<p>I am aware that I can use busy waiting to wait for nanoseconds, but this is a no go, since I do not want to waste CPU resources.
Moreover, MinGW implementation seems to provide unpredictable results.</p>
<ol>
<li>Is there a way to sleep for microseconds?</li>
<li>Is there a good crossplatform alternative for STL threads that implements sleeping for microseconds?</li>
</ol>
| 3 | 3,190 |
Transforming an Image to move diagnally
|
<pre><code>public void draw(Graphics g, Graphics g2d, double theta, int NEWY){
g.setColor(Color.orange);
int drawLocationX = character.x;
int drawLocationY = character.y-47;
double rotationRequired = Math.toRadians (theta);
double locationX = this.getWidth()/2;
double locationY = this.getHeight()/2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
g2d.drawImage(op.filter(image, null), drawLocationX, NEWY, null);
}
public int getHeightWorld(int x){
//meant to find height of land at specified location
int highest = 0;
int checked = 0;
for(int c = panel.HEIGHT-1; c >= 0; c--){
if(this.inColRange(x)&& this.inRowRange(c))
if(LandList[c][x] == 2){
highest = c;
checked++;
}
}
return (1000 - highest);
}
public double getAngleWorldT1(){
//meant to find angle tank needs to be rotated at
int g = this.getHeightWorld(tank1.getNEWX());
int h = this.getHeightWorld((tank1.getWidth()+ tank1.getNEWX()));
double trythis = this.NewEquation();
int newg = tank1.getWidth()+ tank1.getNEWX();
int newh = tank2.getWidth()+ tank2.getNEWX();
double newery = (trythis*newg);
double newery2 = (trythis*tank1.getNEWX());
double newval = newery - newery2;
double u = 5;
double width = tank1.getWidth();
if(Math.abs(h-g) > tank1.getWidth()){
u = width/(g-h);
}
else{
u = (g-h)/width;
}
double p = 57.6846779*Math.asin(Math.toRadians(u));
return p;
}
public double NewEquation(){
int dividethis = 0;
int subtractthis = 0;
int numnegative = 0;
for(int what = 0; what < tank1.getWidth(); what++){
if(Math.abs(this.getHeightWorld(what)-this.getHeightWorld(what-1)) < 2){
dividethis += this.getHeightWorld(what);
if(this.getHeightWorld(what)-this.getHeightWorld(what-1) < 0){
numnegative++;
}
}
else{
subtractthis++;
}
}
dividethis = dividethis/(tank1.getWidth()-subtractthis);
if((numnegative - tank1.getWidth()) > tank1.getWidth()/2){
dividethis = dividethis*-1;
}
return dividethis;
}
public void draw(Graphics g) {
//MOVE TO DIFF METHOD
int newy = this.getHeightWorld(tank1.getNEWX()) - tank1.getHeight();
int newy2 = this.getHeightWorld(tank2.getNEWX()) - tank2.getHeight();
if( LandList[newy][tank1.getNEWX()] == 2){
while (LandList[newy][tank1.getNEWX()] == 2){
newy--;
// System.out.println("FIRST HERE");
// System.out.println(newy);
}
// System.out.println("FIRST");
}
if( LandList[newy+1][tank1.getNEWX()] != 2){
while (LandList[newy+1][tank1.getNEWX()] != 2){
newy++;
// System.out.println("SECOND HERE");
}
// System.out.println("SECOND");
}
//System.out.println("YESSSSS" +Math.toDegrees(this.getAngleWorldT1()) );
tank1.draw(g, g, Math.toDegrees(this.getAngleWorldT1()), newy - tank1.getHeight()-50);
tank2.draw(g, g, Math.toDegrees(this.getAngleWorldT2()), newy2 - tank2.getHeight());
// System.out.println("2");
for(int x = 0; x < platforms.size(); x++){
platforms.get(x).draw(g);
}
}
}
</code></pre>
<p>(Sorry for the messy code.)</p>
<p>These are two classes I am using to design a tank shooter game. In this portion, I am attempting to make the image rotate according to the land it is over(to appear traveling uphill or downhill) and I don't want any piece inside of the land. "LandList" is a 2D array that has a value of 2 if there is land and 1 if there is no land. Two issues is A) rotating at incorrect heights and not rotating at all points
B)Image cuts off at a certain height</p>
<p>Thank you for your help.</p>
<p>BOTH CLASSES IN FULL</p>
<pre><code>public class World {
Land[][] land;
List<Land> platforms = new ArrayList<Land>();
private GraphicsPanel panel;
int[][] LandList = new int[800][1500];
private int delay = 30;
private Timer timer;
private Random r;
Tank tank1;
Tank tank2;
public World(GraphicsPanel marioPanel) {
panel = marioPanel;
land = new Land[panel.WIDTH][panel.HEIGHT-500-3];
setUpWorld();
setUpTimer();
}
private void setUpWorld() {
for(int r = 0; r < panel.WIDTH; r++){
for(int c = 0; c < panel.HEIGHT; c++){
LandList[c][r] = 1;
}
}
//tank not displaying
//a lot of stuff copied over
tank1 = new Tank(25,442,100,60,1);
tank2 = new Tank(700,442,100,60,2);
r = new Random();
int w = 0;
int n = 0;
for(int x = 0; x < panel.WIDTH; x+=5){
if(x > 0 && x < panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(x+r) && inColRange(y+c))
LandList[y+r][x+c] = 2;
}
}
}
}
if(x > panel.WIDTH/6 && x < 2*panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500+ 4*w; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
}
}
}
w--;
}
if(x > 2*panel.WIDTH/6 && x < 3*panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500+ 4*w; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
}
}
}
w++;
}
if(x > 3*panel.WIDTH/6 && x < 4*panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500+ 4*n; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
}
}
}
n--;
}
if(x > 4*panel.WIDTH/6 && x < 5*panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500+ 4*n; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
}
}
}
n++;
}
if(x > 5*panel.WIDTH/6){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
// System.out.println(LandList[x+r][y+c]);
}
}
}
}
// else{
// for(int y = 500; y < panel.HEIGHT; y+=5){
// Land creating = new Land(x, y, 5, 5);
// platforms.add(creating);
// }
//
// }
}
for(int r = 0; r < panel.WIDTH; r++){
for(int c = 0; c < panel.HEIGHT; c++){
//System.out.println(LandList[r][c]);
}
}
for(int checked = 0; checked < panel.WIDTH; checked++){
System.out.println(this.getHeightWorld(checked));
}
// System.out.println(LandList);
}
private boolean inColRange(int i) {
// TODO Auto-generated method stub
return i>=0 && i<LandList[0].length;
}
private boolean inRowRange(int i) {
// TODO Auto-generated method stub
return i>=0 && i<LandList.length;
}
private void setUpTimer() {
timer = new Timer(delay, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// what should happen each time the timer goes off?
panel.repaint();
moveStuff();
checkHitBoxes();
//System.out.println(mario.getY());
}
});
timer.start();
}
protected void checkHitBoxes() {
}
protected void moveStuff() {
tank1.move();
panel.repaint();
}
public int getHeightWorld(int x){
//meant to find height of land at specified location
int highest = 0;
int checked = 0;
for(int c = panel.HEIGHT-1; c >= 0; c--){
if(this.inColRange(x)&& this.inRowRange(c))
if(LandList[c][x] == 2){
highest = c;
checked++;
}
}
return (1000 - highest);
}
public double getAngleWorldT1(){
//meant to find angle tank needs to be rotated at
int g = this.getHeightWorld(tank1.getNEWX());
int h = this.getHeightWorld((tank1.getWidth()+ tank1.getNEWX()));
double trythis = this.NewEquation();
int newg = tank1.getWidth()+ tank1.getNEWX();
int newh = tank2.getWidth()+ tank2.getNEWX();
double newery = (trythis*newg);
double newery2 = (trythis*tank1.getNEWX());
double newval = newery - newery2;
double u = 5;
double width = tank1.getWidth();
if(Math.abs(h-g) > tank1.getWidth()){
u = width/(g-h);
}
else{
u = (g-h)/width;
}
double p = 57.6846779*Math.asin(Math.toRadians(u));
return p;
}
public double getAngleWorldT2(){
int a = this.getHeightWorld(tank2.getNEWX());
int s = this.getHeightWorld((tank2.getWidth() + tank2.getNEWX() + 100) );
// a = 100;
// s = 700;
int o = (a-s)/tank2.getWidth();
//System.out.println(o);
double p = -57.6846779*(Math.asin(Math.toRadians(o)));
//System.out.println(p);
return p;
}
public double NewEquation(){
int dividethis = 0;
int subtractthis = 0;
int numnegative = 0;
for(int what = 0; what < tank1.getWidth(); what++){
if(Math.abs(this.getHeightWorld(what)-this.getHeightWorld(what-1)) < 2){
dividethis += this.getHeightWorld(what);
if(this.getHeightWorld(what)-this.getHeightWorld(what-1) < 0){
numnegative++;
}
}
else{
subtractthis++;
}
}
dividethis = dividethis/(tank1.getWidth()-subtractthis);
if((numnegative - tank1.getWidth()) > tank1.getWidth()/2){
dividethis = dividethis*-1;
}
return dividethis;
}
public void draw(Graphics g) {
//MOVE TO DIFF METHOD
int newy = this.getHeightWorld(tank1.getNEWX()) - tank1.getHeight();
int newy2 = this.getHeightWorld(tank2.getNEWX()) - tank2.getHeight();
if( LandList[newy][tank1.getNEWX()] == 2){
while (LandList[newy][tank1.getNEWX()] == 2){
newy--;
// System.out.println("FIRST HERE");
// System.out.println(newy);
}
// System.out.println("FIRST");
}
if( LandList[newy+1][tank1.getNEWX()] != 2){
while (LandList[newy+1][tank1.getNEWX()] != 2){
newy++;
// System.out.println("SECOND HERE");
}
// System.out.println("SECOND");
}
//System.out.println("YESSSSS" +Math.toDegrees(this.getAngleWorldT1()) );
tank1.draw(g, g, Math.toDegrees(this.getAngleWorldT1()), newy - tank1.getHeight()-50);
tank2.draw(g, g, Math.toDegrees(this.getAngleWorldT2()), newy2 - tank2.getHeight());
// System.out.println("2");
for(int x = 0; x < platforms.size(); x++){
platforms.get(x).draw(g);
}
}
}
public class Tank extends Moveable{
private boolean moveRight,moveLeft;
private String direction = "NONE";
private int dx =5;
//graphics
BufferedImage image = null;
private URL file;
private Rectangle character;
private Rectangle hitBox;
JLabel label = new JLabel();
private int NEWX;
public Tank(int x, int y, int w, int h, int color){
character = new Rectangle(x,y,w,h);
this.create(null,x,y,w,h);
NEWX = character.x;
BufferedImage img =null;
if(color == 1){
// file= getClass().getResource("pictures\\green_tank1");
try {
img = ImageIO.read(new File("green_tank1.png"));
image = img;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
// file = getClass().getResource("pictures\\blue_tank1");
try {
img = ImageIO.read(new File("blue_tank1.png"));
image = img;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void draw(Graphics g, Graphics g2d, double theta, int NEWY){
g.setColor(Color.orange);
int drawLocationX = character.x;
int drawLocationY = character.y-47;
double rotationRequired = Math.toRadians (theta);
double locationX = this.getWidth()/2;
double locationY = this.getHeight()/2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
g2d.drawImage(op.filter(image, null), drawLocationX, NEWY, null);
//System.out.println("This is new X " + NEWX);
// label.setVisible(true);
// label.isOpaque();
// label.setBounds(character.x, character.y, character.width, character.height);
// label.repaint();
//g.drawImage(image, 0, 0, null);
// int centerx = character.x + character.width/2;
// int centery = character.y + character.height/2;
//
// int point1 = (int) (centerx + (character.width/2)*Math.cos(Math.toRadians(theta)) - (character.height/2)* Math.sin(Math.toRadians(theta)));
// int point2 = (int) (centery + (character.height/2)*Math.cos(Math.toRadians(theta))+(character.width/2)*Math.sin(Math.toRadians(theta)));
// int point3 =(int) (centerx - (character.width/2)*Math.cos(Math.toRadians(theta)) + (character.height/2)* Math.sin(Math.toRadians(theta)));
// int point4 = (int) (centery - (character.height/2)*Math.cos(Math.toRadians(theta))-(character.width/2)*Math.sin(Math.toRadians(theta)));
// //System.out.println(theta);
// g.drawImage(image, point1,point2,point3,point4, null);
//// System.out.println("3");
// Rotation information
// AffineTransform tx = AffineTransform.getRotateInstance(Math.toRadians (theta), character.x, character.y);
// AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
//
// // Drawing the rotated image at the required drawing locations
// g.drawImage(op.filter((BufferedImage) image, null), character.x, character.y, null);
// System.out.println(this.getX());
// System.out.println(this.getY());
// System.out.println(this.getWidth());
// System.out.println(this.getHeight());
// g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
// this.setBounds(this.getX(), this.getY(), this.getWidth(), this.getHeight());
//
}
public Rectangle getRect(){
return this.character;
}
public void move(){
if(moveLeft == true){
character.setBounds(character.x -2, character.y, character.width, character.height);
character.x = character.x -2;
NEWX += -2;
}
if(moveRight == true){
character.setBounds(character.x +2, character.y, character.width, character.height);
character.x = character.x +2;
NEWX += 2;
}
}
public void setDirection(String s){
this.direction = s;
String x = s.toUpperCase().substring(0, 1);
if(x.equals("L")){
//System.out.println(x);
moveLeft = true;
moveRight = false;
}
if(x.equals("R")){
moveRight = true;
moveLeft = false;
// System.out.println("im here");
}
else if(x.equals("N")){
moveRight = false;
moveLeft =false;
// System.out.println("I Got Here #2");
}
}
public String getDirection(){
return this.direction;
}
public int getNEWX(){
return this.NEWX;
}
}
</code></pre>
| 3 | 10,227 |
Action Bar Background Not Changing
|
<p>I have went on android and followed their instructions to style the Action Bar and it is not working. The app keeps stopping. I can see the changed color briefly as the message is shown. I have a note 2 with 4.4.2.. Here are my </p>
<p>styles.` </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActionBarTheme"
parent="@android:style/Theme.Holo.Light.DarkActionBar">
<item name="android:actionBarStyle">@style/MyActionBar</item>
</style>
<!-- ActionBar styles -->
<style name="MyActionBar"
parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
<item name="android:background">#F00</item>
</style>
</resources>`
</code></pre>
<p>manifest</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="funnestgames.actionbar" >
<application
android:theme="@style/CustomActionBarTheme"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>and my logcat.</p>
<pre><code> 5-29 20:35:33.541 838-838/funnestgames.actionbar E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: funnestgames.actionbar, PID: 838
java.lang.RuntimeException: Unable to start activity ComponentInfo{funnestgames.actionbar/funnestgames.actionbar.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:122)
at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:59)
at funnestgames.actionbar.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:5451)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
| 3 | 1,625 |
Setup Fedena on windows 8
|
<p>I am trying to setup Fedena project on windows 8. I have followed steps mentioned in official website. <a href="http://www.projectfedena.org/install" rel="nofollow">http://www.projectfedena.org/install</a> . But while creating database it throws an error.
Step is <code>Run the command "rake db:create". This will create the required database.</code>
Error facing :
C:\fedena>rake db:create --trace
(in C:/fedena)
rake aborted!
uninitialized constant ActiveSupport::Dependencies::Mutex
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2503:in `const_missing'</p>
<pre><code>C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/depende
ncies.rb:55
C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original
_require'
C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support.rb:56
C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original
_require'
C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
C:/Ruby187/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/misc.rake:18
C:/Ruby187/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:4:in `load'
C:/Ruby187/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:4
C:/Ruby187/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:4:in `each'
C:/Ruby187/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:4
C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original
_require'
C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
C:/fedena/Rakefile:10
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2383:in `load'
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2383:in `raw_load_rakef
ile'
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2017:in `load_rakefile'
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_excep
tion_handling'
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2016:in `load_rakefile'
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2000:in `run'
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_excep
tion_handling'
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
C:/Ruby187/lib/ruby/gems/1.8/gems/rake-0.8.7/bin/rake:31
C:/Ruby187/bin/rake:23:in `load'
C:/Ruby187/bin/rake:23
</code></pre>
| 3 | 1,158 |
Most efficient way to re-order my database table and display to web
|
<p>I'm new to MySQL, Just read the section of my book explaining it and now at the point where I'm applying it to the website I'm building.</p>
<p>I have the two following tables in my database:</p>
<pre><code>Table Name: Transactions
+------------------+------------+-----------+--------+
| description | date | category | amount |
+------------------+------------+-----------+--------+
| Internet | 2013-01-04 | Bills | $50.00 |
+------------------+------------+-----------+--------+
| Giant Eagle Trip | 2013-10-04 | Groceries | $30.00 |
+------------------+------------+-----------+--------+
| Car Insurance | 2013-01-04 | Bills | $90.00 |
+------------------+------------+-----------+--------+
| Starbucks | 2013-09-04 | Coffee | $5.00 |
+------------------+------------+-----------+--------+
| Giant Eagle Trip | 2013-11-04 | Groceries | $15.00 |
+------------------+------------+-----------+--------+
Table Name: Categories
+------+-----------+
| rank | Name |
+------+-----------+
| 1 | Bills |
+------+-----------+
| 2 | Groceries |
+------+-----------+
| 3 | Coffee |
+------+-----------+
</code></pre>
<p>On My website I want to take that transaction table and order it by category column. The trick is I don't want it ordered alphabetically, I want it ordered in the same order as the Categories table. The final result I have displayed below:</p>
<pre><code>+------------------+------------+-----------+--------+
| description | date | category | amount |
+------------------+------------+-----------+--------+
| Internet | 2013-01-04 | Bills | $50.00 |
+------------------+------------+-----------+--------+
| Car Insurance | 2013-01-04 | Bills | $90.00 |
+------------------+------------+-----------+--------+
| Giant Eagle Trip | 2013-10-04 | Groceries | $30.00 |
+------------------+------------+-----------+--------+
| Giant Eagle Trip | 2013-11-04 | Groceries | $15.00 |
+------------------+------------+-----------+--------+
| Starbucks | 2013-09-04 | Coffee | $5.00 |
+------------------+------------+-----------+--------+
</code></pre>
<p>I have thought of two ways to do this and they are as follows:</p>
<pre><code>//Option A: using arrays
//Get categories in correct order
$query = "select name
from Categories
order by rank";
$result = $db->query($query);
$numOfCategories = $result->num_rows;
for($i=0; $i<$numOfCategories; $i++) {
$row = $result->fetch_assoc();
$category[$i] = $row['name'];
}
//Get transactions and put in correct order
$query = "select *
from Transactions";
$result = $db->query($query);
$numOfTransactions = $result->num_rows;
for($i=0; $i<$numOfTransactions; $i++) {
$row = $result->fetch_assoc();
for($j=0; $j<$numOfCategories; $j++) {
if ($category[$j] == $row['category']) {
$tableRows[$j][] = $row;
}
}
}
//Display Table
echo "<table>\n";
for($i=0; $i<count($tableRows); $i++) {
for($j=0; $j<count($tableRows[$i]); $j++) {
echo " <tr>\n";
echo " <td>".$tableRows[$i][$j]['description']."</td>\n";
echo " <td>".$tableRows[$i][$j]['date']."</td>\n";
echo " <td>".$tableRows[$i][$j]['category']."</td>\n";
echo " <td>".$tableRows[$i][$j]['amount']."</td>\n";
echo " </tr>\n";
}
}
echo "</table><br><br>\n";
//Option B: using where in select query
//Get categories in correct order
$query = "select name
from Categories
order by rank";
$result = $db->query($query);
$numOfCategories = $result->num_rows;
for($i=0; $i<$numOfCategories; $i++) {
$row = $result->fetch_assoc();
$category[$i] = $row['name'];
}
//Get transactions and display table
echo "<table>\n";
for($i=0; $i<$numOfCategories; $i++) {
$query = "select *
from Transactions
where category = '".$category[$i]."'";
$result = $db->query($query);
for($j=0; $j<$result->num_rows; $j++) {
$row = $result->fetch_assoc();
echo " <tr>\n";
echo " <td>".$row['description']."</td>\n";
echo " <td>".$row['date']."</td>\n";
echo " <td>".$row['category']."</td>\n";
echo " <td>".$row['amount']."</td>\n";
echo " </tr>\n";
}
}
echo "</table><br><br>\n";
</code></pre>
<p>Which way is better and why, or is there another way that is even better than the ways (maybe using index feature in MySQL that my book didn't explain in much detail and/or using prepared statements that my book also didn't explain in much detail). </p>
| 3 | 2,114 |
Generic expression for EF Core 3.1 filtering throws exception on .Any(...)
|
<p>I try to create a generic way of getting data via EF Core 3.1 with the same filtering of different children. For this, I try to extract the searched expression inside of Any(...).</p>
<pre><code>public Expression<Func<PraeparatUpdateEntity, bool>> IsToApprovePackungUpdates_Working()
{
return entity => entity.PackungUpdates.Any(e => !e.IsImported
&& e.UpdateState != EntityUpdateState.Accepted
&& e.UpdateType != EntityUpdateType.Unchanged);
}
public Expression<Func<PraeparatUpdateEntity, bool>> IsToApprovePackungUpdates_NotWorking()
{
var func = new Func<PackungUpdateEntity, bool>(e => !e.IsImported
&& e.UpdateState != EntityUpdateState.Accepted
&& e.UpdateType != EntityUpdateType.Unchanged);
return entity => entity.PackungUpdates.Any(func);
}
public new async Task<ICollection<PraeparatUpdateEntity>> GetToApproveAsync(bool trackChanges = false)
{
var query = Set.Include(praeparatUpdateEntity => praeparatUpdateEntity.PackungUpdates)
.Where(IsToApprovePackungUpdates_NotWorking());
if (!trackChanges)
{
query = query.AsNoTracking();
}
return await query.ToListAsync();
}
</code></pre>
<p>The first version is working.
The second one fails with errormessage:</p>
<pre><code>System.ArgumentException : Expression of type 'System.Func`2[MyProject.Data.Common.Entities.Update.PackungUpdateEntity,System.Boolean]' cannot be used for parameter of type 'System.Linq.Expressions.Expression`1[System.Func`2[MyProject.Data.Common.Entities.Update.PackungUpdateEntity,System.Boolean]]' of method 'Boolean Any[PackungUpdateEntity](System.Linq.IQueryable`1[MyProject.Data.Common.Entities.Update.PackungUpdateEntity], System.Linq.Expressions.Expression`1[System.Func`2[MyProject.Data.Common.Entities.Update.PackungUpdateEntity,System.Boolean]])' (Parameter 'arg1')
at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression arg0, Expression arg1)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
at Microsoft.EntityFrameworkCore.Query.Internal.EnumerableToQueryableMethodConvertingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at System.Linq.Expressions.ExpressionVisitor.VisitLambda[T](Expression`1 node)
at System.Linq.Expressions.Expression`1.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Linq.Expressions.UnaryExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.Process(Expression query)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at MyProject.Data.Repositories.PraeparatUpdateRepository.GetToApproveAsync(Boolean trackChanges) in C:\git\MyProject\Source\MyProject.Data\Repositories\PraeparatUpdateRepository.cs:line 156
at MyProject.Data.Tests.Integration.RepositoryNavigationPropertyLoadingTests.GetAllPraeparatUpdates_WhereToApprove_WithNavigationProperties_OK_Test() in C:\git\MyProject\Source\MyProject.Data.Tests.Integration\RepositoryNavigationPropertyLoadingTests.cs:line 328
--- End of stack trace from previous location where exception was thrown ---
</code></pre>
<h2>******** UPDATE ********</h2>
<p>If I add AsQueryable() to my IEnumerable database children I can add my Expressions like that:</p>
<pre><code>var query = Set.Include(praeparatUpdateEntity => praeparatUpdateEntity.PackungUpdates)
.Include(praeparatUpdateEntity => praeparatUpdateEntity.SequenzUpdates)
.ThenInclude(sequenzUpdateEntity => sequenzUpdateEntity.ApplikationsartUpdates)
.Include(praeparatUpdateEntity => praeparatUpdateEntity.SequenzUpdates)
.ThenInclude(sequenzUpdateEntity => sequenzUpdateEntity.DeklarationUpdates)
.Where(IsToApprove<PraeparatUpdateEntity>()
.OrElse(entity => entity.PackungUpdates.AsQueryable().Any(IsToApprove<PackungUpdateEntity>()))
.OrElse(entity => entity.SequenzUpdates.AsQueryable().Any(IsToApprove<SequenzUpdateEntity>()))
.OrElse(entity => entity.SequenzUpdates.SelectMany(sequenzUpdateEntity => sequenzUpdateEntity.ApplikationsartUpdates).AsQueryable()
.Any(IsToApprove<ApplikationsartUpdateEntity>()))
.OrElse(entity => entity.SequenzUpdates.SelectMany(sequenzUpdateEntity => sequenzUpdateEntity.DeklarationUpdates).AsQueryable()
.Any(IsToApprove<DeklarationUpdateEntity>())));
</code></pre>
<p>and my generic Expression:</p>
<pre><code>public Expression<Func<T, bool>> IsToApprove<T>() where T : class, IUpdateEntity
{
return entity => !entity.IsImported && entity.UpdateState != EntityUpdateState.Accepted
&& entity.UpdateType != EntityUpdateType.Unchanged;
}
</code></pre>
<p>which seems at the moment to work... Tests in progress</p>
| 3 | 2,367 |
My app keeps saying "unfortunately it has stopped". I don't know why it is crashing
|
<p>In my activity, the user can input numbers into a EditViews, then click a button to calculate, the result is displayed below. However, if a user edits an EditView, clicks calculate, then goes back to edit an EditView again, the app crashes when the user clicks calculate to recalculate a new total.</p>
<p>Full log:</p>
<pre><code>06-24 09:14:06.025 2618-2637/washingtondeli.groupboxlunchesestimateandordering D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 06-24 09:14:06.035 2618: 2618 D/ ]
HostConnection::get() New Host Connection established 0xaac28fe0, tid 2618
06-24 09:14:06.109 2618-2637/washingtondeli.groupboxlunchesestimateandordering I/OpenGLRenderer: Initialized EGL, version 1.4
06-24 09:14:10.220 2618-2637/washingtondeli.groupboxlunchesestimateandordering E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae6cc2a0
06-24 09:14:10.226 2618-2637/washingtondeli.groupboxlunchesestimateandordering D/OpenGLRenderer: endAllStagingAnimators on 0xb2a8d580 (RippleDrawable) with handle 0xae452850
06-24 09:14:13.718 2618-2618/washingtondeli.groupboxlunchesestimateandordering W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=304.2444, y[0]=1010.4492, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=20361, downTime=16521, deviceId=0, source=0x1002 }
06-24 09:14:13.718 2618-2618/washingtondeli.groupboxlunchesestimateandordering W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=304.2444, y[0]=1010.4492, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=20361, downTime=16521, deviceId=0, source=0x1002 }
06-24 09:14:13.718 2618-2618/washingtondeli.groupboxlunchesestimateandordering W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=304.2444, y[0]=1010.4492, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=20361, downTime=16521, deviceId=0, source=0x1002 }
06-24 09:14:13.718 2618-2618/washingtondeli.groupboxlunchesestimateandordering W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=304.2444, y[0]=1010.4492, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=20361, downTime=16521, deviceId=0, source=0x1002 }
06-24 09:14:37.797 2618-2618/washingtondeli.groupboxlunchesestimateandordering D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-24 09:14:37.797 2618-2618/washingtondeli.groupboxlunchesestimateandordering E/AndroidRuntime: FATAL EXCEPTION: main
Process: washingtondeli.groupboxlunchesestimateandordering, PID: 2618
java.lang.NumberFormatException: Invalid int: "$19.00"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:410)
at java.lang.Integer.parseInt(Integer.java:367)
at java.lang.Integer.parseInt(Integer.java:334)
at washingtondeli.groupboxlunchesestimateandordering.CapitolhillActivity.calculate2(CapitolhillActivity.java:165)
at washingtondeli.groupboxlunchesestimateandordering.CapitolhillActivity$2.onClick(CapitolhillActivity.java:131)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code></pre>
| 3 | 3,456 |
JavaScript Calculator not displaying total
|
<p>When I click the calculate button, the total doesn't display and I don't know why. It's supposed to add up all the quantity ticket fields and display the total amount. Instead nothing happens when I click the button "Calculate". Any ideas?
JavsScript</p>
<pre><code>// JavaScript Document
$(document).ready(function () {
$('#logo1').animate({
marginLeft: "350px"
}, 2000);
});
function displayTotal(){
var beforenoonprice = 6.00; // CHANGE THE PRICE OF THE BEFORE NOON TICKET
var matineeprice = 8.50; // CHANGE THE PRICE OF THE MATINEE TICKET
var seniorprice = 9.50; // CHANGE THE PRICE OF THE SENIOR TICKET
var militaryprice = 9.00; // CHANGE THE PRICE OF THE MILITARY TICKET
var studentdayprice = 7.50; // CHANGE THE PRICE OF THE STUDENT DAY TICKET
var seniordayprice = 6.00; // CHANGE THE PRICE OF THE SENIOR DAY TICKET
var adultprice = 10.50; // CHANGE THE PRICE OF THE ADULT TICKET
var childprice = 7.50; // CHANGE THE PRICE OF THE CHILD TICKET
var threeDprice = 3.50; // CHANGE THE PRICE OF THE REGULAR 3D PRICE
var imaxPrice = 4.50; // CHANGE THE PRICE OF THE IMAX TICKET
var imax3dPrice = 5.50; // CHANGE THE PRICE OF THE IMAX 3D TICKET
//PRICE CHANGE EDIT ENDS HERE
var beforenoon = Number(document.getElementById('beforeNoon').value) || 0;
var beforenooncost = beforenoon * beforenoonprice;
var matinee = Number(document.getElementById('matinee').value) || 0;
var matineecost = matinee * matineeprice;
var senior = Number(document.getElementById('seniorTicket').value) || 0;
var seniorcost = senior * seniorprice;
var Military = Number(document.getElementById('militaryTicket').value) || 0;
var militarycost = Military * militaryprice;
var StudentDay = Number(document.getElementById('studentdayTicket').value) || 0;
var studentdaycost = StudentDay * studentdayprice;
var seniorDay = Number(document.getElementById('seniordayTicket').value) || 0;
var seniordaycost = seniorDay * seniordayprice;
var Adult = Number(document.getElementById('adultTicket').value) || 0;
var adultcost = Adult * adultprice
var child = Number(document.getElementById('childTicket').value) || 0;
var childcost = child * childprice;
var threeD = Number(document.getElementById('threed').value) || 0;
var threeDcost = threeD * threeDprice;
var Imax = Number(document.getElementById('imax').value) || 0;
var imaxCost = Imax * imaxPrice;
var Imax3d = Number(document.getElementById('imax3d').value) || 0;
var imax3dCost = Imax3d * imax3dPrice;
var total = childcost+adultcost+militarycost+seniorcost+studentdaycost+seniordaycost+threeDcost+imaxCost+imax3dCost+beforenooncost+matineecost;
document.getElementById('calculate').innerHTML = total.toFixed(2);
}
</code></pre>
<p>HTML</p>
<pre><code><!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="amc.css">
<meta charset="utf-8">
<title>Ticket Calculator</title>
</head>
<body>
<div id="logo1"><img src="logo1.png" width="822" height="59" alt=""/></div>
<div id="outline">
<div id="quantityLabel">Please enter the quantity of each ticket</div>
<div id="ticketFields">
<div class="controls controls-row">
<input type="text" id="beforeNoon" class="input-small" placeholder="Before Noon"><br>
<input type="text" id="matinee" class="input-small" placeholder="Matinee"><br>
<input type="text" id="adultTicket" class="input-small" placeholder="Adult"><br>
<input type="text" id="childTicket" class="input-small" placeholder="Child"><br>
<input type="text" id="seniorTicket" class="input-small" placeholder="Senior"><br>
<input type="text" id="military" class="input-small" placeholder="Military"><br>
<input type="text" id="seniorDayTicket" class="input-small" placeholder="Senior Day"><br>
<input type="text" id="studentDayTicket" class="input-small" placeholder="Student Day">
<div id="pricingStructure">
<div id="beforeNoonPrice">$6.75</div>
<div id="matineePrice">$9.00</div>
<div id="adultPrice">$10.75</div>
<div id="childPrice">$8.00</div>
<div id="seniorPrice">$9.25</div>
<div id="militaryPrice">$9.25</div>
<div id="seniorDayPrice">$6.75</div>
<div id="studentDayPrice">$8.00</div>
</div><br>
<br>
<div id="additionalInfo">
<div id="please2">Please enter additional information if needed</div>
<input type="text" id="threed" class="input-small" ><div id="reg3d">How many tickets are regular<b> 3D?</b>&nbsp;&nbsp;($3.50 additional charge per ticket)</div>
<input class="input-small" id="imax" type="text" ><div id="imaxLabel">How many tickets are <b>IMAX(NO 3D)?</b>&nbsp;&nbsp;($4.50 additional charge per
ticket)</div>
<input class="input-small" id="imax3dField" type="text" ><div id="imax3d">How many tickets are <b>IMAX 3D?</b>&nbsp;&nbsp;($5.50 additional charge per ticket)</div><br>
<button type="button" id="calculateButton" onClick="displayTotal()" class="btn btn-success btn-lg">Calculate</button>
<button type="button" id="clearButton" class="btn btn-danger btn-lg" onClick="window.location.reload()">Clear</button>
<div id="calculate">
<br>
</div>
<div id="totalCalculated">Ticket Total: $ </div>
</div>
</div>
</div>
<script type="text/javascript" src="jQuery.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="amc.js"></script>
</div>
</body>
</code></pre>
| 3 | 2,306 |
optimize query with lambra expression in entity framework
|
<p>I have the following query, often have excution timeout errors, have any ideas for optimization.
Thank you!</p>
<pre><code>queryResult = db.Products
.Where(x => !x.product_is_deleted)
.Where(x => x.product_name.Contains(keyword) || x.product_barcode.Contains(keyword) || x.ProductType.pro_type_name.Contains(keyword) || x.ProductType.pro_type_name.Contains(keyword))
.Select(x => new ProductView
{
product_id = x.product_id,
product_barcode = x.product_barcode,
product_name = x.product_name,
product_unit = x.product_unit,
product_size = x.product_size,
product_weight = x.product_weight,
product_type_id = x.product_type_id,
product_inventory = shelf == 0 ? (x.ImportProductDetails.Where(y => y.imp_pro_detail_product_id == x.product_id && y.ImportProduct.import_pro_warehouse_id == warehouse_id ).Select(y => y.imp_pro_detail_inventory).DefaultIfEmpty(0).Sum()) : (x.ImportProductDetails.Where(y => y.imp_pro_detail_product_id == x.product_id && y.ImportProduct.import_pro_warehouse_id == warehouse_id && y.imp_pro_detail_shelf_id == shelf).Select(y => y.imp_pro_detail_inventory).DefaultIfEmpty(0).Sum()),
product_opening_stock = x.product_opening_stock,
product_type_name = x.ProductType.pro_type_name,
product_price = x.ProductPrices.Where(y => !y.proprice_is_deleted).Where(y => y.proprice_applied_datetime <= DateTime.Now).OrderByDescending(y => y.proprice_applied_datetime).Select(y => y.proprice_price).FirstOrDefault(),
product_discount_type = x.ProductDiscounts.Where(y => !y.pro_discount_is_deleted && y.pro_discount_start_datetime <= datetimeNow && y.pro_discount_end_datetime >= datetimeNow).OrderByDescending(y => y.pro_discount_id).Select(y => y.pro_discount_type).FirstOrDefault(),
product_discount_value = x.ProductDiscounts.Where(y => !y.pro_discount_is_deleted && y.pro_discount_start_datetime <= datetimeNow && y.pro_discount_end_datetime >= datetimeNow).OrderByDescending(y => y.pro_discount_id).Select(y => y.pro_discount_value).FirstOrDefault()
//product_norm_name = x.ProductionNorms.Where(y => y.pro_norm_name == x.product_id && y.pro_norm_is_applied == true).Select(y => y.pro_norm_id).FirstOrDefault()
});
</code></pre>
| 3 | 1,454 |
Message Box preventing exception, but requires user input
|
<p>This code gets images from google, and sets a Picturebox's image to the specified index. For some reason it will not work without, "MsgBox("anytext")" being right before "Dim hecImages as HtmlElementCollection..."</p>
<pre><code>Private Sub GetImagesFromUrl()
Dim wbID As New WebBrowser
wbID.Navigate("https://www.google.com/search?q=" + TextBox2.Text + "+ background" + "&tbm=isch")
Dim wcObj As New System.Net.WebClient() 'Create New Web Client Object
MsgBox("anytext")
Dim hecImages As HtmlElementCollection = wbID.Document.GetElementsByTagName("img") 'Browse Through HTML Tags
Dim strWebTitle As String 'Web Page Title
Dim strPath1 As String 'Folder Path
Dim strPath2 As String 'Sub Folder Path
strWebTitle = wbID.DocumentTitle 'Obtain Web Page Title
strPath1 = Application.StartupPath + "\content\images\" & strWebTitle 'Create Folder Named Web Page Title
strPath2 = strPath1 & "\Images" 'Create Images Sub Folder
Dim diTitle As DirectoryInfo = Directory.CreateDirectory(strPath1)
Dim diImages As DirectoryInfo = Directory.CreateDirectory(strPath2)
For i As Integer = 0 To hecImages.Count - 1 'Loop Through All IMG Elements Found
'Download Image(s) To Specified Path
wcObj.DownloadFile(hecImages(i).GetAttribute("src"), strPath1 & "\images\" & i.ToString() & ".jpg")
Next
' MsgBox(strPath2)
PictureBox1.Image = Image.FromFile(strPath2 + "\1.jpg")
End Sub
</code></pre>
<p>Removing the messagebox only causes "hecImages" to return nothing.</p>
<pre><code>Exception Thrown:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Forms.WebBrowser.Document.get returned Nothing.
</code></pre>
<p>I want it to be able to do all this without the user pressing anything</p>
<hr />
<pre><code>'Fixed Version
#Region "Get Images from URL"
Private WithEvents wbID As New WebBrowser
Private Sub GetImagesFromUrl()
Dim wbCleanPath = Path.Combine("https://www.google.com/search?q=" + Form2.TextBox2.Text + "+ background + banner" + "&tbm=isch")
wbID.Navigate(wbCleanPath)
End Sub
Private Sub wbID_DlFinished(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles wbID.DocumentCompleted
If wbID.ReadyState = WebBrowserReadyState.Complete Then
Dim wcObj As New System.Net.WebClient() 'Create New Web Client Object
'MsgBox("anytext")
Dim hecImages As HtmlElementCollection = wbID.Document.GetElementsByTagName("img") 'Browse Through HTML Tags
Dim strWebTitle As String 'Web Page Title
Dim strPath1 As String 'Folder Path
Dim strPath2 As String 'Sub Folder Path
strWebTitle = wbID.DocumentTitle 'Obtain Web Page Title
strPath1 = Path.Combine(Application.StartupPath + "\content\images\" & strWebTitle) 'Create Folder Named Web Page Title
strPath2 = Path.Combine(strPath1 & "\Images") 'Create Images Sub Folder
Dim diTitle As DirectoryInfo = Directory.CreateDirectory(strPath1)
Dim diImages As DirectoryInfo = Directory.CreateDirectory(strPath2)
For i As Integer = 0 To 1 'Loop Through All IMG Elements Found
'Download Image(s) To Specified Path
wcObj.DownloadFile(hecImages(i).GetAttribute("src"), Path.Combine(strPath1 & "\images\" & i.ToString() & ".jpg"))
Next
' MsgBox(strPath2)
PictureBox1.Image = Image.FromFile(Path.Combine(strPath2 + "\1.jpg"))
File.Delete(Path.Combine(strPath2 + "\0.jpg"))
wbID.Dispose()
wcObj.Dispose()
Else
'donothing
End If
End Sub
#End Region
</code></pre>
| 3 | 1,683 |
Error Resources not found on Xamarin Forms droid
|
<p>I have a xamarin solution with a iOS project working, now i'm triying to do the same on android. So i created a new project android, install the nugets, and set the references, and this happens:</p>
<pre><code>resource integer/google_play_services_version not found. (APT0000)
</code></pre>
<p>In the path obj/debug/android..., so i delete the obj and bin folder, build and got this:</p>
<pre><code>resource style/Theme.AppCompat.Light.Dialog' not found.
style attribute 'attr/colorAccent' not found.
resource style/Theme.AppCompat.Light.DarkActionBar' not found.
style attribute 'attr/windowNoTitle' not found.
style attribute 'attr/windowActionBar' not found.
style attribute 'attr/colorPrimary' not found.
style attribute 'attr/colorPrimaryDark' not found.
style attribute 'attr/colorAccent' not found.
style attribute 'attr/windowActionModeOverlay' not found.
</code></pre>
<p>I deleted the obj and bin folder, the .local/share/xamarin too, clean and rebuild. And the packages are this:
<a href="https://i.stack.imgur.com/2jajp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2jajp.png" alt="enter image description here"></a></p>
<p>And this is my style.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Login" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowBackground">@drawable/SplashImage</item>
<!-- This is for the EditText Color lines-->
<item name="colorControlNormal">@color/white</item>
<item name="colorControlActivated">@color/greenBase</item>
<item name="colorControlHighlight">@color/greenBase</item>
<item name="android:textColorHint">@color/white</item>
</style>
<style name="MyActionBarStyle" parent="Widget.AppCompat.Light.ActionBar.Solid">
<item name="displayOptions">showTitle</item>
</style>
<!-- Base theme applied no matter what API -->
<style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<!--If you are using revision 22.1 please use just windowNoTitle. Without android:-->
<item name="windowNoTitle">false</item>
<item name="actionBarStyle">@style/MyActionBarStyle</item>
<!--We will be using the toolbar so no need to show ActionBar-->
<item name="windowActionBar">true</item>
<!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette -->
<!-- colorPrimary is used for the default action bar background -->
<item name="colorControlNormal">@color/greyBase</item>
<item name="colorControlActivated">@color/greenBase</item>
<item name="colorControlHighlight">@color/greenBase</item>
<item name="android:textColorHint">@color/greyBase</item>
<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight and colorSwitchThumbNormal. -->
<item name="windowActionModeOverlay">true</item>
<item name="android:datePickerDialogTheme">@style/AppCompatDialogStyle</item>
</style>
<style name="AppCompatDialogStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/greenBase</item>
</style>
<style name="MainTheme" parent="MainTheme.Base"/>
<!-- Base theme applied no matter what API -->
<style name="MainTheme.BaseLight" parent="Theme.AppCompat.Light.NoActionBar">
<!--If you are using revision 22.1 please use just windowNoTitle. Without android:-->
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette -->
<!-- colorPrimary is used for the default action bar background -->
<item name="colorControlNormal">@color/greyBase</item>
<item name="colorControlActivated">@color/greenBase</item>
<item name="colorControlHighlight">@color/greenBase</item>
<item name="android:textColorHint">@color/greyBase</item>
<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight and colorSwitchThumbNormal. -->
<item name="windowActionModeOverlay">true</item>
<item name="android:datePickerDialogTheme">@style/AppCompatDialogStyle</item>
</style>
</resources>
</code></pre>
<p>I don't know if i'm making something wrong to make the android app. What more can i try?</p>
| 3 | 1,990 |
How to reload Datatable using Ajax when checkbox is clicked
|
<p>I want to be able to reload my Datatable once my checkbox is clicked , provided below is my attempted code but I continue to get error:Uncaught TypeError: Cannot set property 'data' of null not really sure how to handle this error. I have provided both the javascript and the view in my MVC application please let me know if you need more details.</p>
<p><strong><em>.js</em></strong></p>
<pre><code>function ReloadTable()
{
$(document).ready(function () {
var table = $('#DashboardTable').DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
//"pageLength": 5,
"ajax": {
"url": "/Chargeback/Index",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "ChargebackCode" },
{ "data": "StatusName" },
{ "data": "BusinessUnitName" },
{ "data": "InvoiceCode" },
{ "data": "OrderCode" },
{ "data": "PickTicketCode" },
{ "data": "CustomerPo" },
{ "data": "AssignedDepartment" },
{ "data": "DivisionName" },
{ "data": "Customer" },
{ "data": "WarehouseName" },
{ "data": "Coordinator" },
{ "data": "ChargebackDate" },
{ "data": "ModDate" },
{ "data": "ChargebackDeadline" },
{ "data": "ChargebackCloseDate" },
{ "data": " DaysOpen" },
{ "data": "ChargebackAmount" },
{ "data": "ChargebackBalance" },
{ "data": "FaultName" },
{ "data": "ResponsibleName" }
]
});
table.ajax.reload();
});
}
</code></pre>
<p><strong><em>view:</em></strong></p>
<pre><code>@using (Html.BeginForm("Index", "Chargeback"))
{
<label id = "Include" > @Html.CheckBox("IncludeClosed", (bool)ViewBag.IncludeClosed, new { onChange = "ReloadTable()" }) Include Closed</label>
<table id="DashboardTable" class="table table-striped" >
<thead>
<tr>
<th>Code</th>
<th>Status</th>
<th>Business</th>
<th>Invoice</th>
<th>Order</th>
<th>Pick Tickets</th>
<th>Customer PO</th>
<th>Assigned</th>
<th>Division</th>
<th>Customer</th>
<th>Warehouse</th>
<th>Coordinator</th>
<th>Open Date</th>
<th>Last Activity</th>
<th>Deadline</th>
<th>Closed Date</th>
<th>Days Open</th>
<th>Amount</th>
<th>Balance</th>
<th>Fault</th>
<th>Responsible</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
var chargebackDeadline = item.ChargebackDeadline == null ? "" : ((DateTime)item.ChargebackDeadline).ToString("MM/dd/yyyy");
var chargebackCloseDateAsString = item.ChargebackCloseDate == null ? "" : ((DateTime)item.ChargebackCloseDate).ToString("MM/dd/yyyy");
<tr>
<td>@Html.ActionLink(item.ChargebackCode, "Details", "Chargeback", new { id = item.Id }, null)</td>
<td>@item.StatusName</td>
<td>@item.BusinessUnitName</td>
<td>@item.InvoiceCode</td>
<td>@item.OrderCode</td>
<td>@item.PickTicketCode</td>
<td>@item.CustomerPo</td>
<td>@item.AssignedDepartment</td>
<td>@item.DivisionName</td>
<td>@item.Customer</td>
<td>@item.WarehouseName</td>
<td>@item.Coordinator</td>
<td>@item.ChargebackDate.ToString("MM/dd/yyyy")</td>
<td>@item.ModDate.ToString("MM/dd/yyyy")</td>
<td>@chargebackDeadline</td>
<td>@chargebackCloseDateAsString</td>
<td>@item.DaysOpen</td>
<td>$@item.ChargebackAmount</td>
<td>$@item.ChargebackBalance</td>
<td>@item.FaultName</td>
<td>@item.ResponsibleName</td>
</tr>
}
</tbody>
</table>
}
</code></pre>
| 3 | 2,731 |
Compute the Cartesian Distance between points in high-dimensional space optimally
|
<p><strong>Summary:</strong></p>
<p>My class SquareDistance computes the square of the Cartesian distance in four ways using methods with these names:</p>
<ol>
<li>Signed</li>
<li>UnsignedBranching</li>
<li>UnsignedDistribute</li>
<li>CastToSignedLong</li>
</ol>
<p>The first one is fastest and uses signed integers, but my data must be unsigned (for reasons given below). The other three methods start with unsigned numbers. My goal is to write a method like those in SquareDistance that takes unsigned data and performs better than the three I already wrote, as close as possible in performance to #1. Code with benchmark results follows. (unsafe code is permitted, if you think it will help.)</p>
<p><strong>Details:</strong></p>
<p>I am developing an algorithm to solve K-nearest neighbor problems using an index derived from the Hilbert curve. The execution time for the naive, linear scan algorithm grows in time quadratically with the number of points and linearly with the number of dimensions, and it spends all its time computing and comparing Cartesian distances. </p>
<p>The motivation behind the special Hilbert index is to reduce the number of times that the distance function is called. However, it must still be called millions of times, so I must make it as fast as possible. (It is the most frequently called function in the program. A recent failed attempt to optimize the distance function doubled the program execution time from seven minutes to fifteen minutes, so no, this is not a premature or superfluous optimization.)</p>
<p><strong>Dimensions</strong>: The points may have anywhere from ten to five thousand dimensions.</p>
<p><strong>Constraints</strong>. I have two annoying constraints:</p>
<ol>
<li><p>The Hilbert transformation logic requires that the points be expressed as uint (unsigned integer) arrays. (The code was written by another, is magic and uses shifts, ANDs, ORs, and the like and can't be changed.) Storing my points as signed integers and incessantly casting them to uint arrays produced wretched performance, so I must at the very least store a uint array copy of each point.</p></li>
<li><p>To improve efficiency, I made a signed integer copy of each point to speed up the distance calculations. This worked very well, but once I get to about 3,000 dimensions, I run out of memory! </p></li>
</ol>
<p>To save on memory, I removed the memoized signed integer arrays and tried to write an unsigned version of the distance calculation. My best results are 2.25 times worse than the signed integer version.</p>
<p>The benchmarks create 1000 random points of 1000 dimensions each and perform distance calculations between every point and every other point, for 1,000,000 comparisons. Since I only care about the relative distance, I save time by not performing the square root.</p>
<p>In debug mode:</p>
<blockquote>
<pre><code>SignedBenchmark Ratio: 1.000 Seconds: 3.739
UnsignedBranchingBenchmark Ratio: 2.731 Seconds: 10.212
UnsignedDistributeBenchmark Ratio: 3.294 Seconds: 12.320
CastToSignedLongBenchmark Ratio: 3.265 Seconds: 12.211
</code></pre>
</blockquote>
<p>In release mode:</p>
<pre><code> SignedBenchmark Ratio: 1.000 Seconds: 3.494
UnsignedBranchingBenchmark Ratio: 2.672 Seconds: 9.334
UnsignedDistributeBenchmark Ratio: 3.336 Seconds: 11.657
CastToSignedLongBenchmark Ratio: 3.471 Seconds: 12.127
</code></pre>
<p>The above benchmarks were run on a Dell with an Intel Core i7-4800MQ CPU @ 2.70GHz with 16 GB memory. My larger algorithm already uses the Task Parallel library for larger tasks, so it is fruitless to parallelize this inner loop.</p>
<p><strong>Question:</strong> Can anyone think of a faster algorithm than UnsignedBranching?</p>
<p>Below is my benchmark code.</p>
<p><strong>UPDATE</strong></p>
<p>This uses loop unrolling (thanks to @dasblinkenlight) and is 2.7 times faster:</p>
<pre><code>public static long UnsignedLoopUnrolledBranching(uint[] x, uint[] y)
{
var distance = 0UL;
var leftovers = x.Length % 4;
var dimensions = x.Length;
var roundDimensions = dimensions - leftovers;
for (var i = 0; i < roundDimensions; i += 4)
{
var x1 = x[i];
var y1 = y[i];
var x2 = x[i+1];
var y2 = y[i+1];
var x3 = x[i+2];
var y3 = y[i+2];
var x4 = x[i+3];
var y4 = y[i+3];
var delta1 = x1 > y1 ? x1 - y1 : y1 - x1;
var delta2 = x2 > y2 ? x2 - y2 : y2 - x2;
var delta3 = x3 > y3 ? x3 - y3 : y3 - x3;
var delta4 = x4 > y4 ? x4 - y4 : y4 - x4;
distance += delta1 * delta1 + delta2 * delta2 + delta3 * delta3 + delta4 * delta4;
}
for (var i = roundDimensions; i < dimensions; i++)
{
var xi = x[i];
var yi = y[i];
var delta = xi > yi ? xi - yi : yi - xi;
distance += delta * delta;
}
return (long)distance;
}
</code></pre>
<p><strong>SquareDistance.cs:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DistanceBenchmark
{
/// <summary>
/// Provide several alternate methods for computing the square of the Cartesian distance
/// to allow study of their relative performance.
/// </summary>
public static class SquareDistance
{
/// <summary>
/// Compute the square of the Cartesian distance between two N-dimensional points
/// with calculations done on signed numbers using signed arithmetic,
/// a single multiplication and no branching.
/// </summary>
/// <param name="x">First point.</param>
/// <param name="y">Second point.</param>
/// <returns>Square of the distance.</returns>
public static long Signed(int[] x, int[] y)
{
var distance = 0L;
var dimensions = x.Length;
for (var i = 0; i < dimensions; i++)
{
var delta = x[i] - y[i];
distance += delta * delta;
}
return distance;
}
/// <summary>
/// Compute the square of the Cartesian distance between two N-dimensional points
/// with calculations done on unsigned numbers using unsigned arithmetic, a single multiplication
/// and a branching instruction (the ternary operator).
/// </summary>
/// <param name="x">First point.</param>
/// <param name="y">Second point.</param>
/// <returns>Square of the distance.</returns>
public static long UnsignedBranching(uint[] x, uint[] y)
{
var distance = 0UL;
var dimensions = x.Length;
for (var i = 0; i < dimensions; i++)
{
var xi = x[i];
var yi = y[i];
var delta = xi > yi ? xi - yi : yi - xi;
distance += delta * delta;
}
return (long)distance;
}
/// <summary>
/// Compute the square of the Cartesian distance between two N-dimensional points
/// with calculations done on unsigned numbers using unsigned arithmetic and the distributive law,
/// which requires four multiplications and no branching.
///
/// To prevent overflow, the coordinates are cast to ulongs.
/// </summary>
/// <param name="x">First point.</param>
/// <param name="y">Second point.</param>
/// <returns>Square of the distance.</returns>
public static long UnsignedDistribute(uint[] x, uint[] y)
{
var distance = 0UL;
var dimensions = x.Length;
for (var i = 0; i < dimensions; i++)
{
ulong xi = x[i];
ulong yi = y[i];
distance += xi * xi + yi * yi - 2 * xi * yi;
}
return (long)distance;
}
/// <summary>
/// Compute the square of the Cartesian distance between two N-dimensional points
/// with calculations done on unsigned numbers using signed arithmetic,
/// by first casting the values into longs.
/// </summary>
/// <param name="x">First point.</param>
/// <param name="y">Second point.</param>
/// <returns>Square of the distance.</returns>
public static long CastToSignedLong(uint[] x, uint[] y)
{
var distance = 0L;
var dimensions = x.Length;
for (var i = 0; i < dimensions; i++)
{
var delta = (long)x[i] - (long)y[i];
distance += delta * delta;
}
return distance;
}
}
}
</code></pre>
<p><strong>RandomPointFactory.cs:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DistanceBenchmark
{
public static class RandomPointFactory
{
/// <summary>
/// Get a random list of signed integer points with the given number of dimensions to use as test data.
/// </summary>
/// <param name="recordCount">Number of points to get.</param>
/// <param name="dimensions">Number of dimensions per point.</param>
/// <returns>Signed integer test data.</returns>
public static IList<int[]> GetSignedTestPoints(int recordCount, int dimensions)
{
var testData = new List<int[]>();
var random = new Random(DateTime.Now.Millisecond);
for (var iRecord = 0; iRecord < recordCount; iRecord++)
{
int[] point;
testData.Add(point = new int[dimensions]);
for (var d = 0; d < dimensions; d++)
point[d] = random.Next(100000);
}
return testData;
}
/// <summary>
/// Get a random list of unsigned integer points with the given number of dimensions to use as test data.
/// </summary>
/// <param name="recordCount">Number of points to get.</param>
/// <param name="dimensions">Number of dimensions per point.</param>
/// <returns>Unsigned integer test data.</returns>
public static IList<uint[]> GetUnsignedTestPoints(int recordCount, int dimensions)
{
var testData = new List<uint[]>();
var random = new Random(DateTime.Now.Millisecond);
for (var iRecord = 0; iRecord < recordCount; iRecord++)
{
uint[] point;
testData.Add(point = new uint[dimensions]);
for (var d = 0; d < dimensions; d++)
point[d] = (uint)random.Next(100000);
}
return testData;
}
}
}
</code></pre>
<p><strong>Program.cs:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DistanceBenchmark
{
public class Program
{
private static IList<int[]> SignedTestData = RandomPointFactory.GetSignedTestPoints(1000, 1000);
private static IList<uint[]> UnsignedTestData = RandomPointFactory.GetUnsignedTestPoints(1000, 1000);
static void Main(string[] args)
{
var baseline = TimeIt("SignedBenchmark", SignedBenchmark);
TimeIt("UnsignedBranchingBenchmark", UnsignedBranchingBenchmark, baseline);
TimeIt("UnsignedDistributeBenchmark", UnsignedDistributeBenchmark, baseline);
TimeIt("CastToSignedLongBenchmark", CastToSignedLongBenchmark, baseline);
TimeIt("SignedBenchmark", SignedBenchmark, baseline);
Console.WriteLine("Done. Type any key to exit.");
Console.ReadLine();
}
public static void SignedBenchmark()
{
foreach(var p1 in SignedTestData)
foreach (var p2 in SignedTestData)
SquareDistance.Signed(p1, p2);
}
public static void UnsignedBranchingBenchmark()
{
foreach (var p1 in UnsignedTestData)
foreach (var p2 in UnsignedTestData)
SquareDistance.UnsignedBranching(p1, p2);
}
public static void UnsignedDistributeBenchmark()
{
foreach (var p1 in UnsignedTestData)
foreach (var p2 in UnsignedTestData)
SquareDistance.UnsignedDistribute(p1, p2);
}
public static void CastToSignedLongBenchmark()
{
foreach (var p1 in UnsignedTestData)
foreach (var p2 in UnsignedTestData)
SquareDistance.CastToSignedLong(p1, p2);
}
public static double TimeIt(String testName, Action benchmark, double baseline = 0.0)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
benchmark();
stopwatch.Stop();
var seconds = stopwatch.Elapsed.TotalSeconds;
var ratio = baseline <= 0 ? 1.0 : seconds/baseline;
Console.WriteLine(String.Format("{0,-32} Ratio: {1:0.000} Seconds: {2:0.000}", testName, ratio, seconds));
return seconds;
}
}
}
</code></pre>
| 3 | 5,617 |
LWJGL Objects not shown on ATI graphics card
|
<p>I've written an LWJGL application that uses .obj files, reads them and displays them (using displaylists).</p>
<p>On my nvidia graphics card, everything runs fine. But on an amd graphics card i can't see the objects.</p>
<p>How i give data to the shaders:</p>
<pre><code>glUseProgram(shaderEngine.obj);
glUniform1i(glGetUniformLocation(shaderEngine.obj, "inOrangeJuice"), inOrangeJuice ? 1 : 0);
shaderEngine.loadMatrix(glGetUniformLocation(shaderEngine.standard, "projectionMatrix"), camera.projectionMatrix);
shaderEngine.loadMatrix(glGetUniformLocation(shaderEngine.obj, "viewMatrix"), camera.viewMatrix);
</code></pre>
<p>ModelMatrix is loaded:</p>
<pre><code>shaderEngine.createModelMatrix(new Vector3f(x, y, z), new Vector3f(rx, ry, rz), new Vector3f(1, 1, 1));
shaderEngine.loadModelMatrix(shaderEngine.obj);
</code></pre>
<p>Fragment Shader:</p>
<pre><code>#version 130
uniform sampler2D tex;
uniform vec2 texCoord[4];
float textureSize;
float texelSize;
uniform int inOrangeJuice;
bool pointInTriangle(vec3 P, vec3 A, vec3 B, vec3 C)
{
vec3 u = B - A;
vec3 v = C - A;
vec3 w = P - A;
vec3 vCrossW = cross(v, w);
vec3 vCrossU = cross(v, u);
if(dot(vCrossW, vCrossU) < 0)
{
return false;
}
vec3 uCrossW = cross(u, w);
vec3 uCrossV = cross(u, v);
if(dot(uCrossW, uCrossV) < 0)
{
return false;
}
float denom = length(uCrossV);
float r = length(vCrossW);
float t = length(uCrossW);
return (r + t <= 1);
}
vec4 texture2DBilinear(sampler2D textureSampler, vec2 uv)
{
vec4 tl = texture2D(textureSampler, uv);
vec4 tr = texture2D(textureSampler, uv + vec2(texelSize, 0));
vec4 bl = texture2D(textureSampler, uv + vec2(0, texelSize));
vec4 br = texture2D(textureSampler, uv + vec2(texelSize , texelSize));
vec2 f = fract( uv.xy * textureSize );
vec4 tA = mix( tl, tr, f.x );
vec4 tB = mix( bl, br, f.x );
return mix( tA, tB, f.y );
}
void main()
{
ivec2 textureSize2d = textureSize(tex,0);
textureSize = float(textureSize2d.x);
texelSize = 1.0 / textureSize;
//texture coordinate:
vec2 texCoord = (gl_TexCoord[0].st);
bool inOJ = false;
if(inOrangeJuice == 1)
{
float depth = gl_FragCoord.z / gl_FragCoord.w;//works only with perspective projection
depth = depth / 6;
if(depth > 1)
{
depth = 1;
}
inOJ = true;
gl_FragColor = texture2DBilinear(tex, texCoord) * gl_Color * (1.0 - depth) + vec4(1.0, 0.5, 0.0, 1.0) * depth;
}
if(inOJ == false)
{
gl_FragColor = texture2DBilinear(tex, texCoord) * gl_Color;
}
//Nothing is shown, inOrangeJuice should be 0
//gl_FragColor = vec4(inOrangeJuice,0,0,1);
//Always works:
//gl_FragColor = texture2D(tex, texCoord) * gl_Color;
}
</code></pre>
| 3 | 1,260 |
facebook login status in sdk javascript
|
<p>I have a problem to get the login status of the logged in user.
The getLoginStatus Function will be not called.
I want to get the access token to get the user data.
I tried with my own APP-ID and with a game APP-ID (298553513572593).
Above you can see my code:</p>
<pre><code><body>
<div id="fb-root"></div>
<script type="text/javascript">
// Load the SDK asynchronously
(
function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
//js.src = "http://connect.facebook.net/de_DE/all.js";
js.src = "http://connect.facebook.net/de_DE/all.js#xfbml=1&appId=APP_ID";
fjs.parentNode.insertBefore(js, fjs);
}
(document, 'script', 'facebook-jssdk')
);
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
} else {
// cancelled
}
});
}
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'APP_ID',
status : true,
cookie : true,
xfbml : true
});
// Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
alert(response);
if (response.status === 'connected') {
// connected
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// not_authorized
login();
} else {
// not_logged_in
login();
}
});
};
</script>
<div>
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
</div>
</body>
</code></pre>
<p>The Html-Tag has the attribute <code>xmlns:fb="http://ogp.me/ns/fb#"</code></p>
| 3 | 1,320 |
How to import an object of one app into another app in the same django project?
|
<p>Codes are given below.</p>
<p><strong>users.model.py</strong></p>
<pre><code>from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.db import models
# from django.contrib.auth.models import User
from PIL import Image
from .managers import CustomUserManager
from django.contrib import admin
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
class CustomUser(AbstractUser):
username = None
first_name = models.CharField('Name',max_length=200,unique=True)
email = models.EmailField(_('email address'), unique=True)
registration = models.IntegerField()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
class Profile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
</code></pre>
<p><strong>blog.model.py</strong></p>
<pre><code>from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.conf import settings
from multiselectfield import MultiSelectField
from django import forms
from django.core.validators import MinValueValidator, MaxValueValidator
from PIL import Image
DAYS_OF_WEEK = [
(0, ' Monday'),
(1, ' Tuesday'),
(2, ' Wednesday'),
(3, ' Thursday'),
(4, ' Friday'),
(5, ' Saturday'),
(6, ' Sunday'),
]
class PostManager(models.Manager):
def like_toggle(self, user, post_obj):
if user in post_obj.liked.all():
is_liked = False
post_obj.liked.remove(user)
else:
is_liked = True
post_obj.liked.add(user)
return is_liked
class Post(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField('Doctor\'s Name',max_length=100)
content = models.CharField('Specialty',max_length=100)
chamber = models.CharField('Chamber\'s Name',max_length=200)
address = models.CharField('Address',max_length=100, blank=True)
fees = models.IntegerField(default=0)
days = MultiSelectField('Available Days', choices= DAYS_OF_WEEK)
start_time = models.TimeField('Chamber Beginning Time')
end_time = models.TimeField('Chamber Ending Time')
image = models.ImageField( upload_to='profile_pics')
review = models.TextField()
rating = models.IntegerField('Behavior')
overall_rating = models.PositiveIntegerField(validators=[
MaxValueValidator(10),
MinValueValidator(0)
])
liked = models.ManyToManyField(
settings.AUTH_USER_MODEL, blank=True, related_name='liked')
date_posted = models.DateTimeField(default=timezone.now)
objects = PostManager()
class Meta:
ordering = ('-date_posted', )
def get_absolute_url(self):
return reverse('post_detail', kwargs={'pk': self.pk})
def save(self):
super().save() # saving image first
img = Image.open(self.image.path) # Open image using self
if (img.height > 1020 or img.width > 1920):
new_img = (1020, 1920)
img.thumbnail(new_img)
img.save(self.image.path) # saving image at the same path
class Comment(models.Model):
post = models.ForeignKey(
Post, related_name='comments', on_delete=models.CASCADE)
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=True)
def approve(self):
self.approved_comment = True
self.save()
def get_absolute_url(self):
return reverse("post_list")
def __str__(self):
return self.author
</code></pre>
<p>I have created a project. In that project there are two apps named: user and blog. I'm saving the CustomUsers in Profile.
I want to use the user.model.py file's first_name field value as blog.model.py file's title field.
I'm new to django.Help me fix this issue!</p>
| 3 | 1,645 |
Puppeteer - TypeError: require(...) is not a function
|
<p>I've started using puppeteer to test a login form, I've tried the following code but I get this errors in vs terminal when I try to run the script</p>
<p>index.js</p>
<pre><code>#!/usr/bin/env node
require('dotenv').config()
const puppeteer = require('puppeteer')
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.google.com');
// other actions...
//await browser.close();
})();
</code></pre>
<pre><code>(async () => {
^
TypeError: require(...) is not a function
at Object.<anonymous> (/Users/dev/Desktop/fuserbot/index.js:30:1)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
</code></pre>
<p>The code is the same of the example provided on the puppeteer documentation. As you can see I'm trying to make a cli script. If I try with my custom code, I will get this error instead</p>
<p>index.js</p>
<pre><code>#!/usr/bin/env node
require('dotenv').config();
const puppeteer = require('puppeteer');
(async () => {
//
const browser = await puppeteer.launch();
//
const page = await browser.newPage();
//
page.setRequestInterception(true);
//
page.on('request', (request) => {
console.log(request.url(), request.headers(), request.method(), request.postData());
});
//
await page.goTo('https://www.examplesite.com');
//
await page.type('#email', process.env.MY_EMAIL, {delay: 2000});
await page.type('#pass', process.env.MY_PASS, {delay: 2000});
//
await page.click('button[type="submit"]');
//
await page.waitForNavigation();
console.log('New url', page.url());
})();
</code></pre>
<pre><code> const page = browser.newPage();
^
TypeError: browser.newPage is not a function
at /Users/dev/Desktop/fuserbot/index.js:12:26
at Object.<anonymous> (/Users/dev/Desktop/fuserbot/index.js:30:3)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
</code></pre>
<p>What's wrong with the code?</p>
| 3 | 1,068 |
How to make the text inside of a div glow whenever you hover over the div
|
<p>Okay I have this navbar its a series of 5 divs that have text inside of them. I want to make it to where whenever I hover over a div the <code><p></code> element inside of the div will have a glow. I know all of the correct css tags to get the glow and such, but I'm stumped when it comes to the (div):hover { } css tags to recognize that I want the text inside of them to glow, not the entire div. Heres the code that you'll need for this.</p>
<p>HTML</p>
<pre class="lang-html prettyprint-override"><code><div id="navBar">
<a class="navLinks" href="#"> <!-- Replace the # with your url or directory link, keep the "" around it. -->
<div class="navButtonsNorm" id="n1">
<p class="navTextNorm">Donate</p><!-- Replace the text between the <p></p> tags with your own link names. -->
</div>
</a>
<a class="navLinks" href="#"> <!-- Replace the # with your url or directory link, keep the "" around it. -->
<div class="navButtonsNorm" id="n2">
<p class="navTextNorm">Contact Me</p><!-- Replace the text between the <p></p> tags with your own link names. -->
</div>
</a>
<a class="navLinks" href="#"> <!-- Replace the # with your url or directory link, keep the "" around it. -->
<div class="navButtonsNorm" id="n3">
<p class="navTextNorm">Portfolio</p><!-- Replace the text between the <p></p> tags with your own link names. -->
</div>
</a>
<a class="navLinks" href="#"> <!-- Replace the # with your url or directory link, keep the "" around it. -->
<div class="navButtonsNorm" id="n4">
<p class="navTextNorm">About me</p><!-- Replace the text between the <p></p> tags with your own link names. -->
</div>
</a>
<a class="navLinks" href="#"> <!-- Replace the # with your url or directory link, keep the "" around it. -->
<div class="navButtonsNorm" id="n5">
<p class="navTextNorm">Home</p> <!-- Replace the text between the <p></p> tags with your own link names. -->
</div>
</a>
</div>
</code></pre>
<p>CSS</p>
<pre class="lang-css prettyprint-override"><code>.navButtonsNorm {
width:150px;
height:50px;
border-right:1px inset black;
float:right;
background: rgba(254,254,254,1);
background: -moz-linear-gradient(top, rgba(254,254,254,1) 0%, rgba(240,240,240,1) 47%, rgba(219,219,219,1) 52%, rgba(226,226,226,1) 100%);
background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(254,254,254,1)), color-stop(47%, rgba(240,240,240,1)), color-stop(52%, rgba(219,219,219,1)), color-stop(100%, rgba(226,226,226,1)));
background: -webkit-linear-gradient(top, rgba(254,254,254,1) 0%, rgba(240,240,240,1) 47%, rgba(219,219,219,1) 52%, rgba(226,226,226,1) 100%);
background: -o-linear-gradient(top, rgba(254,254,254,1) 0%, rgba(240,240,240,1) 47%, rgba(219,219,219,1) 52%, rgba(226,226,226,1) 100%);
background: -ms-linear-gradient(top, rgba(254,254,254,1) 0%, rgba(240,240,240,1) 47%, rgba(219,219,219,1) 52%, rgba(226,226,226,1) 100%);
background: linear-gradient(to bottom, rgba(254,254,254,1) 0%, rgba(240,240,240,1) 47%, rgba(219,219,219,1) 52%, rgba(226,226,226,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fefefe', endColorstr='#e2e2e2', GradientType=0 );
}
.navTextNorm {
font-family:CODE Light;
font-size:24px;
color:black;
-webkit-text-stroke:1px;
text-align:center;
margin-top:15px;
}
.navLinks {
text-decoration:none;
}
.navLinks:hover{
}
</code></pre>
<p>Thanks, if you can help.</p>
| 3 | 1,706 |
Fileserver directory for dynamic route
|
<p><strong>My scenario</strong></p>
<p>Compiled angular projects are saved like</p>
<pre><code>.
├── branch1
│ ├── commitC
│ │ ├── app1
│ │ │ ├── index.html
│ │ │ └── stylesheet.css
│ └── commitD
│ ├── app1
│ │ ├── index.html
│ │ └── stylesheet.css
│ └── app2
│ ├── index.html
│ └── stylesheet.css
├── branch2
│ ├── commitE
│ ├── app1
│ │ ├── index.html
│ │ └── stylesheet.css
│ └── app2
│ ├── index.html
│ └── stylesheet.css
└── master
├── commitA
│ ├── app1
│ │ ├── index.html
│ │ └── stylesheet.css
└── commitB
├── app1
├── index.html
└── stylesheet.css
</code></pre>
<p><strong>Database</strong></p>
<pre><code>TABLE data(id , branch, commit)
</code></pre>
<p>Entries: e.g.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">id</th>
<th style="text-align: center;">branch</th>
<th style="text-align: center;">commit</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">abc</td>
<td style="text-align: center;">branch1</td>
<td style="text-align: center;">commitC</td>
</tr>
<tr>
<td style="text-align: left;">def</td>
<td style="text-align: center;">branch1</td>
<td style="text-align: center;">commitD</td>
</tr>
<tr>
<td style="text-align: left;">ghi</td>
<td style="text-align: center;">master</td>
<td style="text-align: center;">commitA</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Now I want to access</strong></p>
<p>:8080/apps/{id}</p>
<p>e.g.: localhost:8080/apps/<strong>abc</strong></p>
<p>the path should will be generated after requesting the DB entry</p>
<p>and a fileserver serves the directory
./files/<strong>branch1</strong>/<strong>commitC</strong>/</p>
<p>now i would expect to see the folders app1 and app2</p>
<p><strong>What I have</strong></p>
<pre class="lang-golang prettyprint-override"><code>func main() {
mux = mux.NewRouter()
mux.HandleFunc("/apps/{id}/{app}", s.serveApp).Methods("GET")
}
func (s *Server) serveApp(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
app := params["app"]
id := params["id"]
entry, err := getFromDB(id)
if err != nil {
w.Header().Set("Content-Type", "text/html")
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
file := filepath.Join(DefaultFolder, entry.Branch, entry.Commit, app, "index.html")
fmt.Printf("redirecting to %s", file)
http.ServeFile(w, r, file)
}
</code></pre>
<p>how can I serve the whole directory like that, so all css and js files can be accessed correctly?</p>
<p>I think I need something like this</p>
<pre class="lang-golang prettyprint-override"><code>http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
</code></pre>
<p>but how can a access mux.Vars(request) to build up the directory path?</p>
<p><strong>############</strong>
<strong>Regarding CSS serving problem</strong></p>
<pre class="lang-golang prettyprint-override"><code>import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
mux := mux.NewRouter()
fs := http.FileServer(http.Dir("static"))
mux.Handle("/", fs)
log.Println("Listening...")
http.ListenAndServe(":3000", mux)
}
</code></pre>
<p>CSS files are served as 'text/plain'</p>
<p><strong>Files:</strong></p>
<ul>
<li>main.go</li>
<li>static/
<ul>
<li>index.html</li>
<li>main.css</li>
</ul>
</li>
</ul>
<p>index.html</p>
<pre class="lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>A static page</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<h1>Hello from a static page</h1>
</body>
</html>
</code></pre>
<p>main.css</p>
<pre class="lang-css prettyprint-override"><code>body {color: #c0392b}
</code></pre>
| 3 | 1,875 |
How to calculate a div's width and make all their sibilings adopt the biggest size so that they look consistent using CSS?
|
<p>I want to make several divs containing diferent strings () length inside. I want them to fit to the content, but this pose a problem: one of the various divs will contain a larger string, hence, It will be bigger in width than the others, and when applying a border, it looks awful.</p>
<p>I've been practicing some HTML and CSS in jsbin and did this 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-css lang-css prettyprint-override"><code>html,body{
padding:0!important;
margin:0!important;
}
.padre{
border:2px solid violet;
width: -moz-fit-content;
width: -o-fit-content;
width:-webkit-fit-content;
width: fit-content;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="padre">
<div class="hijo">
<h4 id="gato">El gato.</h1>
</div>
<div class="hijo">
<h4 id="gato">La Firefox.</h1>
</div>
<div class="hijo">
<h4>El gato pulpo.</h1>
</div>
<div class="hijo">
<h4>La turritopsis nutrícula.</h1>
</div>
</div>
<div class="padre">
<div class="hijo">
<h4 id="gato">El perro.</h1>
</div>
<div class="hijo">
<h4 id="gato">La vaca.</h1>
</div>
<div class="hijo">
<h4>El lobo aguila.</h1>
</div>
<div class="hijo">
<h4>La caravana h.</h1>
</div>
</div>
<div class="padre">
<div class="hijo">
<h4 id="gato">El mono.</h1>
</div>
<div class="hijo">
<h4 id="gato">La dragon.</h1>
</div>
<div class="hijo">
<h4>La serpiente.</h1>
</div>
<div class="hijo">
<h4>El caballo.</h1>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>:</p>
<p>But as you can see, they don't look consistent because I'm using <code>width:fit-content</code> instead of a fixed width.</p>
<p>Is there a way using pure CSS to calculate the biggest div's width and apply that width to others?</p>
| 3 | 1,362 |
Calculate total amount from different dropdowns selected value
|
<p>I am trying to calculate the total value of the selected value. In one row I have three options one is to select room that is one only, second is to select any one option and the same with the third column. When I am selecting options, it shows the correct "total Amount". Also on clicking on add room one new row with same options appears and there is no limit to add rows. But now what I am trying to do is When someone select values from different rows, "Total Amount" must show the total selected values. </p>
<p>Suppose, I have selected 1 room, 1st value is 5000 and 2nd value is 4000, then "Total Amount" is showing 9000. When I added one more row, in this again I selected 1 room, the 1st value is 6000 and the 2nd value is 9000. Now the " Total Amount" will show 24000 and this will work continuously on adding rows and selecting values.</p>
<p>Here is my HTML :</p>
<pre><code><table style="width: 100%;">
<tr style=" color: white;">
<th class="col-md-4 text-center" style="padding: 10px;">No. of Rooms : </th>
<th class="col-md-4 text-center" style="padding: 10px;">Adult's : </th>
<th class="col-md-4 text-center" style="padding: 10px;">Extra : </th>
</tr>
</table>
<table id="dataTable" style="width: 100%;">
<tr>
<td >
<select name="links" class="form-control person-3" action="post" id="myselect" onChange="document.getElementById('rooms').innerHTML = this.value;">
<option value="0" selected="selected">--select--</option>
<option value="1">1</option>
</select>
</td>
<td >
<select name="keywords" class="form-control person-1" action="post" id="myselect" onChange="document.getElementById('adults').innerHTML = this.value;">
<option value="0" selected="selected">--select--</option>
<option value="5000">1</option>
<option value="8000">2</option>
</select>
</td>
<td >
<select name="violationtype" class="form-control person-2" action="post" id="myselect" onChange="document.getElementById('extra').innerHTML = this.value;">
<option value="0" selected="selected">No Beds</option>
<option value="4000">Adult</option>
<option value="3000">Child below 12</option>
<option value="2000">Child below 7</option>
</select>
</td>
</tr>
</table>
<input type="button" value="Add Rooms" onclick="addRow('dataTable')" class="btn btn-primary" style="margin-top: 15px;" /><br><br>
<div class="row">
<div class="col-md-6" style="color: white;font-size: 20px;text-align: right;">Total Amount :</div>
<div class="col-md-6" style="color: white;font-size: 20px;text-align: left;">
<span class="addition"></span>
</div>
</div><br>
</code></pre>
<p>Here is my script through which I am calculating the total amount:</p>
<pre><code>var add_1 =0;
var add_2 = 0;
var mul_3 = 0;
function displayValues() {
add_1 = parseInt($('.person-1').val());
add_2 = parseInt($('.person-2').val());
mul_3 = parseInt($('.person-3').val());
$(".addition-1").text(add_1);
$(".addition-2").text(add_2);
$(".multiplication_3").text(mul_3);
$(".addition").text( mul_3 *( add_1 + add_2) );
}
$(document).ready(function(){
$(".person-1").change(displayValues);
$(".person-2").change(displayValues);
$(".person-3").change(displayValues);
});
</code></pre>
<p>Here is the code to add rooms:</p>
<pre class="lang-js prettyprint-override"><code>function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</code></pre>
| 3 | 1,996 |
Why does my method return the wrong value?
|
<p>Even though my method <em>operationsNeeded</em> prints the correct value for my return-int "count1", the very next line it returns something else to my main method. I did not include the rest of my code, if needed I'd gladly provide it.
For example if <em>operationsNeeded</em> is executed 4 times, <em>count1</em> is on 4 which is printed out as well. But for reasons unknown to me the System.out.println("check: " +count1); Statement is executed 4 times like this:<br>
<strong>check: 4<br>
check: 4<br>
check: 3<br>
check: 2</strong><br>
I would expect my program to execute this only once and then continue to the return statement. </p>
<pre><code>public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
int count =0;
while (count<testcases){
int numberOfColleagues = sc.nextInt();
sc.nextLine();
String startPieces = sc.nextLine();
int[] listOfcolleagues = listOfColleagues(numberOfColleagues, startPieces);
int count2 = operationsNeeded(listOfcolleagues, 1);
count++;
System.out.println(count2);
}
}
public static int operationsNeeded (int[] listOfColleagues, int count1){
//remove duplicates first
ArrayList<Integer> relevantList=removeDuplicatesAndSort(listOfColleagues);
System.out.println("relevantlist" + relevantList);
//check for smallestdelta & index
int [] deltaAndIndex = smallestDeltaHigherIndex(relevantList);
int delta = deltaAndIndex[0];
int index = deltaAndIndex[1];
if (delta==1){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+1);
}
}
}
if (delta>1 && delta<5){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+2);
}
}
}
if (delta>4){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+5);
}
}
}
System.out.println(count1);
int[] updatedList = new int[relevantList.size()];
for (int i=0; i<relevantList.size();i++){
updatedList[i]=relevantList.get(i);
}
if (!isAllTheSame(relevantList)) {
count1 +=1;
operationsNeeded(updatedList,count1);
}
System.out.println("check: " + count1);
return count1;
}
</code></pre>
| 3 | 1,064 |
$scope.modal remains undefined on $ionicPlatform.ready
|
<p>I've been looking everywhere for an answer to this problem; I wouldn't mind but it was actually working earlier. I'm trying to open a modal in an Ionic App on load of the app if there is no user access token stored in localStorage.</p>
<p>This is the code I'm working with:</p>
<p>JS</p>
<pre><code>.controller('LeagueCtrl', function($scope, $ionicModal, $ionicPlatform, $cordovaOauth, Spotify, Favourites) {
$scope.favourites = Favourites.all();
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
$scope.modal = modal;
console.log($scope.modal);
});
$scope.openModal = function() {
$scope.modal.show();
};
$scope.closeModal = function() {
$scope.modal.hide();
};
...
$scope.loginSpotify = function () {
$cordovaOauth.spotify('583ac6ce144e4fcb9ae9c29bf9cad5ef', ['user-read-private']).then(function(result) {
window.localStorage.setItem('spotify-token', result.access_token);
Spotify.setAuthToken(result.access_token);
$scope.updateInfo();
//$scope.closeModal();
}, function(error) {
console.log("Error -> " + error);
});
};
$scope.updateInfo = function() {
Spotify.getCurrentUser().then(function(data) {
$scope.getUserPlaylists(data.id);
}, function(error) {
$scope.loginSpotify();
});
};
$ionicPlatform.ready(function() {
var storedToken = window.localStorage.getItem('spotify-token');
if (storedToken !== null) {
Spotify.setAuthToken(storedToken);
$scope.updateInfo();
} else {
$scope.openModal();
alert('ionicPlatform ready');
}
});
})
</code></pre>
<p>HTML</p>
<pre><code><html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="css/ionic.app.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.min.js"></script>
<script src="lib/angular-spotify/dist/angular-spotify.min.js"></script>
<script src="cordova.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="share">
<ion-nav-bar class="bar-assertive">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</body>
</html>
</code></pre>
<p>As I said it was actually working before, opening the modal on startup as expected. Then it just stopped working, and producing an error I'd encountered earlier for no apparent reason. The error is as follows:</p>
<pre><code>ypeError: Cannot read property 'show' of undefined
at Scope.$scope.openModal (http://localhost:8100/js/controllers.js:24:17)
at http://localhost:8100/js/controllers.js:60:14
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:53329:19
at Object.ionic.Platform.ready (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2135:9)
at Object.self.ready (http://localhost:8100/lib/ionic/js/ionic.bundle.js:53327:26)
at new <anonymous> (http://localhost:8100/js/controllers.js:54:18)
at invoke (http://localhost:8100/lib/ionic/js/ionic.bundle.js:17762:17)
at Object.instantiate (http://localhost:8100/lib/ionic/js/ionic.bundle.js:17770:27)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:22326:28
at self.appendViewElement (http://localhost:8100/lib/ionic/js/ionic.bundle.js:56883:24) <ion-nav-view name="tab-league" class="view-container tab-content" nav-view="active" nav-view-transition="ios">
</code></pre>
<p>Any help would be appreciated massively, I can't grasp what the problem is.</p>
| 3 | 1,660 |
Why is my layout displayed wrongly on Xperia Z?
|
<p>I have a problem with layout rendering on Xperia Z. I have 2 buttons on layout which should take the size of its parent. Unfortunately, the phone can not do that. This is my layout code :</p>
<pre><code><RelativeLayout>
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="match_parent"
android:layout_height="250dp"
class="android.support.v4.view.ViewPager"
android:id="@+id/View_Pager_Layout_View_Pager"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<ImageButton
android:layout_width="50dp"
android:layout_height="50dp"
android:text="X"
android:visibility="gone"
android:layout_alignParentLeft="true"
android:id="@+id/View_Pager_Layout_Exit_Image_Button_2"/>
<ImageButton
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@android:drawable/ic_delete"
android:scaleType="fitXY"
android:background="@drawable/selector_button"
android:visibility="gone"
android:layout_alignParentRight="true"
android:id="@+id/View_Pager_Layout_Exit_Image_Button_1"/>
<RelativeLayout
android:id="@+id/View_Pager_Layout_Arrow_Left"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/View_Pager_Layout_Exit_Image_Button_2"/>
<RelativeLayout
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:background="#FF0000"
android:id="@+id/View_Pager_Layout_Arrow_Right"
android:layout_below="@+id/View_Pager_Layout_Exit_Image_Button_1"/>
<com.viewpagerindicator.CirclePageIndicator
android:id="@+id/View_Pager_Layout_View_Pager_Indicator"
android:layout_alignBottom="@+id/View_Pager_Layout_View_Pager"
android:layout_width="match_parent"
android:layout_height="30dp" android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_toRightOf="@+id/View_Pager_Layout_Arrow_Left"
android:layout_toLeftOf="@+id/View_Pager_Layout_Arrow_Right"/>
</RelativeLayout>
</code></pre>
<p><code>RelativeLayout</code>s with ID <code>View_Pager_Layout_Arrow_Left</code> and <code>View_Pager_Layout_Arrow_Right</code> are displayed wrongly.</p>
<p><img src="https://i.stack.imgur.com/ckrpe.jpg" alt="screenshot"></p>
| 3 | 1,141 |
database file can't be found
|
<p>i am trying to use dataBAseHelper class to create database file, but i cant find it on data file (it stills empty). while debugging it, it seems that onCreate method doesn't been called .
i tried different databaseHelper versions,but it didnt work.<br />
you can see my code below (MAinActivity & DataBaseHelper classes):</p>
<h3>The DatabaseHelper class</h3>
<pre><code>public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "tasks.db";
public static final String TABLE_NAME = "task_table";
public static final String ID_COL = "ID";
public static final String NAME_COL = "NAME";
public static final String CATEGORY_COL = "CATEGORY";
public static final String DURATION_COL = "DURATION";
public static final String DATETIME_COL = "DATETIME";
public static final String DESCRIPTION_COL = "DATETIME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_TASKS = "CREATE TABLE " + TABLE_NAME + "("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ NAME_COL + " TEXT, "
+ DATETIME_COL + " TEXT,"
+ DURATION_COL + " INTEGER,"
+ CATEGORY_COL + " TEXT,"
+ DESCRIPTION_COL + " TEXT " + ")";
db.execSQL(CREATE_TABLE_TASKS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME_COL,task.getName());
contentValues.put(CATEGORY_COL,task.getCategory().toString());
contentValues.put(DATETIME_COL,task.getDateTime());
contentValues.put(DURATION_COL,task.getDuration());
contentValues.put(DESCRIPTION_COL,task.getDescription());
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean updateData(String id,Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ID_COL,id);
contentValues.put(CATEGORY_COL,task.getCategory().toString());
contentValues.put(DATETIME_COL,task.getDateTime());
contentValues.put(DURATION_COL,task.getDuration());
contentValues.put(DESCRIPTION_COL,task.getDescription());
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
}
</code></pre>
<h3>The MainActivity class</h3>
<pre><code>public class MainActivity extends AppCompatActivity {
DatabaseHelper data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
data = new DatabaseHelper(this);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.item,menu);
Intent intent = new Intent(MainActivity.this, addActivity.class);
// startActivity(intent);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
Intent intent = new Intent(MainActivity.this,addActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
| 3 | 1,749 |
Freeing dynamic 2D array not working as expected in C
|
<p>When I run code like the following:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int i, count = 0x09;
int sizei = 5, sizej = 2;
int **ary = malloc (sizei * sizeof **ary);
for (i = 0; i < sizei; i++) {
*(ary + i) = malloc (sizej * sizeof *(ary + i));
**(ary + i) = ++count;
printf (" %2d |%p| +%x+ \n", i, (ary + i), *(*(ary + i)));
}
puts("----");
for (i = sizei - 1; i >= 0; i--) {
printf (" %2d |%p| +%x+ \n", i, (ary + i), *(*(ary + i)));
free (*(ary + i));
}
puts("----");
free (ary);
return 0;
}
</code></pre>
<p>I would expect that the first half would create a 2d dynamic array of ints called <code>ary</code> (i.e a pointer to a dynamically allocated array of pointers, each pointing to a dynamically allocated array of ints). The 0th element of each array <code>**(ary + i)</code> would then be recursively assigned the current value of <code>count</code>.</p>
<p>The second half would iterate in reverse, freeing each element of <code>ary</code> in the reverse it was malloc'd, followed by freeing <code>ary</code> itself.</p>
<p>This appears to work fine until I try to free <code>*(ary + 0)</code>, at which point I get a double free / corruption error. I've included the output.</p>
<pre><code> 0 |0x1d6f010| +a+
1 |0x1d6f018| +b+
2 |0x1d6f020| +c+
3 |0x1d6f028| +d+
4 |0x1d6f030| +e+
----
4 |0x1d6f030| +e+
3 |0x1d6f028| +d+
2 |0x1d6f020| +c+
1 |0x1d6f018| +b+
0 |0x1d6f010| +1d6f0b0+
*** Error in `./a.out': double free or corruption (out): 0x0000000001d6f030 ***
</code></pre>
<p>I'm curious why the 0th element of the 0th element of <code>ary</code> (i.e <code>*(*(ary + 0) + 0))</code> or just <code>**ary</code>) became what looks like some memory address (only slighly) out of bounds from what's taken up by this 2d array once it got out of the first loop.</p>
<p>And if I get rid of the second loop and just try to free <code>ary</code> directly without first freeing any of its elements I get something like:</p>
<pre><code> 0 |0x1d6f010| +a+
1 |0x1d6f018| +b+
2 |0x1d6f020| +c+
3 |0x1d6f028| +d+
4 |0x1d6f030| +e+
----
*** Error in `./a.out': free(): invalid next size (fast): 0x0000000001d6f010 ***
</code></pre>
<p>I don't understand what I've done wrong here. Would using array notation make a difference? I need any solutions to allow me to have a dynamic length of each array independant of the length of the rest of the elements of <code>ary</code> if at all possible. The number elements of <code>ary</code> wouldn't necesarily be known at compile time either. I'm using gcc 4.9 if that's relevant.</p>
| 3 | 1,098 |
Django class-based view doesn't display query result
|
<p>I'm trying to improve my <code>Django view</code> with classes in order to get a better script.</p>
<p>I don't why but I don't overcome to display query result with the new syntax. Maybe someone could help me to find a solution ?</p>
<p><strong>This is my view :</strong></p>
<pre><code>class IdentityIndividuForm(TemplateView) :
template_name= "Identity_Individu_Form.html"
model = Individu
def ID_Recherche (request) :
if 'recherche' in request.GET:
query_Nom_ID = request.GET.get('q1NomID')
query_Prenom_ID = request.GET.get('q1PrenomID')
query_DateNaissance_ID = request.GET.get('q1DateNaissanceID')
query_VilleNaissance_ID = request.GET.get('q1VilleNaissanceID')
sort_params = {}
Individu_Recherche.set_if_not_none(sort_params, 'Nom__icontains', query_Nom_ID)
Individu_Recherche.set_if_not_none(sort_params, 'Prenom__icontains', query_Prenom_ID)
Individu_Recherche.set_if_not_none(sort_params, 'DateNaissance__icontains', query_DateNaissance_ID)
Individu_Recherche.set_if_not_none(sort_params, 'VilleNaissance__icontains', query_VilleNaissance_ID)
query_ID_list = Individu_Recherche.Recherche_Filter(Individu, sort_params)
context = {
"query_Nom_ID" : query_Nom_ID,
"query_Prenom_ID" : query_Prenom_ID,
"query_DateNaissance_ID" : query_DateNaissance_ID,
"query_VilleNaissanceID" : query_VilleNaissance_ID,
"query_ID_list" : query_ID_list,
}
return render(request, 'Identity_Individu_Form.html', context)
</code></pre>
<p><strong>My url.py file :</strong></p>
<pre><code>urlpatterns = [
url(r'^Formulaire/Individus$', IdentityIndividuForm.as_view(), name="IndividuFormulaire"),
]
</code></pre>
<p><strong>And my template :</strong></p>
<pre><code><div class="subtitle-form">
<h4> <span class="glyphicon glyphicon-user"></span></span> Rechercher le n° identification d'un individu <a><span title="Outil permettant de vérifier si un individu est déjà enregistré dans la Base de Données Nationale. Saisir au minimum Nom et Prénom (entièrement ou en partie). Si la personne recherchée est trouvée, ne pas remplir le formulaire de création de fiche !"
class="glyphicon glyphicon-info-sign"></a>
</h4>
</div>
<div class="form">
<form autocomplete="off" method="GET" action="">
<input type="text" name="q1NomID" placeholder="Nom (ex:TEST) " value="{{ request.GET.q1NomID }}"> &nbsp;
<input type="text" name="q1PrenomID" placeholder="Prénom (ex:Test)" value="{{ request.GET.q1PrenomID }}"> &nbsp; <p></p>
<input id="id_search" type="text" name="q1DateNaissanceID" placeholder="Date de Naissance (YY-mm-dd) " value="{{ request.GET.q1DateNaissanceID }}"> &nbsp; <p></p>
<input id="id_search" type="text" name="q1VilleNaissanceID" placeholder="Ville de Naissance" value="{{ request.GET.q1VilleNaissanceID }}"> &nbsp; <br></br>
<input class="button" type="submit" name='recherche' value="Rechercher">&nbsp;
</form>
<br></br>
<table style="width:120%">
<tbody>
<tr>
<th>ID</th>
<th>État</th>
<th>N° Identification</th>
<th>Civilité</th>
<th>Nom</th>
<th>Prénom</th>
<th>Date de Naissance</th>
<th>Ville de Naissance</th>
<th>Pays de Naissance</th>
</tr>
{% for item in query_ID_list %}
<tr>
<td>{{ item.id}}</td>
<td>{{ item.Etat}}</td>
<td>{{ item.NumeroIdentification}}</td>
<td>{{ item.Civilite }}</td>
<td>{{ item.Nom }}</td>
<td>{{ item.Prenom }}</td>
<td>{{ item.DateNaissance }}</td>
<td>{{ item.VilleNaissance }}</td>
<td>{{ item.PaysNaissance.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</code></pre>
<p>Something is false in my script ? First time I'm trying to use Class Oriented Object.</p>
<p>Thank you !</p>
| 3 | 2,560 |
How to display images using foreach statement in asp.net?
|
<p>To better understand my problem, I will explain first my main goal for the website. My website is a music store which has 6 different brand of guitars(Ibanez, Fender, Gibson, PRS, Musicman and ESP). Now I've created a webpage where it will display the logo for each guitar brands.</p>
<p>Here is the aspx code for displaying the guitar logos:</p>
<pre><code><%@ Page Title='' Language='C#' MasterPageFile='~/MasterPage.master'
AutoEventWireup='true' CodeFile='GuitarBrands.aspx.cs'
Inherits='Pages_GuitarBrands' %>
<asp:Content ID='Content1' ContentPlaceHolderID='ContentPlaceHolder1'
Runat='Server'>
<% foreach (guitarBrand guitar in brandList) { %>
<table class="one-third">
<tr>
<th rowspan="3" class="guitarLogoHover">
<a href="<%= guitar.page%>"><img src="<%= guitar.image %>"/></a>
</th>
</tr>
</table>
<% } %>
</asp:Content>
</code></pre>
<p>Here is the aspx.cs code for displaying the guitar logos:</p>
<pre><code>public partial class Pages_GuitarBrands : System.Web.UI.Page
{
public List<guitarBrand> brandList { get; set; }
private string brandType = "Guitar";
protected void Page_Load(object sender, EventArgs e)
{
brandList = new List<guitarBrand>();
brandList = ConnectionClassBrands.GetBrandsByType(brandType);
}
</code></pre>
<p>The code above successfully displays all 6 guitar logos in the aspx webpage. Now the next thing to do is, when i click a guitar logo, lets say i click the Ibanez logo. it should open a new webpage and display guitars that are available within that brand. The tricky part is, I'm trying to create a single webpage for all guitar brands, which will serve like a template so that i don't need to have many aspx pages per guitar brand. Here is my attempt to this.</p>
<p>Firstly, in my connectionclass code where all the retrieving of data happens. I added a private string field named guitar that will retrieve the guitar brand everytime that it is iterating in the foreach loop.</p>
<p>Code 1 - Here is the new aspx code for displaying the guitar logos. As you can see below, i've created a string field named guitar in ConnectionClassGuitarItems to get the guitar brand.</p>
<pre><code><%@ Page Title='' Language='C#' MasterPageFile='~/MasterPage.master'
AutoEventWireup='true' CodeFile='GuitarBrands.aspx.cs'
Inherits='Pages_GuitarBrands' %>
<asp:Content ID='Content1' ContentPlaceHolderID='ContentPlaceHolder1'
Runat='Server'>
<% foreach (guitarBrand guitar in brandList) { %>
<table class="one-third">
<tr>
<th rowspan="3" class="guitarLogoHover">
<a href="<%= guitar.page%>"><img src="<%= guitar.image %>"/></a>
</th>
</tr>
</table>
<% ConnectionClassGuitarItems.guitar = guitar.name;%>//newly added code
<% } %>
</asp:Content>
</code></pre>
<p>Code 2 - Here is also the code for the ConnectionClassGuitarItems. The value that the field guitar get from the above. It will supplement the List GetGuitarItems() method so that it can identify what guitar products to retrieve.</p>
<pre><code>public static string guitar;
public static List<guitarItem> GetGuitarItems()
{
List<guitarItem> list2 = new List<guitarItem>();
BrandsDBEntities obj2 = new BrandsDBEntities();
list2 = (from g in obj2.guitarItems where g.brand == guitar select g).ToList();
return list2;
}
</code></pre>
<p>Code 3 - Now here is the aspx.cs code for displaying the guitar products. This is where i would store the retrieved products in another field called List guitarItemList so that i can supplement it in its aspx page.</p>
<pre><code>public partial class Pages_GuitarItems1 : System.Web.UI.Page
{
public List<guitarItem> guitarItemList { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
guitarItemList = new List<guitarItem>();
guitarItemList = ConnectionClassGuitarItems.GetGuitarItems();
}
}
</code></pre>
<p>Code 4 - And finally here is the aspx code for displaying the guitar products.</p>
<pre><code><%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="GuitarItems1.aspx.cs"
Inherits="Pages_GuitarItems1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<% foreach (guitarItem gItem in guitarItemList) { %>
<div class="one-two">
<img src="<%= gItem.itemimage1 %>"/>
<div class="content">
<div id="label"><%= gItem.brand %> <%= gItem.model %></div>
</div>
</div>
<% } %>
</asp:Content>
</code></pre>
<p><strong>Now here is the problem</strong>
It is not displaying the right guitar products according to its brand. Since i've only made a single webpage for each brand, it is only displaying ESP guitar products. For example if i click the Ibanez logo, it should display Ibanez products. But in this case, when i click the Ibanez logo, it will show ESP guitar products. Same as the other brand logos, when i click it, it will only display ESP guitar products. What is wrong with the new code that i have implemented?</p>
<p>From my understanding, the foreach loop will iterate the guitar brands in this order(Ibanez,Fender,Gibson,PRS,Musicman and ESP). Please help me guys on solving this one. I've already tried several variations but its still having the same results. </p>
| 3 | 2,002 |
Oozie custom asynchronous action
|
<p>I have a problem implementing a custom asynchronous action in Oozie. My class extends from ActionExecutor, and overwrites the methods initActionType, start, end, check, kill and isCompleted.</p>
<p>In the start method, i want to to start a YARN job, that is implemented through my BiohadoopClient class. To make the call asynchronous, i wrapped the client.run() method in a Callable:</p>
<pre><code>public void start(final Context context, final WorkflowAction action) {
...
Callable<String> biohadoop = new Callable<String>() {
BiohadoopClient client = new BiohadoopClient();
client.run();
}
// submit callable to executor
executor.submit(biohadoop);
// set the start data, according to https://oozie.apache.org/docs/4.0.1/DG_CustomActionExecutor.html
context.setStartData(externalId, callBackUrl, callBackUrl);
...
}
</code></pre>
<p>This works fine, and for example when I use my custom action in a fork/join manner, the execution of the actions runs in parallel.</p>
<p>Now, the problem is, that Oozie remains in a RUNNING state for this actions. It seems impossible to change that to a completed state. The check() method is never called by Oozie, the same is true for the end() method. It doesn't help to set the context.setExternalStatus(), context.setExecutionData() and context.setEndData() manually in the Callable (after the client.run() has finished). I tried also to queue manually an ActionEndXCommand, but without luck.</p>
<p>When I wait in the start() method for the Callable to complete, the state gets updated correctly, but the execution in fork/join isn't parallel anymore (which seem logic, as the execution waits for the Callable to complete).</p>
<p><a href="https://stackoverflow.com/questions/20671386/how-external-clients-notify-oozie-workflow-with-http-callback/20680301#20680301">How external clients notify Oozie workflow with HTTP callback</a> didn't help, as using the callback seems to change nothing (well, I can see that it happened in the log files, but beside from that, nothing...). Also, the answer mentioned, that the SSH action runs asynchronously, but I haven't found out how this is done. There is some wrapping inside a Callable, but at the end, the call() method of the Callable is invoked directly (no submission to an Executor).</p>
<p>So far I haven't found any example howto write an asynchronous custom action. Can anybody please help me?</p>
<p>Thanks</p>
<p><strong>Edit</strong></p>
<p>Here are the implementations of initActionType(), start(), check(), end(), the callable implementation can be found inside the start() action.</p>
<p>The callable is submitted to an executor in the start() action, after which its shutdown() method is invoked - so the executor shuts down after the Callable has finished. As next step, context.setStartData(externalId, callBackUrl, callBackUrl) is invoked. </p>
<pre><code>private final AtomicBoolean finished = new AtomicBoolean(false);
public void initActionType() {
super.initActionType();
log.info("initActionType() invoked");
}
public void start(final Context context, final WorkflowAction action)
throws ActionExecutorException {
log.info("start() invoked");
// Get parameters from Node configuration
final String parameter = getParameters(action.getConf());
Callable<String> biohadoop = new Callable<String>() {
@Override
public String call() throws Exception {
log.info("Starting Biohadoop");
// No difference if check() is called manually
// or if the next line is commented out
check(context, action);
BiohadoopClient client = new BiohadoopClient();
client.run(parameter);
log.info("Biohadoop finished");
finished.set(true);
// No difference if check() is called manually
// or if the next line is commented out
check(context, action);
return null;
}
};
ExecutorService executor = Executors.newCachedThreadPool();
biohadoopResult = executor.submit(biohadoop);
executor.shutdown();
String externalId = action.getId();
String callBackUrl = context.getCallbackUrl("finished");
context.setStartData(externalId, callBackUrl, callBackUrl);
}
public void check(final Context context, final WorkflowAction action)
throws ActionExecutorException {
// finished is an AtomicBoolean, that is set to true,
// after Biohadoop has finished (see implementation of Callable)
if (finished.get()) {
log.info("check(Context, WorkflowAction) invoked -
Callable has finished");
context.setExternalStatus(Status.OK.toString());
context.setExecutionData(Status.OK.toString(), null);
} else {
log.info("check(Context, WorkflowAction) invoked");
context.setExternalStatus(Status.RUNNING.toString());
}
}
public void end(Context context, WorkflowAction action)
throws ActionExecutorException {
log.info("end(Context, WorkflowAction) invoked");
context.setEndData(Status.OK, Status.OK.toString());
}
</code></pre>
| 3 | 1,655 |
Modify a <p> element in a list, with jQuery
|
<p>I'm coming back here because I'm not able to do what I want. I have a nav menu, with three 'li' in one 'ul', each containing a <p> element, with the nav name.
I already have a script which hides divs and show the corresponding one, containing project thumbnails. What I would like to do, is to distinguish which nav element is active, by modifying it when it has been clicked.</p>
<p>I gave a try to modify the string of the <p> element to add a dash "-" or a point • to distinguish which was the active menu but I'm not too good with jQuery yet to manipulate a "p" in a "li" in a "ul" effectively.</p>
<p>Here is my html :</p>
<pre><code><section id="content">
<p class="section_title"> WORK </p>
<div id="sections">
<ul>
<li class="section" data-grid="grid1"><p class="navigation" style="cursor : pointer;"> Product</p></li>
<li class="section" data-grid="grid2"><p class="navigation" style="cursor : pointer;"> Mobility</p></li>
<li class="section" data-grid="grid3"><p class="navigation" style="cursor : pointer;"> Arcade Sticks</p></li>
<!-- <li class="section" data-grid="grid4"><p style="cursor : pointer;">. Infography</p></li> -->
</ul>
</div>
<!-- PROJECT GRID -->
<div id="project_grid">
<!-- PRODUCT PROJECTS -->
<div id="grid1" class="grid">
<a href="projects/product/jorislaarman.html" style="background:url('assets/img/thumbnails/jorislaarman.png')"></a>
<a href="projects/product/ptitlouis.html" style="background:url('assets/img/thumbnails/ptitlouis.png')"></a>
<a href="projects/product/diwel.html" style="background:url('assets/img/thumbnails/diwel.png')"></a>
<a href="projects/product/wirquin.html" style="background:url('assets/img/thumbnails/wirquin.png')"></a>
<a href="projects/product/ulna.html" style="background:url('assets/img/thumbnails/ulna.png')"></a>
<a href="projects/product/envol.html" style="background:url('assets/img/thumbnails/envol.png')"></a>
</div>
</code></pre>
<p>There are other grids following, each manipulated by the jQuery, here :</p>
<pre><code>$("#project_grid div:not(#grid1)").hide();
$('.section').click(function() {
$('.grid').hide();
$('#' + $(this).data('grid')).show();
});
</code></pre>
<p>I tried several things with the jQuery there, without alterating the original script, to at least underline the clicked <p> element, such as :</p>
<pre><code>$('.navigation').click(function(){
$('p').css("text-decoration","underlined");
});
</code></pre>
<p>and : </p>
<pre><code>$('p').clicked(function(){
$(this).css('text-decoration','underlined');
});
</code></pre>
<p>But none of this works :/ And I can't really figure it out.</p>
<p>I also tried to modify the <p> string, with .append, but I couldn't figure it out ether...</p>
<p>I'd just like to do something simple. Either underline the active nav section, either add a "•" before product, mobility, or arcade stick section when they have been clicked. And of course disappear when another one is clicked.</p>
<p><a href="http://jsfiddle.net/g32Vm/" rel="nofollow">http://jsfiddle.net/g32Vm/</a></p>
<p>Thanks for your help !</p>
| 3 | 1,403 |
What is the purpose of creating "Mappings" in CloudFormation?
|
<p>See the code below:</p>
<pre><code>Mappings:
RegionMap:
us-east-1:
bucketname: s3bucketname-us-east-1
us-east-2:
bucketname: s3bucketname-us-east-2
us-west-1:
bucketname: s3bucketname-us-west-1
us-west-2:
bucketname: s3bucketname-us-west-2
ap-south-1:
bucketname: s3bucketname-ap-south-1
ap-northeast-2:
bucketname: s3bucketname-ap-northeast-2
ap-southeast-1:
bucketname: s3bucketname-ap-southeast-1
ap-southeast-2:
bucketname: s3bucketname-ap-southeast-2
ap-northeast-1:
bucketname: s3bucketname-ap-northeast-1
ca-central-1:
bucketname: s3bucketname-ca-central-1
eu-central-1:
bucketname: s3bucketname-eu-central-1
eu-west-1:
bucketname: s3bucketname-eu-west-1
eu-west-2:
bucketname: s3bucketname-eu-west-2
eu-west-3:
bucketname: s3bucketname-eu-west-3
eu-north-1:
bucketname: s3bucketname-eu-north-1
sa-east-1:
bucketname: s3bucketname-east-1
af-south-1:
bucketname: s3bucketname-south-1
ap-east-1:
bucketname: s3bucketname-east-1
ap-northeast-3:
bucketname: s3bucketname-ap-northeast-3
eu-south-1:
bucketname: s3bucketname-eu-south-1
me-south-1:
bucketname: s3bucketname-me-south-1
Resources:
StateS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "cfntf-${AWS::Region}-${AWS::AccountId}"
</code></pre>
<p>There is more to this code however I've only included the relevant snippets for the question.</p>
<p>To summarize - why include mappings for bucketname when the bucketname is set directly, using region and account ID in the 'Resources' section?</p>
<p>There is use of the <code>Fn::FindInMap</code> function which is used here as part of the <code>ExecutorLambdaFunction</code>:</p>
<pre><code>ExecutorLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: myfunction
Handler: index.handler
Role: !GetAtt ExecutorLambdaServiceRole.Arn
Environment:
Variables:
BUCKET: !Ref StateS3Bucket
Code:
S3Bucket: !If
- S3Defined
- !Ref S3Bucket
- Fn::FindInMap:
- RegionMap
- !Ref AWS::Region
- bucketname
S3Key: !If
- S3Defined
- !Ref S3Key
- /app.zip
Runtime: python3.8
</code></pre>
| 3 | 1,575 |
RadioGroup not updating bound value
|
<p>I am using a <code>radiogroup</code> in my form, and I noticed that when I select one of the radio buttons, the value (bound value) is not updated.</p>
<p>Here's a small example:</p>
<pre><code>Ext.create({
xtype: 'container',
renderTo: Ext.getBody(),
items: [{
xtype: 'formpanel',
viewModel: {
data: {
myValue: 3
}
},
items: [{
xtype: 'displayfield',
label: 'This is the value of myValue:',
bind: '{myValue}'
}, {
xtype: 'textfield',
label: 'Update myValue:',
bind: '{myValue}'
}, {
xtype: 'radiogroup',
vertical: true,
label: 'Click a radio button:',
bind: '{myValue}',
items: [{
label: 'One',
value: 1
}, {
label: 'Two',
value: 2
}, {
label: 'Three',
value: 3
}, ]
}]
}]
});
</code></pre>
<p>I created a simple <code>viewModel</code> with one data value: <code>myValue: 3</code>. This is bound to all of the form elements: the <code>radiogroup</code>, a <code>textfield</code>, and a <code>displayfield</code>.</p>
<p>I'd expect that when I click one of the radio buttons, that the <code>displayfield</code> would update its value. The <code>displayfield</code> value is updated when you type into the <code>textfield</code>, but the <code>radiogroup</code> is not updated.</p>
<p>It seems like the <code>radiogroup</code> is only using its bound value when it initializes, but it doesn't notice when it gets updated nor does it update it on its own.</p>
<p>What am I doing wrong? Why doesn't the bound value get updated when I click on a radio button?</p>
<p>Here's an example over on Sencha Fiddle: <a href="https://fiddle.sencha.com/#view/editor&fiddle/389i" rel="nofollow noreferrer">https://fiddle.sencha.com/#view/editor&fiddle/389i</a></p>
<hr />
<p>UPDATE: I found a solution adding a <code>change</code> listener to the <code>radiogroup</code>. Well, this fixes updating <code>myValue</code> wen you click on a radio button. I'd need another listener to update the <code>radiogroup</code> when <code>myValue</code> is updated elsewhere (like in the <code>textfield</code>).</p>
<p>This works for my needs, but why should I need to add a <code>change</code> listener? Why doesn't the <code>radiogroup</code> bind to <code>{myValue}</code> correctly?</p>
<pre><code>listeners: {
change: function(field, val) {
let vm = field.lookupViewModel();
vm.set('myValue', val);
}
}
</code></pre>
<p>Here's a fiddle with this update applied: <a href="https://fiddle.sencha.com/#view/editor&fiddle/389k" rel="nofollow noreferrer">https://fiddle.sencha.com/#view/editor&fiddle/389k</a></p>
| 3 | 1,247 |
Spring MVC4 Session Management
|
<p>I am developing a small spring project in which the login page has two type of users admin and staff. on login attempt i want to apply session using spring MVC4 and also wants to open jsp based on the user role(Admin or Staff).
the session has four/five fields like name,id,role,SessionId. i want these information to travel through the jsp pages. But i don't want to do this using url parameter passing. </p>
<p>I don't know how to do this because i am new in spring and this is my first project. Help me Please.
If someone can provide me the sample code and guide me on this then it would be very helpfull.</p>
<p>// Login.jsp code</p>
<pre><code>var MobileNo=$('#mobno').val();
var StaffPwd=$('#pwd').val();
$.ajax
(
{
url: "http://localhost:8080/OnlineStore/kmsg/grocery/Login",
type: "POST",
data: {MobileNo: MobileNo,StaffPwd: StaffPwd},
success: function(data)
{
var vUserRole = data["UserRole"];
var vUserName = data["UserName"];
if(data==="")
{
alert("Login Failed");
}
else
{
if(vUserRole == "Admin")
{
alert("Login Success: " + vUserName);
window.location.href = "http://localhost:8080/OnlineStore/JspPages/City.jsp";
}
if(vUserRole == "CityAdmin")
{
alert("Login Success: " + vUserName);
window.location.href = "http://localhost:8080/OnlineStore/JspPages/Locality.jsp";
}
if(vUserRole == "Staff")
{
alert("Login Success: " + vUserName);
window.location.href = "http://localhost:8080/OnlineStore/JspPages/CustomerOrder.jsp";
}
}
},
error: function(e)
{
alert('Error:' +e)
}
}
);
</code></pre>
<p>// this is controller code</p>
<pre><code> @RequestMapping("/Login")
public @ResponseBody UserServiceModel selectStaff(@RequestParam Map<String,String> requestParams) throws Exception
{
String MobileNo = requestParams.get("MobileNo");
String StaffPwd = requestParams.get("StaffPwd");
return staffAdapter.login(MobileNo, StaffPwd);
}
--------------
</code></pre>
<hr>
| 3 | 1,638 |
Windows Server 2012 IIS8 Performance over Server 2003 IIS6, Sporadic slowness with WebService
|
<p>We had a few .NET 1.1 projects hosted on IIS6 in Server 2003. I was tasked with porting these projects to .NET 4.0 and host them on new Server 2012 VM's. Ported the code and getting it to run on Server 2012 IIS8 was no problem, but I started seeing performance problems throughout the day and they would over time resolve themselves. I have the APP Pools set to recycle every 4 hours, so I can't see it being an unhealthy app pool.</p>
<p>The config of the app pool is as follows;</p>
<p>Managed Pipeline Mode: Classic Mode
Start Mode: Always Running
Enable 32-bit Applications: True
Memory Limit: 0 (Unlimited)</p>
<p>The OS config is as follows;</p>
<p>Server 2012
Dedicated web server, no other services running.
4 virtual processors
10gb Ram
10gb Virtual NIC</p>
<p>For the webservice itself, its a simple webservice that hits a database and it also calls another webservice hosted on the same web server. I have the hostname listed in the host file, so its not doing a DNS lookup. The database is pretty much sitting idle. To give you an idea on how often this service is utilized, we had about 40k web service calls yesterday.</p>
<p>I wrote a program that tested the web service every 10 seconds for a 24 hour period. The results were kind of interesting. The times listed below are when the response times were slow and the "slow" was always consistent. The slow response times were about 6000ms, or 6 seconds. The time in between the times listed below were 200ms, or .2 seconds. </p>
<p>8:18AM - 8:36AM – 18 minutes</p>
<p>9:02AM - 9:10AM – 8 minutes</p>
<p>9:36AM - 9:47AM – 11 minutes</p>
<p>10:17AM - 10:26AM – 9 minutes</p>
<p>10:41AM - 10:56AM – 14 minutes</p>
<p>11:16AM - 11:22AM – 6 minutes</p>
<p>11:48AM - 11:56AM – 8 minutes</p>
<p>12:23PM - 12:31PM – 8 minutes</p>
<p>12:53PM - 1:00PM – 7 minutes</p>
<p>1:07PM - 1:19PM – 12 minutes </p>
<p>1:41PM - 1:47PM – 6 minutes</p>
<p>2:03PM - 2:52PM – 49 minutes</p>
<p>3:15PM - 3:34PM – 19 minutes</p>
<p>3:57PM - 4:02PM – 6 minutes</p>
<p>4:20PM - 4:26PM – 6 minutes </p>
<p>4:35PM - 4:56PM – 21 minutes</p>
<p>5:17PM - 5:25PM – 8 minutes</p>
<p>6:02PM - 6:16PM – 14 minutes</p>
<p>6:49PM - 7:00PM – 11 minutes</p>
<p>7:41PM - 7:55PM – 14 minutes </p>
<p>8:36PM - 8:51PM – 16 minutes </p>
<p>9:31PM - 9:45PM - 14 minutes</p>
<p>10:26PM - 10:41PM – 15 minutes</p>
<p>11:25PM - 11:41PM – 16 minutes</p>
<p>12:28AM - 12:45AM – 17 minutes</p>
<p>1:34AM - 1:53AM – 19 minutes</p>
<p>2:42AM - 3:02AM – 20 minutes</p>
<p>3:49AM - 4:08AM – 19 minutes</p>
<p>5:01AM - 5:15AM – 14 minutes</p>
<p>6:03AM - 6:22AM – 19 minutes</p>
<p>7:12AM - 7:28AM – 16 minutes</p>
<p>8:07AM - 8:18AM – 11 minutes</p>
<p>I can't find the culprit of the slow downs. We did not have any performance problems hosting on iis6, so it can't be the database.</p>
<p>Thoughts? </p>
| 3 | 1,100 |
Kendo Grid AJAX Bound Not Updating MVC4
|
<p>I am trying to get my grid to update for the opt-in status, but when I hit update no action occurs. I an using ajax binding with a model and entity framework. When I hit cancel it will follow this method. I am not sure what I am missing as everything else functions and compiles. </p>
<p>View </p>
<pre><code><div class="row">
<h2>PQA Opt-In</h2>
<br />
@(Html.Kendo().Grid<TelerikMvcApp1.Models.PQAViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(opt => opt.Jobber).Width(90);
columns.Bound(opt => opt.Dealer).Width(95);
columns.Bound(opt => opt.OptInd).Width(110);
columns.Bound(opt => opt.establish_date_time);
columns.Bound(opt => opt.establish_id);
columns.Command(commands =>
{
commands.Edit();
}).Title("Commands").Width(200);
})
.DataSource(datasource => datasource
.Ajax()
.Model(model =>
{
model.Id(opt => opt.Jobber);
model.Field(opt => opt.Jobber).Editable(false);
model.Field(opt => opt.Dealer).Editable(false);
model.Field(opt => opt.establish_date_time).Editable(false);
model.Field(opt => opt.establish_id).Editable(false);
})
.PageSize(20)
.Read(read => read.Action("ProductQualityFileFull_Read", "PQA"))
.Update(update => update.Action("Opt_Update", "PQA"))
)
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Filterable()
.Pageable()
)
</div>
</code></pre>
<p>Controller </p>
<pre><code>sing System;
using System.Linq;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using TelerikMvcApp1.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
namespace TelerikMvcApp1.Controllers
{
public class PQAController : Controller
{
public ActionResult Baseline()
{
return View();
}
public ActionResult ProductQualityFileFull_Read([DataSourceRequest] DataSourceRequest
request)
{
using (var pqa = new PQAEntities())
{
IQueryable<ProductQualityFileFull> opt = pqa.ProductQualityFileFulls;
DataSourceResult result = opt.ToDataSourceResult(request, ProductQualityFileFull =>
new PQAViewModel
{
Jobber = ProductQualityFileFull.Jobber,
Dealer = ProductQualityFileFull.Dealer,
OptInd = ProductQualityFileFull.OptInd,
establish_date_time = ProductQualityFileFull.establish_date_time,
establish_id = ProductQualityFileFull.establish_id
});
return Json(result);
}
}
public ActionResult UpdateOptIn()
{
return View();
}
public ActionResult Opt_Update([DataSourceRequest] DataSourceRequest request,
PQAViewModel opt)
{
if (ModelState.IsValid)
{
using (var pqa = new PQAEntities())
{
var entity = new ProductQualityFileFull
{
Jobber = opt.Jobber,
Dealer = opt.Dealer,
OptInd = opt.OptInd,
establish_date_time = opt.establish_date_time,
establish_id = opt.establish_id
};
pqa.ProductQualityFileFulls.Attach(entity);
pqa.Entry(entity).State = EntityState.Modified;
pqa.SaveChanges();
}
}
return Json(new[] { opt }.ToDataSourceResult(request, ModelState));
}
}
}
</code></pre>
<p>Model </p>
<pre><code>namespace TelerikMvcApp1.Models
{
public class PQAViewModel
{
public string Jobber { get; set; }
public int Dealer { get; set; }
public int OptInd { get; set; }
public DateTime establish_date_time { get; set; }
public string establish_id { get; set; }
}
}
</code></pre>
| 3 | 1,979 |
Cannot set ImageView by Capture Camera from Intent.createChooser
|
<p>Im reaching the way how to set image for ImageView from Camera or Gallery without using AlertDialog or handle two buttons for too intent.</p>
<p>So, I found the Intent.createChooser from <a href="https://gist.github.com/Mariovc/f06e70ebe8ca52fbbbe2" rel="nofollow noreferrer">https://gist.github.com/Mariovc/f06e70ebe8ca52fbbbe2</a> or <a href="https://stackoverflow.com/questions/4455558/allow-user-to-select-camera-or-gallery-for-image/12347567#12347567">Allow user to select camera or gallery for image</a></p>
<p>Everything working perfect when i was selected image from Gallery, but from Camera , always RunExceptionError.</p>
<p>Here are my classes:
MainActivity.class</p>
<pre><code>public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_ID = 234;
ImageView image;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
onPickImage(v);
}catch (IOException e){e.printStackTrace();}
}
});
}
public void onPickImage(View view) throws IOException{
Intent chooseIntent = ImagePicker.getPickImageIntent(this);
startActivityForResult(chooseIntent,PICK_IMAGE_ID);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,Intent data) {
switch (requestCode){
case PICK_IMAGE_ID:
Bitmap bitmap = ImagePicker.getImageFromResult(this, resultCode, data);
image.setImageBitmap(bitmap);
}
}
}
</code></pre>
<p>ImagePicker.java</p>
<pre><code>public class ImagePicker {
private static final int DEFAULT_MIN_WIDTH_QUALITY = 400; // min pixels
private static final String TAG = "ImagePicker";
private static final String TEMP_IMAGE_NAME = "tempImage";
public static int minWidthQuality = DEFAULT_MIN_WIDTH_QUALITY;
public static Intent getPickImageIntent(Context context) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent pickIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra("return-data", true);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
intentList = addIntentsToList(context, intentList, pickIntent);
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
context.getString(R.string.pick_image_intent_text));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
list.add(targetedIntent);
Log.d(TAG, "Intent: " + intent.getAction() + " package: " + packageName);
}
return list;
}
public static Bitmap getImageFromResult(Context context, int resultCode,
Intent imageReturnedIntent) {
Log.d(TAG, "getImageFromResult, resultCode: " + resultCode);
Bitmap bm = null;
File imageFile = getTempFile(context);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage;
boolean isCamera = imageReturnedIntent == null;
if (isCamera) { /** CAMERA **/
selectedImage = Uri.fromFile(imageFile);
} else { /** ALBUM **/
selectedImage = imageReturnedIntent.getData();
}
Log.d(TAG, "selectedImage: " + selectedImage);
bm = getImageResized(context, selectedImage);
int rotation = getRotation(context, selectedImage, isCamera);
bm = rotate(bm, rotation);
}
return bm;
}
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private static Bitmap decodeBitmap(Context context, Uri theUri, int sampleSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
Log.d(TAG, options.inSampleSize + " sample method bitmap ... " +
actuallyUsableBitmap.getWidth() + " " + actuallyUsableBitmap.getHeight());
return actuallyUsableBitmap;
}
/**
* Resize to avoid using too much memory loading big images (e.g.: 2560*1920)
**/
private static Bitmap getImageResized(Context context, Uri selectedImage) {
Bitmap bm = null;
int[] sampleSizes = new int[]{5, 3, 2, 1};
int i = -1;
do {
i++;
bm = decodeBitmap(context, selectedImage, sampleSizes[i]);
Log.d(TAG, "resizer: new bitmap width = " + bm.getWidth());
} while (bm.getWidth() < minWidthQuality && i < sampleSizes.length);
return bm;
}
private static int getRotation(Context context, Uri imageUri, boolean isCamera) {
int rotation;
if (isCamera) {
rotation = getRotationFromCamera(context, imageUri);
} else {
rotation = getRotationFromGallery(context, imageUri);
}
Log.d(TAG, "Image rotation: " + rotation);
return rotation;
}
private static int getRotationFromCamera(Context context, Uri imageFile) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageFile, null);
ExifInterface exif = new ExifInterface(imageFile.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
public static int getRotationFromGallery(Context context, Uri imageUri) {
String[] columns = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (cursor == null) return 0;
cursor.moveToFirst();
int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
return cursor.getInt(orientationColumnIndex);
}
private static Bitmap rotate(Bitmap bm, int rotation) {
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Bitmap bmOut = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
return bmOut;
}
return bm;
}
}
</code></pre>
<p>And here is the LogCat:</p>
<pre><code>10-10 22:30:13.038 27208-27208/com.example.tri.intentchooser W/System﹕ ClassLoader referenced unknown path: /data/app/com.example.tri.intentchooser-2/lib/arm
10-10 22:30:13.156 27208-27223/com.example.tri.intentchooser D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-10 22:30:13.430 27208-27223/com.example.tri.intentchooser I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 09/02/15, 76f806e, Ibddc658e36
10-10 22:30:13.468 27208-27223/com.example.tri.intentchooser I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-10 22:30:38.589 27208-27208/com.example.tri.intentchooser D/ImagePicker﹕ Intent: android.intent.action.PICK package: com.google.android.apps.photos
10-10 22:30:38.590 27208-27208/com.example.tri.intentchooser D/ImagePicker﹕ Intent: android.media.action.IMAGE_CAPTURE package: com.google.android.GoogleCamera
10-10 22:30:38.620 27208-27215/com.example.tri.intentchooser W/art﹕ Suspending all threads took: 25.571ms
10-10 22:30:39.827 27208-27223/com.example.tri.intentchooser E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xaefbc490
10-10 22:30:48.058 27208-27208/com.example.tri.intentchooser D/ImagePicker﹕ getImageFromResult, resultCode: -1
10-10 22:30:48.074 27208-27208/com.example.tri.intentchooser D/ImagePicker﹕ selectedImage: null
10-10 22:30:48.082 27208-27208/com.example.tri.intentchooser D/AndroidRuntime﹕ Shutting down VM
10-10 22:30:48.098 27208-27208/com.example.tri.intentchooser E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.tri.intentchooser, PID: 27208
java.lang.RuntimeException: Unable to resume activity {com.example.tri.intentchooser/com.example.tri.intentchooser.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=234, result=-1, data=Intent { }} to activity {com.example.tri.intentchooser/com.example.tri.intentchooser.MainActivity}: java.lang.NullPointerException: uri
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3103)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=234, result=-1, data=Intent { }} to activity {com.example.tri.intentchooser/com.example.tri.intentchooser.MainActivity}: java.lang.NullPointerException: uri
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3089)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: uri
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:922)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:865)
at com.example.tri.intentchooser.ImagePicker.decodeBitmap(ImagePicker.java:110)
at com.example.tri.intentchooser.ImagePicker.getImageResized(ImagePicker.java:133)
at com.example.tri.intentchooser.ImagePicker.getImageFromResult(ImagePicker.java:90)
at com.example.tri.intentchooser.MainActivity.onActivityResult(MainActivity.java:62)
at android.app.Activity.dispatchActivityResult(Activity.java:6428)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3089)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code></pre>
<p>I had look for <code>"Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=234, result=-1, data=Intent { }} to activity"</code> but not luck for it, also it may relating to the log <code>selectedImage = NULL</code>.</p>
<p>Please show me any idea or advise for it.
Thanks.</p>
| 3 | 5,923 |
phonegap - should navigator work in the browser?
|
<p>I'm just trying to get phonegap/cordova working. Should the Navigator's function be working in the android emulator? When i do the geolocation getcurrentposition function, it doesn't do anything. </p>
<p>When i try the navigator.notification.alert() in the browser and emulator, it doesn't work. It says that navigator.notification.alert() isn't defined. </p>
<p>I have no idea what the problem is. I would have figured it would have at least shown a browser alert. </p>
<p>My manifest is below. </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.timetracker2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.timetracker2.MainActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="org.apache.cordova.DroidGap"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<intent-filter></intent-filter>
</activity>
</application>
</manifest>
</code></pre>
| 3 | 1,285 |
JIT deoptimization, reason="constraint". Why JIT deoptimizes method?
|
<p>could someone point me in direction which might lead me to get why JIT deoptimizes my loop? (OSR). It looks like it gets compiled once by C1 and then its deoptimized multiple times (I can see tens or maybe hundred logs which starts with <deoptimized...>)</p>
<p>This is the class which contains that important loop:</p>
<pre class="lang-java prettyprint-override"><code>@SynchronizationRequired
public class Worker implements Runnable
{
private static final byte NOT_RUNNING = 0, RUNNING = 1, SHUTDOWN = 2, FORCE_SHUTDOWN = 3;
private static final AtomicIntegerFieldUpdater<Worker> isRunningFieldUpdater =
AtomicIntegerFieldUpdater.newUpdater(Worker.class, "isRunning");
private volatile int isRunning = NOT_RUNNING;
private final Queue<FunkovConnection> tasks = new SpscUnboundedArrayQueue<>(512);
/**
* Executing tasks from queue until closed.
*/
@Override
public void run()
{
if (isRunning())
{
return;
}
while (notClosed())
{
FunkovConnection connection = tasks.poll();
if (null != connection)
{
connection.run();
}
}
if (forceShutdown())
{
setNonRunning();
return;
}
FunkovConnection connection;
while ((connection = tasks.poll()) != null)
{
connection.run();
}
setNonRunning();
}
public void submit(FunkovConnection connection)
{
tasks.add(connection);
}
/**
* Shutdowns worker after it finish processing all pending tasks on its queue
*/
public void shutdown()
{
isRunningFieldUpdater.compareAndSet(this, RUNNING, SHUTDOWN);
}
/**
* Shutdowns worker after it finish currently processing task. Pending tasks on queue are not handled
*/
public void shutdownForce()
{
isRunningFieldUpdater.compareAndSet(this, RUNNING, FORCE_SHUTDOWN);
}
private void setNonRunning()
{
isRunningFieldUpdater.set(this, NOT_RUNNING);
}
private boolean forceShutdown()
{
return isRunningFieldUpdater.get(this) == FORCE_SHUTDOWN;
}
private boolean isRunning()
{
return isRunningFieldUpdater.getAndSet(this, RUNNING) == RUNNING;
}
public boolean notClosed()
{
return isRunningFieldUpdater.get(this) == RUNNING;
}
}
</code></pre>
<p>JIT logs:</p>
<pre class="lang-none prettyprint-override"><code> 1. <task_queued compile_id='535' compile_kind='osr' method='Worker run ()V' bytes='81' count='1' backedge_count='60416' iicount='1' osr_bci='8' level='3' stamp='0,145' comment='tiered' hot_count='60416'/>
2. <nmethod compile_id='535' compile_kind='osr' compiler='c1' level='3' entry='0x00007fabf5514ee0' size='5592' address='0x00007fabf5514c10' relocation_offset='344' insts_offset='720' stub_offset='4432' scopes_data_offset='4704' scopes_pcs_offset='5040' dependencies_offset='5552' nul_chk_table_offset='5560' oops_offset='4624' metadata_offset='4640' method='Worker run ()V' bytes='81' count='1' backedge_count='65742' iicount='1' stamp='0,146'/>
3. <deoptimized thread='132773' reason='constraint' pc='0x00007fabf5515c24' compile_id='535' compile_kind='osr' compiler='c1' level='3'>
<jvms bci='37' method='Worker run ()V' bytes='81' count='1' backedge_count='68801' iicount='1'/>
</deoptimized>
4. <deoptimized thread='132773' reason='constraint' pc='0x00007fabf5515c24' compile_id='535' compile_kind='osr' compiler='c1' level='3'>
<jvms bci='37' method='Worker run ()V' bytes='81' count='1' backedge_count='76993' iicount='1'/>
</deoptimized>
5.<deoptimized thread='132773' reason='constraint' pc='0x00007fabf5515c24' compile_id='535' compile_kind='osr' compiler='c1' level='3'>
<jvms bci='37' method='Worker run ()V' bytes='81' count='1' backedge_count='85185' iicount='1'/>
</deoptimized>
6. <deoptimized thread='132773' reason='constraint' pc='0x00007fabf5515c24' compile_id='535' compile_kind='osr' compiler='c1' level='3'>
<jvms bci='37' method='Worker run ()V' bytes='81' count='1' backedge_count='93377' iicount='1'/>
</deoptimized>
</code></pre>
<p>Two questions here:</p>
<ol>
<li>What could be the reason for deoptimization? "constraint" seems not that meaningful to me</li>
<li>Why there is so many logs about deoptimization, not just one? It look likes it's compiled once but decompiled multipile times</li>
</ol>
| 3 | 1,879 |
Javasript function to change a HTML class of a <div>, render, then continue running the rest of the function code
|
<p>I am learning programming HTML/CSS/Javascript. I created a webpage and a javascript code to get some information within an Access database then render it to user. It is a big table sometimes.
I just want to update a class and an innerHTML at the beginning and in the end of the code, in order to show to the user: "Wait, page is loading"... and after the code runs, change the class and innerHTML to nothing ("") then the message to user would disappear.</p>
<p>I did the code, but when my function runs, it is not rendering the changes to class and innerHTML until the functions is finished... </p>
<p>JUST FOR INFORMATION: At this point, the HTML is already rendered. The Javascript will act from a button click on the page.</p>
<p>My HTML - The classes and innerHTML I want to update with Javascript code.</p>
<pre><code> <section>
<div id="RunningCode" class="">
<span id="RunningCode1" class=""></span>
</div>
</section>
</code></pre>
<p>My JAVASCRIPT CODE in the beginning of the function. (This is what I want to render/update before the code continue</p>
<pre><code>var YellowCard = document.getElementById("RunningCode");
YellowCard.className = "mensagemCodeRunning";
var YellowCard1 = document.getElementById("RunningCode1");
YellowCard1.className = "mensagemCodeRunningText";
YellowCard1.innerHTML = "Loading. Please Wait..."
</code></pre>
<p>Then My JAVASCRIPT CODE in the end of the function:</p>
<pre><code>YellowCard1.className = "";
YellowCard1.innerHTML = ""
YellowCard.className = "";
</code></pre>
<p>FULL JAVASCRIPT CODE:</p>
<pre><code>function getSpecificSupplier()
{
var YellowCard = document.getElementById("RunningCode");
YellowCard.className = "mensagemCodeRunning";
var YellowCard1 = document.getElementById("RunningCode1");
YellowCard1.className = "mensagemCodeRunningText";
YellowCard1.innerHTML = "Loading. Please Wait..."
var Carrier_Name = Carrier_NameHTML.value;
var cn = new ActiveXObject("ADODB.Connection");
var strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = MySource;
var rs = new ActiveXObject("ADODB.Recordset");
var SQL = "select * from ...
cn.Open(strConn);
rs.Open(SQL, cn);
var Linhas_da_Tabela = document.getElementById("Apagando");
while(Linhas_da_Tabela.firstChild) {
Linhas_da_Tabela.removeChild(Linhas_da_Tabela.firstChild);
}
while (!rs.eof) {
var table = document.getElementById("mytable");
var row = table.insertRow(-1);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
var cell8 = row.insertCell(8);
cell0.innerHTML = rs1
cell1.innerHTML = rs2
cell2.innerHTML = rs3
cell3.innerHTML = rs4
var WholeDate = new Date(rs("Arrival Time"));
var dd = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getDate());
var mm = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMonth()+1);
var yyyy = WholeDate.getFullYear();
var hh = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getHours());
var min = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMinutes());
cell4.innerHTML = "" + mm + "-" + dd + "-" + yyyy + " " + hh + ":" + min + "h";
var WholeDate = new Date(rs("Gate IN"));
var dd = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getDate());
var mm = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMonth()+1);
var yyyy = WholeDate.getFullYear();
var hh = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getHours());
var min = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMinutes());
cell5.innerHTML = "" + mm + "-" + dd + "-" + yyyy + " " + hh + ":" + min + "h";
var WholeDate = new Date(rs("Dock IN"));
var dd = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getDate());
var mm = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMonth()+1);
var yyyy = WholeDate.getFullYear();
var hh = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getHours());
var min = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMinutes());
cell6.innerHTML = "" + mm + "-" + dd + "-" + yyyy + " " + hh + ":" + min + "h";
var WholeDate = new Date(rs("Dock OUT"));
var dd = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getDate());
var mm = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMonth()+1);
var yyyy = WholeDate.getFullYear();
var hh = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getHours());
var min = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMinutes());
cell7.innerHTML = "" + mm + "-" + dd + "-" + yyyy + " " + hh + ":" + min + "h";
var WholeDate = new Date(rs("Gate OUT"));
var dd = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getDate());
var mm = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMonth()+1);
var yyyy = WholeDate.getFullYear();
var hh = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getHours());
var min = new Intl.NumberFormat('en-IN', { minimumIntegerDigits: 2 }).format(WholeDate.getMinutes());
cell8.innerHTML = "" + mm + "-" + dd + "-" + yyyy + " " + hh + ":" + min + "h";
rs.MoveNext
}
rs.Close();
cn.Close();
YellowCard1.className = "";
YellowCard1.innerHTML = ""
YellowCard.className = "";
}
</code></pre>
| 3 | 2,209 |
Not receiving PHP contact form submissions
|
<p>I was wondering if you guys can figure out why I'm not receiving my contact form submissions. I tested it out with my secondary email but still haven't received it. I tried looking for answers here in SO and on Google but can't find any solution. I have 3 questions.</p>
<p>It is my code?
Or did I not properly setup my Apache?
Is my php code secure from spam?</p>
<p>here's my code:</p>
<pre><code><?php
if(isset($_POST['email'])) {
// CHANGE THE TWO LINES BELOW
$email_to = "myemail@mail.com";
$email_subject = "Contract work opportunity";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- place your own success html below -->
Thank you for contacting. I will be in touch with you very soon.
<?php
}
die();
?>
</code></pre>
<p>HTML</p>
<pre><code><form name="htmlform" method="post" action="http://mysite.localdom/html_form_send.php/">
<table width="400px">
</tr>
<tr>
<td valign="top">
<label for="first_name">First Name *</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50">
</td>
</tr>
<tr>
<td valign="top">
<label for="last_name">Last Name *</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50">
</td>
</tr>
<tr>
<td valign="top">
<label for="business_name">Business Name</label>
</td>
<td valign="top">
<input type="text" name="business_name" maxlength="200">
</td>
</tr>
<tr>
<td valign="top">
<label for="website">Website</label>
</td>
<td valign="top">
<input type="text" name="website" maxlength="200">
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address *</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80">
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Phone</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Message</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="5000" cols="25" rows="6">ok ok ok</textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Submit" id="submitbutton">
</td>
</tr>
</table>
</form>
</code></pre>
| 3 | 2,063 |
I get wrong output when using diff -u between two textfiles
|
<p>When i use "diff -u" between two txt files where I have only changed two lines it tells me that i've changed every line in the file. Here's the output:</p>
<pre><code> Admin@DESKTOP-9A5CFG4 MINGW64 ~/Desktop/singlediff
$ diff -u nutty-pancake.txt nutty-pancake-new.txt
--- nutty-pancake.txt 2016-07-12 16:48:29.465917000 +0200
+++ nutty-pancake-new.txt 2016-07-12 16:49:10.737818500 +0200
@@ -1,61 +1,61 @@
-Nutty Pancake
-
-== Ingredients ==
-
-* 1 cup all-purpose bleached flour
-* 2 teaspoons sugar
-* 1/2 teaspoon salt
-* 1/3 teaspoon baking powder
-* 1/4 teaspoon baking soda
-* 3/4 cup buttermilk
-* 1/4 cup milk
-* 1 large egg
-* 2 tablespoon unsalted butter, melted
-* 1 teaspoon almond extract
-* Vegetable oil for brushing griddle
-
-== Procedure ==
-
-1. Heat a large non-stick skillet or griddle over
- low heat while preparing ingredients.
-
-2. Mix flour, sugar, salt, baking powder, and baking
- soda in medium bowl.
-
-3. Microwave buttermilk and milk in a 2-cup Pyrex
- measuring cup to room temperature, 20 to 30 seconds.
-
-4. Whisk in egg, butter, and almond extract.
-
-5. Add wet ingredients to dry ingredients and whisk until
- just mixed.
-
-6. Return batter to measuring cup, stirring in a teaspoon
- or two of water, if necessary, to make a thick, but pourable batter.
-
-7. Increase heat to medium and generously brush skillet or griddle with
- oil.
-
-8. When oil starts to spider, but before it starts to smoke, pour
- batter, about 1/4 cup at a time.
-
-9. Work in batches, if necessary, to avoid overcrowding.
-
-10. When pancake bottoms are golden brown and tops start to bubble,
- 2 to 3 minutes, flip pancakes.
-
-11. Cook until pancakes are golden brown on remaining side.
-
-12. Repeat, brushing skillet or griddle with oil.
-
-Serve hot.
-
-==Source==
-
-This recipe originally comes from Wikibooks.
-
-http://en.wikibooks.org/w/index.php?oldid=769489
-(last visited May 19, 2012).
-
-Some rights reserved; see http://creativecommons.org/licenses/by-sa/3.0/
-for more information.
+Nutty Pancake
+
+== Ingredients ==
+
+* 1 cup all-purpose bleached flour
+* 2 teaspoons sugar
+* 1/2 teaspoon salt
+* 1/3 teaspoon baking powder
+* 1/4 teaspoon baking soda
+* 3/4 cup buttermilk
+* 1/4 cup milk
+* 1 large egg
+* 2 tablespoon unsalted butter, melted
+* 1 teaspoon walnut extract
+* Vegetable oil for brushing griddle
+
+== Procedure ==
+
+1. Heat a large non-stick skillet or griddle over
+ low heat while preparing ingredients.
+
+2. Mix flour, sugar, salt, baking powder, and baking
+ soda in medium bowl.
+
+3. Microwave buttermilk and milk in a 2-cup Pyrex
+ measuring cup to room temperature, 20 to 30 seconds.
+
+4. Whisk in egg, butter, and walnut extract.
+
+5. Add wet ingredients to dry ingredients and whisk until
+ just mixed.
+
+6. Return batter to measuring cup, stirring in a teaspoon
+ or two of water, if necessary, to make a thick, but pourable batter.
+
+7. Increase heat to medium and generously brush skillet or griddle with
+ oil.
+
+8. When oil starts to spider, but before it starts to smoke, pour
+ batter, about 1/4 cup at a time.
+
+9. Work in batches, if necessary, to avoid overcrowding.
+
+10. When pancake bottoms are golden brown and tops start to bubble,
+ 2 to 3 minutes, flip pancakes.
+
+11. Cook until pancakes are golden brown on remaining side.
+
+12. Repeat, brushing skillet or griddle with oil.
+
+Serve hot.
+
+==Source==
+
+This recipe originally comes from Wikibooks.
+
+http://en.wikibooks.org/w/index.php?oldid=769489
+(last visited May 19, 2012).
+
+Some rights reserved; see http://creativecommons.org/licenses/by-sa/3.0/
+for more information.
</code></pre>
<p>I have only changed two occurrences of the word almond to walnut.
I am using gitbash in windows by the way.</p>
| 3 | 1,271 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.