title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Karate is not loading spring boot class with Autowired annotation
|
<p>I have a requirement to automate apache kafka test where my development team is using @Autowired annotaion to load the beans.</p>
<pre><code>@Component
public class getAccountsBuilder {
@Autowired
EventBuilder eventBuilder;
@Value("${uk.ipay.contract.account.get.req}")
private String getAccountsReqTopic;
private String scope;
private String email;
public EventData generaterequest(int rowNum) {
EventData applicationData = null;
Map<Integer, List<String>> paylod;
paylod = readData();
List<String> payloadData = paylod.get(rowNum);
System.out.println(payloadData.get(2));
System.out.println(payloadData.get(1));
applicationData = generateGetAccountssRequest(payloadData);
return applicationData;
}
private Map<Integer, List<String>> readData() {
return DataProcessing.readFromExcel(
"src/test/resources/testData/RequestData_COP.xlsx",
"getAccounts");
}
/**
* This will return event for get accounts.
*
* @param payloadData - Test data
* @return - Request event
*/
private EventData generateGetAccountssRequest(List<String> payloadData) {
/*JWTToken jwtToken = new JWTToken();
jwtToken.setScope(payloadData.get(6));
jwtToken.setEmail(payloadData.get(6));*/
scope = "portal-cop"; //jwtToken.getScope();
email = "test01807@mailinator.com"; //jwtToken.getEmail();
EventData eventData = eventBuilder.buildEventData("uk.ipay.contract.account.get.req", email, scope);
System.out.println(eventData);
return eventData;
}
}
</code></pre>
<p>When I am executing my code, I am getting null value error:</p>
<p><a href="https://i.stack.imgur.com/Yu6K9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yu6K9.png" alt="enter image description here" /></a></p>
<p>I am new to spring boot test and karate, So does any one have implemented any such scenarios and knows how to resolve this issue</p>
| 3 | 1,101 |
jQuery Ajax each function for btn-group bootstrap
|
<p>I'm sorry, but I have no idea how I can set my JSON times in the next btn-group div.<br />
I need it be grouped in 4 "button", and than the next <code><div class="btn-group mt-1"</code> <br />
Here is my JSfiddle: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var JSON = [
{
"Tennis 1": {
"IntervalTime": {
"Dom": [
"09:00", //move into buttons
"10:00", //move into buttons
"11:00", //move into buttons
"12:00", //move into buttons
"13:00", //move into buttons
"14:00", //move into buttons
"15:00", //move into buttons
"16:00", //move into buttons
"17:00", //move into buttons
"18:00" //move into buttons
]
}
},
"Padel 1": {
"IntervalTime": {
"Dom": [
"09:00", //move into buttons
"10:00", //move into buttons
"11:00", //move into buttons
"12:00", //move into buttons
"13:00", //move into buttons
"14:00" //move into buttons
]
}
}
}],html;
$(document).ready(function () {
html = '<div class="container" >';
$.each(JSON, function(index, v){
html += '<div class="col-sm-4">Tennis 1 <--- Here JSON Resource<div class="col-sm-4">TIMES</div></div>';
html += '<div class="btn-group" role="group" aria-label="Orari Disponibili">';
html += '<button type="button" class="btn btn-outline-primary">09:00</button>';
html += '<button type="button" class="btn btn-outline-primary">10:00</button>';
html += '<button type="button" class="btn btn-outline-primary">11:00</button>';
html += '<button type="button" class="btn btn-outline-primary">12:00</button>';
html += '</div>';
html += '<div class="btn-group mt-1" role="group" aria-label="Orari Disponibili">';
html += '<button type="button" class="btn btn-outline-primary">13:00</button>';
html += '<button type="button" class="btn btn-outline-primary">14:00</button>';
html += '<button type="button" class="btn btn-outline-primary">15:00</button>';
html += '<button type="button" class="btn btn-outline-primary">16:00</button>';
html += '</div>';
html += '<div class="btn-group mt-1" role="group" aria-label="Orari Disponibili">';
html += '<button type="button" class="btn btn-outline-primary">17:00</button>';
html += '<button type="button" class="btn btn-outline-primary">18:00</button>';
html += '</div>';
//Seconda riga orari
html += '<div class="col-sm-4">Padel 1 <--- Here JSON Resource<div class="col-sm-4">TIMES</div></div>';
html += '<div class="btn-group mt-1" role="group" aria-label="Orari Disponibili">';
html += '<button type="button" class="btn btn-outline-primary">09:00</button>';
html += '<button type="button" class="btn btn-outline-primary">10:00</button>';
html += '<button type="button" class="btn btn-outline-primary">11:00</button>';
html += '<button type="button" class="btn btn-outline-primary">12:00</button>';
html += '</div>';
html += '<div class="btn-group mt-1" role="group" aria-label="Orari Disponibili">';
html += '<button type="button" class="btn btn-outline-primary">13:00</button>';
html += '<button type="button" class="btn btn-outline-primary">14:00</button>';
html += '</div>';
});
html += '</div>';
$('body').append(html);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
<p>Any idea is appreciated</p>
| 3 | 2,156 |
How to POST a form with Django and not reload the page
|
<p>I'm working on an app where the user will submit a value and I want to hide the div containing the form on submit and display a div containing the results. The goal is to have them submit the form and display a different hidden div. What am I doing wrong with either the Django code or Javascript?</p>
<p>views.py</p>
<pre><code>from django.shortcuts import render
from .models import VintageMac
from .forms import VintageMacForm
def home(request):
if request.method == "POST":
form = VintageMacForm(request.POST)
if form.is_valid():
form.save()
form = VintageMacForm()
else:
form = VintageMacForm()
return render(request, 'hmwypapp/index.html', {'form': form})
</code></pre>
<p>urls.py</p>
<pre><code>from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
</code></pre>
<p>models.py</p>
<pre><code>from django.conf import settings
from django.db import models
from django.utils import timezone
from django import forms
class VintageMac(models.Model):
price = models.IntegerField()
def publish(self):
self.save()
def __str__(self):
return '%s' % (self.price)
</code></pre>
<p>forms.py</p>
<pre><code>from django import forms
from .models import VintageMac
class VintageMacForm(forms.ModelForm):
class Meta:
model = VintageMac
fields = ('price',)
</code></pre>
<p>HTML</p>
<pre><code><div id="submission1">
<p class="card-text">Some quick example text to build on the card title.</p>
<div class="bottom">
<div class="row">
<form action="/create_post/" class="w-100" method="POST" id="form1">
<div class="col-12">
{% csrf_token %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
{% for field in form.visible_fields %}
<div class="form-control">
{% render_field field min="0" class="form-control" id="amount1" placeholder="Type an amount." %}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
{% endfor %}
</div>
<div class="col-12">
<button onclick="myFunction1()" class="mt-1 text-center form-control btn submit-btn">Submit <span></span></button>
</div>
</form>
<div class="text-center credit mt-2 w-100">Submitted by @peterdenatale</div>
</div>
</div></div>
<div id="results1">
<p class="card-text">You said that you would pay <span class="value">$375.00</span> .</p>
<div class="bottom">
<div class="row">
<div class="col-12">
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100" style="width: 65%;">
</div>
</div>
<div class="row" style="margin-bottom: -20px;">
<p class="col-4 raised-text"><strong>Min<br>$0.00</strong></p>
<p class="col-4 average-text"><strong>Avg<br>$250.00</strong></p>
<p class="col-4 goal-text"><strong>Max<br>$500.00</strong></p>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>JavaScript </p>
<pre><code>$(document).on('submit','#form1',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url: '',
data:{
amount: $('#amount1').val(),
},
success:function(){
$('#submission1').fadeOut(500);
$('#results1').delay(500).fadeIn(500);
}
});
</code></pre>
<p>I tried changing the JavaScript to a bunch of different things, but the only thing that it does it reload the page. I want to get rid of the reload and stay on the same page but still post the data and hide/show the divs.</p>
| 3 | 2,779 |
Text does not show string in CountDownTimer
|
<p>I have a CountDownTimer Class to set a countdown which will start will when the user clicks some Button.<br>
This is the code that includes the CountDownTimer </p>
<pre><code> public class play extends Activity implements View.OnClickListener{
private TapCountDownTimer countDownTimer;
private final long startTime = 10;
private final long interval = 1;
private TextView countdowntext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.play);
countDownTimer = new TapCountDownTimer(startTime, interval);
countdowntext = (TextView)findViewById(R.id.countdowntext);
countdowntext.setText(String.valueOf(startTime));
Button buttonstart = (Button)findViewById(R.id.stopbutton);
buttonstart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
countDownTimer.start();
}
});
Button buttonstop = (Button)findViewById(R.id.stopbutton);
buttonstop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
countDownTimer.cancel();
}
});
public class TapCountDownTimer extends CountDownTimer {
public TapCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
@Override
public void onTick(long millisUntilFinished)
{
countdowntext.setText(Long.toString(millisUntilFinished/1));
}
@Override
public void onFinish()
{
countdowntext.setText("Time's up!");
}
}
}
</code></pre>
<p>I set the text in this line </p>
<pre><code>countdowntext.setText(Long.toString(millisUntilFinished/1));
</code></pre>
<p>But it's not working and the text shows "Time's Up" instead of the countdown.<br>
Does anyone know how to fix this issue?</p>
| 3 | 1,100 |
Read HTTP POST from mobile in java
|
<p>I have iOS Swift code, which sends a POST request to server. If i send this code directly to apple server i get response back with proper data. But when i send this to my server, server could not get the body of the HTTP POST. </p>
<p>I have no idea whether this issue is related to client side or server side.</p>
<p>Here is the Swift code.</p>
<pre><code>func validateReceipt(completion : (status : Bool) -> ()) {
let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL!
if NSFileManager.defaultManager().fileExistsAtPath(receiptUrl.path!)
{
if let receipt : NSData = NSData(contentsOfURL: receiptUrl)
{
let receiptdata: NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed)
let dict = ["receipt-data" : receiptdata]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
let request = NSMutableURLRequest(URL: NSURL(string: ReceiptURL.MAIN_SERVER.rawValue)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody = jsonData
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let dataR = data
{
self.handleData(dataR, completion: { status in
completion(status: status)
})
}
})
task.resume()
}
else
{
completion(status: false)
}
}
else
{
completion(status: false)
}
}
</code></pre>
<p>and here is my Java code in server side, there are two Java classes which take care of this</p>
<pre><code>MyRequestWrapper.Java
package webservice;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[100000];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
</code></pre>
<p>And here is the another class.</p>
<pre><code>GetResult.Java
package webservice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
@Path("/service")
public class GetResult {
static Logger logger = Logger.getLogger(GetResult.class);
// @Produces("application/json; charset=UTF-8")
//@Produces("text/plain")
@POST
@Produces (MediaType.APPLICATION_JSON)
public Response inapp(@Context HttpServletRequest request,
@Context HttpServletResponse response) throws Exception {
System.out.println("response===" + response);
System.out.println("Request-Header===" + request.getHeader("receipt-data"));
System.out.println("Request===" + request.getParameter("receipt-data"));
// System.out.println("Request==="+request.getReader());
// reader(request,response);
// getBody(request);
doFilter(request,response);
String result = "";
result = " " /* jsonObject */;
return Response.status(200).entity(result).build();
}
</code></pre>
<p>We could get the client IP and client Port from this request but unable to get the body. In production also we could not get the body. Some Java developers told me that you cant directly get the raw bytes in Java, i don't know about this.</p>
<p>Somebody please take a look at this, and tell me what i am doing wrong.</p>
| 3 | 2,452 |
error: cannot allocate an object of abstract type
|
<p>As much as I want to create an MVCE of this problem...I really can't. I am using an open source fluid flow solver called Palabos with its dev guide also available . It is based on generic structures and mpi. Probably the best available open source solver of its kind</p>
<p>The developers there use Box Processors for cycling through arrays(generally speaking..it can be tensors, lattice are other objects). Here is a way they use processors for a single lattice case</p>
<pre><code>struct IniTemperatureRayleighBenardProcessor2D :
public BoxProcessingFunctional2D_L<T,adDescriptor>
{
IniTemperatureRayleighBenardProcessor2D(RayleighBenardFlowParam<T,nsDescriptor,adDescriptor> parameters_)
: parameters(parameters_)
{ }
virtual void process(Box2D domain, BlockLattice2D<T,adDescriptor>& adLattice)
{
Dot2D absoluteOffset = adLattice.getLocation();
Array<T,adDescriptor<T>::d> jEq(0.0, 0.0);
for (plint iX=domain.x0; iX<=domain.x1; ++iX) {
for (plint iY=domain.y0; iY<=domain.y1; ++iY) {
//some operations...............
}
}
}
virtual IniTemperatureRayleighBenardProcessor2D<T,nsDescriptor,adDescriptor>* clone() const
{
return new IniTemperatureRayleighBenardProcessor2D<T,nsDescriptor,adDescriptor>(*this);
}
virtual void getTypeOfModification(std::vector<modif::ModifT>& modified) const {
modified[0] = modif::staticVariables;
}
virtual BlockDomain::DomainT appliesTo() const {
return BlockDomain::bulkAndEnvelope;
}
private :
RayleighBenardFlowParam<T,nsDescriptor,adDescriptor> parameters;
};
</code></pre>
<p>Here how they call it</p>
<pre><code> applyProcessingFunctional (
new IniTemperatureRayleighBenardProcessor2D<T,NSDESCRIPTOR,ADESCRIPTOR>(parameters), adLattice.getBoundingBox(),
adLattice );
</code></pre>
<p>Details of the whole procedure are at (<a href="http://www.palabos.org/documentation/userguide/data-processors.html" rel="nofollow">http://www.palabos.org/documentation/userguide/data-processors.html</a>)</p>
<p>with related source code at (<a href="http://www.palabos.org/documentation/develguide/dataProcessingFunctional2D_8h_source.html" rel="nofollow">http://www.palabos.org/documentation/develguide/dataProcessingFunctional2D_8h_source.html</a>)</p>
<p>Now, here is my problem.
I am using a similar data processor to perform operation on two scalar arrays. Tried to understand as much as of the source code as possible</p>
<pre><code>template<typename T1, typename T2>
//template<typename T, template<typename NSU> class nsDescriptor,
// template<typename ADU> class adDescriptor, typename T1, typename T2>
struct IniFluxMultiplier2D :
public BoxProcessingFunctional2D_SS<T,T>
{
IniFluxMultiplier2D(RayleighBenardFlowParam<T,NSDESCRIPTOR,ADESCRIPTOR> parameters_)
: parameters(parameters_)
{ }
virtual void process(Box2D domain,
MultiScalarField2D<bool>& boolMask,
MultiScalarField2D<T> &FluxMultiplier)
{
//Dot2D absoluteOffset = adLattice.getLocation();
//Array<T,adDescriptor<T>::d> jEq(0.0, 0.0);
for (plint iX=domain.x0; iX<=domain.x1; ++iX) {
for (plint iY=domain.y0; iY<=domain.y1; ++iY) {
//plint absoluteX = absoluteOffset.x + iX;
//plint absoluteY = absoluteOffset.y + iY;
bool solidblock = boolMask.get(iX,iY);
if(solidblock== true){
FluxMultiplier.get(iX,iY)=(parameters.getTemperatureTau()-(T)0.5)/parameters.getTemperatureTau();}
else{
FluxMultiplier.get(iX,iY)=(parameters.getSolventTau()-(T)0.5)/parameters.getSolventTau();}
}
}
}
virtual IniFluxMultiplier2D<T1,T2>* clone() const
{
return new IniFluxMultiplier2D<T1,T2>(*this);
}
virtual void getTypeOfModification(std::vector<modif::ModifT>& modified) const {
modified[0] = modif::staticVariables;
}
virtual BlockDomain::DomainT appliesTo() const {
return BlockDomain::bulkAndEnvelope;
}
private :
RayleighBenardFlowParam<T,NSDESCRIPTOR,ADESCRIPTOR> parameters;
};
</code></pre>
<p>and here is how I call it</p>
<pre><code>applyProcessingFunctional (
new IniFluxMultiplier2D<T,T>(parameters), boolMask.getBoundingBox(), boolMask,FluxMultiplier);
</code></pre>
<p>I am getting the error</p>
<pre><code>error: cannot allocate an object of abstract type ‘IniFluxMultiplier2D<double, double>’|
</code></pre>
<p>Tried debugging it but I am stuck and really can't figure a way out. I don't really expect anyone to run this, but I know I am making a conceptual mistake at the starting of the structure which I can't really figure out.</p>
<p>T is decalared as </p>
<pre><code>typedef double T;
</code></pre>
<p>globally</p>
| 3 | 2,129 |
Apache Tiles 3 with Freemarker basic setup, not working
|
<p>I have not been able to get a very simple freemarker template working with Tiles 3. The examples on the site seem to be for version 2.x as the programmatic configuration references classes that don't exist in tiles 3.</p>
<p>With the following cofiguration, my template displays as is (that is it does not include any tiles). How can I fix this?</p>
<p><strong>When rendering page:</strong>
When using the url: <code>http://localhost:8080/TilesFreeMarker/myapp.homepage.tiles</code> I get exactly the same content as it in the templage.ftl file below. If I replace all ftl files with jsp's (and the required tags) the example then behaves as expected, but I require freemarker functionality.</p>
<p><strong>Web.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>
</listener>
<!-- Configure so anything ending in .tiles will be processed by tiles -->
<servlet>
<servlet-name>Tiles Dispatch Servlet</servlet-name>
<servlet-class>org.apache.tiles.web.util.TilesDispatchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Tiles Dispatch Servlet</servlet-name>
<url-pattern>*.tiles</url-pattern>s
</servlet-mapping>
</web-app>
</code></pre>
<p><strong>template.ftl</strong></p>
<pre><code><#assign tiles=JspTaglibs["http://tiles.apache.org/tags-tiles"]>
<!DOCTYPE>
<html>
<head>
<title>
<@tiles.getAsString name="title"/>
</title>
</head>
<body>
<table>
<tr>
<td colspan="2">
<@tiles.insertAttribute name="header"/>
</td>
</tr>
<tr>
<td>
<@tiles.insertAttribute name="menu"/>
</td>
<td>
<@tiles.insertAttribute name="body"/>
</td>
</tr>
<tr>
<td colspan="2">
<@tiles.insertAttribute name="footer"/>
</td>
</tr>
</table>
</body>
</html>
</#assign>
</code></pre>
<p><strong>header.ftl</strong></p>
<pre><code><div>The Header</div>
</code></pre>
<p><strong>menu.ftl</strong></p>
<pre><code><ul>
<li>Menu Item</li>
<li>Menu Item</li>
<li>Menu Item</li>
<li>Menu Item</li>
</ul>
</code></pre>
<p><strong>body.ftl</strong></p>
<pre><code><div>The Body</div>
</code></pre>
<p><strong>footer.ftl</strong></p>
<pre><code><div>The Footer</div>
</code></pre>
<p><strong>pom.xml</strong></p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.quaternion</groupId>
<artifactId>TilesFreeMarker</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>TilesFreeMarker</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-extras</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
</code></pre>
| 3 | 3,892 |
Improper behavior of Host Alias
|
<p>I have two host alias in my directory structure that fail to properly register with g-wan. My folder structure is as follows:</p>
<blockquote>
<p>/srv/gwan_linux64-bit/192.168.3.101_80/$dg.lcl <br>
/srv/gwan_linux64-bit/192.168.3.101_80/$myapp <br>
/srv/gwan_linux64-bit/192.168.3.101_80/#192.168.3.101 <br>
/srv/gwan_linux64-bit/192.168.3.101_80/#192.168.3.101:gwan.klickitat.lcl
<br> /srv/gwan_linux64-bit/192.168.3.101_80/#192.168.3.101:test.lcl
<br></p>
</blockquote>
<p>When starting g-wan, I receive the error:</p>
<blockquote>
<p>loading.........
* unresolved aliases: 2
<br></p>
</blockquote>
<p><br>
From the sample server report in the default g-wan configuration:</p>
<blockquote>
<p>Listeners <br> 5 host(s): 192.168.3.101_80 <br> Virtual: $dg.lcl <br>
Root: #test.lcl <br> Root: #gwan.klickitat.lcl <br> Virtual: $myapp
<br> Root: #192.168.3.101 <br></p>
</blockquote>
<p>As you can see, g-wan identifies the two root aliases as additional roots. G-wan only allows a single root host, so the two alias fail to function in the browser with a 404 error. Each of the hosts respond properly to ping, so they are accounted for by the dns. The virtual hosts and root host function as expected.</p>
<p>Thoughts?</p>
<hr>
<h2>Additional research:</h2>
<p>I have corrected my posting error and simplified the presentation. I hope that you will find this to be concise.</p>
<p>My hosts file is as follows for all tests: <br></p>
<blockquote>
<p>127.0.0.1 localhost.klickitat.lcl localhost <br>
192.168.3.101 gwan.klickitat.lcl test.lcl <br></p>
</blockquote>
<p>I implemented an example that is identical to your test with the exception that I used a different IP address to match my local subnet and I eliminated the virtual hosts, which do not impact my result in my testing. <br><br>
The only changes to the default gwan configuration are as follows: <br></p>
<ul>
<li>Changed the listener from 0.0.0.0_8080 to 192.168.3.101_8080</li>
<li>Changed the root host IP from #0.0.0.0 to #192.168.3.101</li>
<li>Added two host aliases #192.168.3.101:gwan.klickitat.lcl and
#192.168.3.101:test.lcl</li>
</ul>
<p>This is my folder structure: <br></p>
<blockquote>
<p>/srv/gwan_linux64-bit/192.168.3.101_8080 <br>
/srv/gwan_linux64-bit/192.168.3.101_8080/#192.168.3.101 <br>
/srv/gwan_linux64-bit/192.168.3.101_8080/#192.168.3.101:gwan.klickitat.lcl
<br> /srv/gwan_linux64-bit/192.168.3.101_8080/#192.168.3.101:test.lcl
<br></p>
</blockquote>
<p>This is my result as reported by gwans included server report application: <br></p>
<blockquote>
<p>3 host(s): 192.168.3.101_8080 <br> Root: #test.lcl <br> Root:
#gwan.klickitat.lcl <br> Root: #192.168.3.101 <br></p>
</blockquote>
<p>Gwan does not recognize the aliases and I cannot access the aliased urls. My result is inconsistent with yours. <br> </p>
<p>The rest of this post is intended only to illustrate that aliases are reported by gwan in alternate configurations in my environment, but with some inconsistencies in the expected outcome. I simply identify the folder structure and my result.</p>
<p><strong>Alternate Config 1</strong> <br>
/srv/gwan_linux64-bit/0.0.0.0_8080 <br>
/srv/gwan_linux64-bit/0.0.0.0_8080/#localhost <br>
/srv/gwan_linux64-bit/0.0.0.0_8080/#localhost:gwan.klickitat.lcl <br>
/srv/gwan_linux64-bit/0.0.0.0_8080/#localhost:test.lcl <br></p>
<p><strong>Result:</strong> <br>
3 host(s): 0.0.0.0_8080 <br>
Root: #localhost <br>
Alias: 0.0.0.0:#gwan.klickitat.lcl <br>
Alias: 0.0.0.0:#test.lcl <br></p>
<p><strong>Alternate Config 2</strong> <br>
/srv/gwan_linux64-bit/192.168.3.101_8080 <br>
/srv/gwan_linux64-bit/192.168.3.101_8080/#localhost <br>
/srv/gwan_linux64-bit/192.168.3.101_8080/#localhost:gwan.klickitat.lcl <br>
/srv/gwan_linux64-bit/192.168.3.101_8080/#localhost:test.lcl <br></p>
<p><strong>Result:</strong> <br>
3 host(s): 192.168.3.101_8080 <br>
Root: #localhost <br>
Alias: 192.168.3.101:#gwan.klickitat.lcl <br>
Alias: 192.168.3.101:#test.lcl <br></p>
<p>While the alternate configurations function, note that the aliases naming varies from the explicit naming in the folder structure. It appears that the listeners are being properly set up, but that there is some issue in how the host laiases are being generated. I'm happy to test further if you so desire.</p>
| 3 | 1,745 |
SPAlbumBrowse - Getting an Accurate List Of An Artist's Albums
|
<p>Okay. This is getting crazy. I've been working on this for a few days trying different weird things. I think I had a nightmare last night about libSpotify, might be a product of my sleeping habits, but, I digress.</p>
<p>Anyway. Let's look up the artist "The XX" with the following code. Assume that <em>artist</em> is initialized with the artist "the xx", Spotify url spotify:artist:3iOvXCl6edW5Um0fXEBRXy</p>
<pre><code>artistBrowse = [[SPArtistBrowse alloc] initWithArtist: artist inSession: spotifySession type: SP_ARTISTBROWSE_ALBUMS];
[SPAsyncLoading waitUntilLoaded: artistBrowse timeout: kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedItems, NSArray *notLoadedItems) {
[SPAsyncLoading waitUntilLoaded: artistBrowse.albums timeout: kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedItems, NSArray *notLoadedItems) {
NSArray *types = @[@"a", @"s", @"c", @"u"];
for(SPAlbum *album in loadedItems) {
NSLog(@"%@, %@, %@, %d, %-50s, %@", types[album.type], album.available ? @"Y" : @" N", album.artist.name, album.year, album.name.UTF8String, album.spotifyURL);
}
}];
}];
</code></pre>
<p>Here's the output. Sorry, it's kind of lengthy. Note that the first column refers to the SP_ALBUM_TYPE of the album (a = album, s = single, c = compilation, u = unknown), the second column is a Y or N depending on if the album is available in my session's region (US), the third column is the artist name, the fifth is the album's year, the sixth is the album's name, and lastly the Spotify URL of the album.</p>
<pre><code>u, N, The xx , 2012, Coexist , spotify:album:2cRMVS71c49Pf5SnIlJX3U
u, N, The xx , 2009, xx , spotify:album:2rmMeEq5D1Bg7YFRwtHBDr
a, N, The xx , 2009, xx , spotify:album:2nXJkqkS1tIKIyhBcFMmwz
s, Y, The xx , 2013, Reunion (Edu Imbernon Remix) , spotify:album:4GRHNZJ1dWCqgWfiyyJF2L
u, N, The xx , 2013, Fiction , spotify:album:4fUxANSrGWQlRtF2kpxo6g
s, Y, The xx , 2013, Innervisions Remixes , spotify:album:4ZmviA6XFr2D2Bfw0bicwa
s, Y, The xx , 2013, Sunset (Jamie Jones Remix) , spotify:album:1XlsTZcDbHQmLr3tNvuV5o
s, Y, The xx , 2013, Sunset (Kim Ann Foxman Remix) , spotify:album:26gAjcYx9iGrOuplES6jC1
s, Y, The xx , 2012, Angels , spotify:album:7kuu8alOjlFTGJmwsRINz9
s, Y, The xx , 2012, Angels (Four Tet Remix) , spotify:album:4ZLWktgv4GJSgzzskz6rpI
s, Y, The xx , 2012, Chained (John Talabot and Pional Blinded Remix) , spotify:album:2PsFbWSt7nAwZuO6M6zeMU
s, Y, The xx , 2012, Chained (LIAR Remix) , spotify:album:6HrD4wpVXVfXkZP1gxcKyH
s, Y, The xx , 2012, Jamie xx Edits , spotify:album:33UOrxCqUHQDH3XvNEYWoP
s, N, The xx , 2009, Basic Space , spotify:album:0LusnqOZqR8IYXHWE3DSQI
s, N, The xx , 2009, Basic Space , spotify:album:6aStvQrltK28rgDFsyOsBS
s, Y, The xx , 2009, Crystalised , spotify:album:6npsIAD3tolsM1htkmCDpT
s, N, The xx , 2009, Islands , spotify:album:7rW7Zf8fTJT25wMo4z6ww3
s, N, The xx , 2009, Islands , spotify:album:0KVBiUIqhl087FgJyvr8kS
s, N, The xx , 2009, VCR , spotify:album:0eRJD5ey3HqIgsGheUwZqg
s, Y, The xx , 2009, VCR (Four Tet Remix) , spotify:album:0L1Dg07wMBxRkzO5qlN1li
s, N, The xx , 2009, xx , spotify:album:0z6ErTRiEcAML2IPrkWI5W
a, N, Various Artists , 2013, Circus HalliGalli , spotify:album:0SCDZwyv5MbWsCdmeRHJUb
a, N, Craig Armstrong , 2013, The Orchestral Score From Baz Luhrmann's Film The Great Gatsby, spotify:album:7hTAlVO7LPTI5Q3KI5rTkR
a, Y, Craig Armstrong , 2013, The Orchestral Score From Baz Luhrmann's Film The Great Gatsby, spotify:album:6OuywehyzlNMYklKnPpr1W
a, N, Various Artists , 2013, Ministry Of Sound Chillout Sessions Classics , spotify:album:4yfIS04c7NLu20GEx0fKLm
a, N, Various Artists , 2013, Young Folks , spotify:album:56HMwAOWW0jnAH7J1S71Q1
a, N, Various Artists , 2013, Dance Anthems (Summer Edition 2013) , spotify:album:25uYDaqMIFjCSKKWgDpDuM
a, N, Various Artists , 2013, FluxFM - Popkultur kompakt Vol. 1 , spotify:album:44OoPqLioRdPtG181OSWXO
a, Y, Various Artists , 2013, Music From Baz Luhrmann's Film The Great Gatsby , spotify:album:0ke0VwcET1D6neauEyk4U4
a, Y, Various Artists , 2013, Music From Baz Luhrmann's Film The Great Gatsby , spotify:album:1ApOUkhympslVqgf9QFHUj
a, Y, Various Artists , 2013, Music From Baz Luhrmann's Film The Great Gatsby , spotify:album:4fPvaODSSdvvP7nuVKCYW2
a, N, Various Artists , 2013, Music From Baz Luhrmann's Film The Great Gatsby , spotify:album:0WXuzb6XoO21qOswVOH0xG
a, N, Various Artists , 2013, Music From Baz Luhrmann's Film The Great Gatsby , spotify:album:2XVXltseIMrGuK09ck7TpS
a, N, Various Artists , 2013, Music From Baz Luhrmann's Film The Great Gatsby , spotify:album:4zmVotzGvedZLgLt7b9enu
a, N, Various Artists , 2013, De Afrekening 54 , spotify:album:5v4Mk83IAaZF8v2ZJlR3zJ
a, N, Various Artists , 2013, Ministry of Sound FUT.UR.ISM , spotify:album:2oliIwXGnek066NvzFOyMh
a, N, Various Artists , 2013, Dermot O'Leary Presents The Saturday Sessions 2013, spotify:album:0vxrNQhxXzFHDoDe8ujfmC
a, N, Various Artists , 2013, Dermot O'Leary Presents The Saturday Sessions 2013, spotify:album:4IjdYP8ejVAUVhYEHIxV69
a, N, Various Artists , 2013, Switch 21 , spotify:album:2asHAel3cC4en0vj8OvL14
a, N, Various Artists , 2013, BRIT Awards 2013 , spotify:album:42DRlqFzejkEI1wTjggazF
a, N, Various Artists , 2013, about:berlin vol:2 , spotify:album:2M4eESAbUIRLtcoTZWKSwd
a, N, Various Artists , 2012, De Afrekening 53 - Best Of 2012 , spotify:album:3EZr5R7qYv49m80jTjjURV
a, N, Various Artists , 2012, Thank God It's Friday , spotify:album:0uUKY9EW6pQN8SPzU9vUyd
a, N, Various Artists , 2012, Humo 2012 , spotify:album:3JUslyKt2lAhaQdwX2nsCu
a, N, Various Artists , 2012, FM4 Soundselection Vol.27 , spotify:album:6vWWIRMgDoy3bYkX6oYy6j
a, N, Various Artists , 2012, Ministry of Sound Chillout Sessions XV , spotify:album:1luLiZ8M8yvlwwaLZNkBxI
a, N, Various Artists , 2012, Life Is Music 2012/2 , spotify:album:5uobOKU5V5Gdkr89uioVSk
a, N, Various Artists , 2012, Pure FM Vol.3 - Best Of 2012 , spotify:album:6VZUAizoJYpXS614EhuErD
a, N, Various Artists , 2012, Festivalitis , spotify:album:1Wzv0KyuSgZhXJTVSHuZMR
a, N, Various Artists , 2012, Sonar 1000 Vol.2 , spotify:album:6RygdphSUzqmQI0tY0XTC8
a, N, Various Artists , 2012, We Love Real Music , spotify:album:3YTlHLpLTpAPYzkh05iewe
a, N, Various Artists , 2012, Alle 40 Goed: Alternative , spotify:album:2v7n6Lgf0IV3bWqsxczFYO
a, N, Various Artists , 2012, Alle 40 Goed: Alternative , spotify:album:3Xy2qnFEUNjHMXAF3AlHhD
a, N, The Antlers , 2011, Together , spotify:album:5k6JBXhKxclnxOtGtvpxXP
a, N, Various Artists , 2011, Radio 1 Sonar 1000 , spotify:album:0ZiepVOAQGrWIl7AeUUsEy
a, N, Various Artists , 2011, Ministry of Sound Uncovered 3 , spotify:album:31Ut6kXlaSoADr5k52rYQb
a, N, Various Artists , 2011, The Weather Channel Presents – The Sounds Of Winter, spotify:album:3TWTfxuFaMCcQMHomKRTpN
a, N, Various Artists , 2011, Solid Sounds 2011/1 , spotify:album:46lwy99LsDyubeZU2KK5kB
a, N, Various Artists , 2010, Humo's Top 2010 , spotify:album:6Cvt2RPh9ANl4CUMXGSFHu
a, N, Various Artists , 2010, Ministry Of Sound Chillout Sessions XIII , spotify:album:2ze7hxcYnwo4CpdyK63xGQ
a, Y, The Big Pink , 2010, Tapes , spotify:album:1RW3Hq6dTHn1Phur2dRvg3
c, Y, The Big Pink , 2010, Tapes , spotify:album:2GJplTNzOUot6it93FtfLu
a, N, Mario Basanov , 2010, Future Balearica: New Chill & Warm Sunset Sounds , spotify:album:0I3COq9K4saT03qXsCmq6c
a, N, Various Artists , 2010, Volume.at - Alternative Summer 2010 , spotify:album:5juF4xi88AVJCreQCdm319
a, N, Various Artists , 2010, Festivalguide 2010 , spotify:album:3B066qff9ZcbFuFWC4vYai
a, N, Various Artists , 2010, Life Is Music 2010-1 , spotify:album:2jsGbNXBbjI933cmL9kGms
a, N, Various Artists , 2010, Uncovered 2 , spotify:album:3TEnNtbEnahNSkmcp0xQFZ
a, N, Various Artists , 2010, Various Artists/Rough Trade Counter Culture 09 , spotify:album:0KRR3PXLfJlIccrlgAllBh
</code></pre>
<p>Out of this data, I want to extract something like the following. These are the xx's albums on their artist page the official Spotify desktop client with the same account I'm using to log into libSpotify with.</p>
<p><img src="https://i.stack.imgur.com/7frlX.png" alt=""></p>
<p>Note that in the output, even after I've loaded all of the albums from artistBrowse.albums, the two items that are actual albums available in my region are <em>all</em> listed as unavailable, and only one is actual listed as an album. </p>
<pre><code>u, N, The xx , 2012, Coexist , spotify:album:2cRMVS71c49Pf5SnIlJX3U
u, N, The xx , 2009, xx , spotify:album:2rmMeEq5D1Bg7YFRwtHBDr
a, N, The xx , 2009, xx , spotify:album:2nXJkqkS1tIKIyhBcFMmwz
</code></pre>
<p>How do I solve this problem? Lots of times, if you go and check the web-api with the Spotify URLs of albums that say they're not available in my region through album.available, the "US" region code is right in the output from the album's result page from the web-api. Secondly, I get WIDELY different results all of the time. Nothing's consistent, sometimes Red Hot Chili Peppers' album "I'm With You" shows up as available in my region, sometimes there isn't one that is available in my region. If there are albums that are not available in my region, sometimes calling another <em>waitUntiLoaded:</em> call with the <em>loadedItems</em> returned in the <em>waitUntilLoaded</em> call with artistBrowse.albums solves the issue; loading the "loaded items" again alleviates the issue occasionally? That doesn't even make sense.</p>
<p>Lastly, wtf.</p>
<pre><code>a, N, Rihanna , 2012, Unaplogetic , spotify:album:4owyFvp5H3UXKIOBBT9x3m
a, Y, Rihanna , 2012, Unapologetic , spotify:album:0XJya16l3K1J2dEwY19F8z
a, Y, Rihanna , 2012, Unapologetic , spotify:album:4eddbruVtOqw8khwxSH6H2
a, N, Rihanna , 2012, Unapologetic , spotify:album:4XBfFj0WYyh5mBtU61EdyY
a, N, Rihanna , 2012, Unapologetic , spotify:album:5pLlGJrxuQO3jMoQe1XxZY
a, N, Rihanna , 2012, Unapologetic , spotify:album:0giyQojM6DkyXVYigNo72p
a, Y, Rihanna , 2012, Unapologetic , spotify:album:1ciAVKFdlpLi2eGDlXv6Bo
a, N, Rihanna , 2012, Unapologetic , spotify:album:1jlYso6n0IxsGTLIvZOXUn
a, N, Rihanna , 2012, Unapologetic , spotify:album:5UDXzVwWnn3mDy3mTpQPYb
</code></pre>
<p><strong>HELP</strong> please, this is a huge bummer. I am literally at a total loss here on how to go about getting <em>any</em> sort of reliable list, though I'm convinced that if the official client can do it, then I can too. I've been staring at this for so many days I'm thinking about backing up my search with a call to the web-api and like, using the web-api to give me album lists for artists.... sounds really unpleasant though. Otherwise, the library has been quite a joy to work with. Thanks again for your help!</p>
| 3 | 7,365 |
Is there a different way to put 3 plots together into 1 image besides using ggpubr in R?
|
<p>I have been using the code below to create 3 separate plots and then using ggarrange in the ggpubr package to combine them into one plot and saving it as an image. However, once I created an Rmd of my script this function is very temperamental and gives me the error "Faceting variables must have at least one value" even when it runs fine outside of the Rmd. Is there a different way to get the same results using something in the ggplot2 package? or another simpler way?
Edit: I would like to maintain the girds in my graph and not use a complex way to get a common legend that cowplot requires.</p>
<pre><code>graph_1 <- ggplot(subset(data_p, Target == "1"), aes(x=as.integer(volume), y=percent_yield, color=Tech.Rep))+
geom_point()+
geom_smooth(se=FALSE)+
facet_wrap(~sample)+
ggtitle(paste("Graph 1"))+
ylab("PERCENT YIELD")+
scale_x_discrete(limits= levels(data_p$volume))+
ylim(min=-150, max=150)+
theme(axis.text.x=element_text(size=10,angle=85,hjust=1,vjust=1))+
theme(legend.position="none")+
geom_ribbon(aes(ymax=100, ymin=50), alpha = 0.2, fill="green", col="green")+
geom_ribbon(aes(ymax=0, ymin=0), alpha = 0.2, fill="black", col="black", size=1.0)
graph_2 <- ggplot(subset(data_p, Target == "2"), aes(x=as.integer(volume), y=percent_yield, color=Tech.Rep))+
geom_point()+
geom_smooth(se=FALSE)+
facet_wrap(~sample)+
ggtitle(paste("Graph 2"))+
ylab("PERCENT YIELD")+
scale_x_discrete(limits= levels(data_p$volume))+
ylim(min=-150, max=150)+
theme(axis.text.x=element_text(size=10,angle=85,hjust=1,vjust=1))+
theme(legend.position="none")+
geom_ribbon(aes(ymax=100, ymin=50), alpha = 0.2, fill="green", col="green")+
geom_ribbon(aes(ymax=0, ymin=0), alpha = 0.2, fill="black", col="black", size=1.0)
graph_3 <- ggplot(subset(data_p, Target == "3"), aes(x=as.integer(volume), y=percent_yield, color=Tech.Rep))+
geom_point()+
geom_smooth(se=FALSE)+
facet_wrap(~sample)+
ggtitle(paste("Graph 3"))+
ylab("PERCENT YIELD")+
scale_x_discrete(limits= levels(data_p$volume))+
ylim(min=-150, max=150)+
theme(axis.text.x=element_text(size=10,angle=85,hjust=1,vjust=1))+
theme(legend.position="none")+
geom_ribbon(aes(ymax=100, ymin=50), alpha = 0.2, fill="green", col="green")+
geom_ribbon(aes(ymax=0, ymin=0), alpha = 0.2, fill="black", col="black", size=1.0)
ggarrange(graph_1, graph_2, graph_3, ncol=3, nrow=1, common.legend=TRUE, legend= "bottom")
</code></pre>
<p>Here is an example of what a single plot would look like:
<a href="https://i.stack.imgur.com/aHcdl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aHcdl.png" alt="enter image description here"></a></p>
<p>and here is what the combined plots look like:</p>
<p><a href="https://i.stack.imgur.com/0s7ux.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0s7ux.png" alt="enter image description here"></a></p>
| 3 | 1,156 |
Spinner still empty
|
<p>i was create a spinner base on an BaseAdapter</p>
<p>but when i select a value still always empty</p>
<p>it's my code</p>
<p><strong>SpinnerAdapter.class</strong></p>
<pre><code>public class SpinnerAdapter extends BaseAdapter {
private List<School> schools;
private Activity parentActivity;
private LayoutInflater inflater;
public SpinnerAdapter(Activity parent, List<School> l) {
parentActivity = parent;
schools = l;
inflater = (LayoutInflater) parentActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return schools.size();
}
@Override
public Object getItem(int position) {
return schools.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.row_spinner, null);
TextView text1 = (TextView) view.findViewById(R.id.id);
TextView text2 = (TextView) view.findViewById(R.id.libelle);
School myObj = schools.get(position);
text1.setText(String.valueOf(myObj.get_id()));
text2.setText(myObj.get_nom());
text1.setVisibility(View.GONE);
return view;
}
}
</code></pre>
<p>School.class</p>
<pre><code>public class School {
private int _id;
private String _nom;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_nom() {
return _nom;
}
public void set_nom(String _nom) {
this._nom = _nom;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/libelle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"/>
</LinearLayout>
</code></pre>
<p>i was create a request using volley library to get data from json file</p>
<p>this my result</p>
<p><a href="https://i.stack.imgur.com/bs7rH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bs7rH.png" alt="enter image description here"></a></p>
<p>but when i select a value style alwsays empty like this</p>
<p><a href="https://i.stack.imgur.com/QM7Hg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QM7Hg.png" alt="enter image description here"></a></p>
<p>thanks for your help</p>
| 3 | 1,317 |
Android - OpenGL Image doesnt rotate (almost completed)
|
<p>I was following a OpenGL tutorial (<a href="https://developer.android.com/training/graphics/opengl/touch.html#angle" rel="nofollow noreferrer">https://developer.android.com/training/graphics/opengl/touch.html#angle</a>) and I did everything right I think. <strong>My problem is that the triangle doesnt rotate on the display.</strong> I tried to debug and <code>mGLView.requestRender();</code> is getting the values but it doesnt update the image on the screen.</p>
<pre><code>public class OpenGL extends Fragment {
private GLSurfaceView mGLView;
private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private float mPreviousX;
private float mPreviousY;
private OpenGLRenderer mRenderer;
public int height = 0;
public int width = 0;
public OpenGL() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mGLView = new GLSurfaceView(getActivity());
mGLView.setEGLContextClientVersion(2);
mRenderer = new OpenGLRenderer();
mGLView.setRenderer(mRenderer);
// Render the view only when there is a change in the drawing data
mGLView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager()
.getDefaultDisplay()
.getMetrics(displayMetrics);
height = displayMetrics.heightPixels;
width = displayMetrics.widthPixels;
mGLView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent e) {
// MotionEvent reports input details from the touch screen
// and other input controls. In this case, you are only
// interested in events where the touch position changed.
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
float dx = x - mPreviousX;
float dy = y - mPreviousY;
// reverse direction of rotation above the mid-line
if (y > height / 2) {
dx = dx * -1;
}
// reverse direction of rotation to left of the mid-line
if (x < width / 2) {
dy = dy * -1;
}
mRenderer.setAngle(
mRenderer.getAngle() +
((dx + dy) * TOUCH_SCALE_FACTOR));
mGLView.requestRender();
}
mPreviousX = x;
mPreviousY = y;
return true;
}
});
return mGLView;
}
@Override
public void onResume() {
super.onResume();
mGLView.onResume();
}
@Override
public void onPause() {
super.onPause();
mGLView.onPause();
}
</code></pre>
<p>}</p>
<p>class OpenGLRenderer implements GLSurfaceView.Renderer {</p>
<pre><code>private Triangle mRectangle;
private OpenGL mOpenGL = new OpenGL();
// mMVPMatrix is an abbreviation for "Model View Projection Matrix"
private final float[] mMVPMatrix = new float[16];
private final float[] mProjectionMatrix = new float[16];
private final float[] mViewMatrix = new float[16];
private float[] mRotationMatrix = new float[16];
float[] scratch = new float[16];
public volatile float mAngle;
public float getAngle() {
return mAngle;
}
public void setAngle(float angle) {
mAngle = angle;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Set the background frame color
//GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
GLES20.glViewport(0, 0, mOpenGL.width, mOpenGL.height);
float ratio = (float) mOpenGL.width / mOpenGL.height;
// this projection matrix is applied to object coordinates
// in the onDrawFrame() method
Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
mRectangle = new Triangle();
}
public void onDrawFrame(GL10 gl) {
// Redraw background color
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
// Set the camera position (View matrix)
Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
// Calculate the projection and view transformation
Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mViewMatrix, 0);
// Create a rotation for the triangle
// long time = SystemClock.uptimeMillis() % 4000L;
// float angle = 0.090f * ((int) time);
Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
// Combine the rotation matrix with the projection and camera view
// Note that the mMVPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);
// Draw triangle
mRectangle.drawMatrix(scratch);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0, 0, width, height);
}
public static int loadShader(int type, String shaderCode){
// create a vertex shader type (GLES20.GL_VERTEX_SHADER)
// or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
int shader = GLES20.glCreateShader(type);
// add the source code to the shader and compile it
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
</code></pre>
<p>}</p>
<p>class Triangle {</p>
<pre><code> private final String vertexShaderCodeMatrix =
// This matrix member variable provides a hook to manipulate
// the coordinates of the objects that use this vertex shader
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition;" +
"void main() {" +
// the matrix must be included as a modifier of gl_Position
// Note that the uMVPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
" gl_Position = uMVPMatrix * vPosition;" +
"}";
// Use to access and set the view transformation
private int mMVPMatrixHandle;
private final String vertexShaderCode =
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = vPosition;" +
"}";
private final String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float triangleCoords[] = { // in counterclockwise order:
0.0f, 0.622008459f, 0.0f, // top
-0.5f, -0.311004243f, 0.0f, // bottom left
0.5f, -0.311004243f, 0.0f // bottom right
};
// Set color with red, green, blue and alpha (opacity) values
float color[] = { 0.5f, 0.5f, 0.5f, 1.0f };
private final int mProgram;
private short[] indices = {0,1,2,0,2,3};
private FloatBuffer vertexBuffer;
private ShortBuffer indexBuffer;
public Triangle() {
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (number of coordinate values * 4 bytes per float)
triangleCoords.length * 4);
// use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder());
// create a floating point buffer from the ByteBuffer
vertexBuffer = bb.asFloatBuffer();
// add the coordinates to the FloatBuffer
vertexBuffer.put(triangleCoords);
// set the buffer to read the first coordinate
vertexBuffer.position(0);
int vertexShader = OpenGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
vertexShaderCode);
int fragmentShader = OpenGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
fragmentShaderCode);
// create empty OpenGL ES Program
mProgram = GLES20.glCreateProgram();
// add the vertex shader to program
GLES20.glAttachShader(mProgram, vertexShader);
// add the fragment shader to program
GLES20.glAttachShader(mProgram, fragmentShader);
// creates OpenGL ES program executables
GLES20.glLinkProgram(mProgram);
}
private int mPositionHandle;
private int mColorHandle;
private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex
public void draw() {
// Add program to OpenGL ES environment
GLES20.glUseProgram(mProgram);
// get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer);
// get handle to fragment shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
// Set color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
// Draw the triangle
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
}
public void drawMatrix(float[] mvpMatrix) { // pass in the calculated transformation matrix
// Add program to OpenGL ES environment
GLES20.glUseProgram(mProgram);
// get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer);
// get handle to fragment shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
// Set color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
// get handle to shape's transformation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
// Pass the projection and view transformation to the shader
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
// Draw the triangle
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
}
</code></pre>
<p>}</p>
| 3 | 4,377 |
How to get the selected texts and display them?
|
<p>What I'm trying to do is to grab the selected option from each of the selection boxes, click 'submit' and store them in the "stored" paragraph.</p>
<p>Here is my HTML:</p>
<pre><code><body>
<div id="container">
<button id="button" onclick="rolldices()">Roll dices</button>
<span id="dice1">0</span>
<span id="dice2">0</span>
<span id="dice3">0</span>
<span id="dice4">0</span>
<span id="dice5">0</span>
<span id="dice6">0</span>
<br><br><br><br>
<select id="select1">
<option>1
<option>2
<option>3
<option>4
<option>5
<option>6
</select>
<select id="select2">
<option>1
<option>2
<option>3
<option>4
<option>5
<option>6
</select>
<select id="select3">
<option>1
<option>2
<option>3
<option>4
<option>5
<option>6
</select>
<select id="select4">
<option>1
<option>2
<option>3
<option>4
<option>5
<option>6
</select>
<select id="select5">
<option>1
<option>2
<option>3
<option>4
<option>5
<option>6
</select>
<select id="select6">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
<button id="submit" onclick="submit()">Submit your answer</button>
<br><br>
<p id="correct">Correct numbers guessed: </p>
<p id="stored"></p>
</div>
</body>
</html>
</code></pre>
<p>Javascript:</p>
<pre><code>var numbers = [ '1', '2', '3', '4', '5', '6' ];
var dices = [ 'dice1', 'dice2', 'dice3', 'dice4', 'dice5', 'dice6' ];
var select = [ 'select1', 'select2', 'select3', 'select4', 'select5', 'select6']
function rolldices() {
for (var diceindex=0; diceindex<dices.length; diceindex++) {
var dice_value = Math.floor((Math.random()*numbers.length));
document.getElementById("dice" + (diceindex + 1)).innerHTML=numbers[dice_value];
}
} // end of rolldices()
</code></pre>
<p>Here is my attempt at solving the problem:</p>
<pre><code>function submit() {
for (var selectindex=0; selectindex<select.length; selectindex++) {
var e = document.getElementById("select" + (selectindex + 1));
var storedNumbers = e.options[e.selectedIndex].text;
document.getElementById("select" + (selectindex + 1)).text;
document.getElementById("stored").innerHTML=storedNumbers;
}
} // end of submit()
</code></pre>
<p>This works SORT OF, but only the last selectbox's text is being displayed in the "stored" paragraph.. What is wrong?</p>
| 3 | 1,325 |
Passing by value in menu driven Java program
|
<p>I am trying to write a simple program that utilizes passing by value to calculate total revenue for all three ticket classes when user selects option <strong>4</strong>. I want method income_Generated to run all first three methods again so I can pass the revenues calculated from each ticket class to calculate total rev. Is there another way to accomplish the same objective? or can someone show me how this can be done?</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import java.util.Scanner;
public class Functions_Menu_Driven
{
public static void main(String[]args)
{
//call the method menu()
menu();
}//end main
public static void menu()
{
int selection;
double revA,revB,revC;
Scanner keyboard=new Scanner(System.in);
System.out.println("***************************Menu*****************************");
System.out.println("**Calculate revenue from Class A ticket sales [1]**");
System.out.println("**Calculate revenue from Class B ticket sales [2]**");
System.out.println("**Calculate revenue from Class C ticket sales [3]**");
System.out.println("**Revenue from Class A, B and C ticket sales [4]**");
System.out.println("**End [5]**");
//allow user to select a choice
selection=keyboard.nextInt();
if(selection==1)
a();
else if(selection==2)
b();
else if(selection==3)
c();
else if(selection==4)
income_Generated();
else
exit();
keyboard.close();
}
public static void a()
{
double rA, nticketsA;
Scanner keyboard=new Scanner(System.in);
do {
System.out.println("How many Class A tickets were sold? ");
while(!keyboard.hasNextDouble())
{ System.out.println("That's not a number!");
keyboard.next();
}
nticketsA=keyboard.nextDouble();
}while(nticketsA <=0);
System.out.println("Thank you! Got"+nticketsA);
//calculate rev for class A tickets
rA=15*nticketsA;
System.out.printf("Revenue:%5.2f ",rA);
System.out.println("");
income_Generated(rA);
keyboard.close();
//end module
}
public static void b()
{
double rB, nticketsB, costB;
Scanner keyboard=new Scanner(System.in);
do{
System.out.println("How many Class B tickets were sold? ");
while(!keyboard.hasNextDouble())
{ System.out.println("That's not a number!");
keyboard.next();
}
nticketsB=keyboard.nextDouble();
}while(nticketsB<=0);
System.out.println("Thank you! Got"+nticketsB);
//prompt user input for cost of 1 ticket
do{
System.out.println("What is the cost of 1 ticket? ");
while(!keyboard.hasNextDouble())
{ System.out.println("That's not a number!");
keyboard.next();
}
costB=keyboard.nextDouble();
}while(costB<=0);
System.out.println("Thank you! Got"+costB);
//calculate rev for class B tickets
rB=costB*nticketsB;
System.out.printf("Revenue:%5.2f ",rB);
System.out.println("");
income_Generated(rB);
keyboard.close();
//end module
}
public static void c()
{
double rC, nticketsC, costC;
Scanner keyboard=new Scanner(System.in);
do{
System.out.println("How many Class C tickets were sold? ");
while(!keyboard.hasNextDouble())
{ System.out.println("That's not a number!");
keyboard.next();
}
nticketsC=keyboard.nextDouble();
}while(nticketsC<=0);
System.out.println("Thank you! Got"+nticketsC);
//prompt user input for cost of 1 ticket
do{
System.out.println("What is the cost of 1 ticket? ");
while(!keyboard.hasNextDouble())
{ System.out.println("That's not a number!");
keyboard.next();
}
costC=keyboard.nextDouble();
}while(costC<=0);
System.out.println("Thank you! Got"+costC);
//calculate rev for class B tickets
rC=costC*nticketsC;
System.out.printf("Revenue:%5.2f ",rC);
System.out.println("");
income_Generated(rC);
keyboard.close();
//end module
}
public static void income_Generated(revA,revB,revC)
{
a();
b();
c();
Scanner keyboard=new Scanner(System.in);
//calculate total rev
total=revA+revB+revC;
System.out.printf("Total revenue from all ticket classes:%5.2f ",total);
System.out.println("");
keyboard.close();
}
public static void exit()
{
System.out.println("Goodbye!");
}
}</code></pre>
</div>
</div>
</p>
| 3 | 2,144 |
Print filtered array(object) ionic4/angular
|
<p>I didn't understand how to pass data from .ts page to .html page in ionic angular.</p>
<p>Array:</p>
<pre><code>this.s1mstatus = [
{
"code" : "01",
"descr" : "Text1."
},
{
"code" : "02",
"descr" : "Text2."
},
{
"code" : "03",
"descr" : "Text3."
}
]
</code></pre>
<p>HTML page</p>
<pre><code><ion-content fullscreen>
<ion-grid>
<ion-row>
<ion-col>
<ion-item [ngClass]="roundedInput" class="roundedInput">
<ion-input type="text" placeholder="Enter M-Status Code" [(ngModel)]="s1mstatus_get" maxlength="2"></ion-input>
<ion-button type="submit" (click)="mstatussend()">Submit</ion-button>
</ion-item>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-item class="roundedInput">
<ion-input type="text" placeholder="Enter M-Data Code" [(ngModel)]="s1mdata_get"></ion-input>
<ion-button type="submit" (click)="mstatussend()">Submit</ion-button>
</ion-item>
</ion-col>
</ion-row>
</ion-grid>
<ion-list *ngFor="let s1ms of s1filtered">
<ion-card class="card-border">
<ion-card-header>
<ion-card-subtitle>M-STATUS: {{s1ms.code}}</ion-card-subtitle>
</ion-card-header>
<ion-card-content>
<p>ERROR MESSAGE:</p>
<p class="ion-black" [innerHTML]="s1ms.descr"></p>
</ion-card-content>
</ion-card>
</ion-list>
</ion-content>
</code></pre>
<p>FUNCTION TO CHECK IF EMPTY AND "DO SOMETHING" IF ISN'T:</p>
<pre><code>mstatussend() {
if(this.s1mstatus_get=="" || this.s1mstatus_get==undefined){
this.roundedInput = 'invalid';
}
else if(this.s1mstatus_get=="" || this.s1mstatus_get==undefined){
this.roundedInput = 'invalid';
}
else {
this.roundedInput = 'valid';
var s1filtered = this.s1mstatus.filter(element => element.code == this.s1mstatus_get);
console.log(s1filtered);
}
};
</code></pre>
<p>As You can see by the screenshot the console.log command works but I didn't understand how to print those values on the HTML page, maybe it's something easy but is driving me mad.</p>
<p><a href="https://i.stack.imgur.com/6fzIY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6fzIY.png" alt="enter image description here"></a></p>
| 3 | 1,233 |
Bind the error data of datagridrow to a tooltip textblock
|
<p>I am trying to show the validation error message of data grid row in a tooltip. Here is the code that works when I use the ToolTip property of the Grid control directly (wihtout styling):</p>
<pre><code><Grid Margin="0,-2,0,-2" ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=(Validation.Errors)[0].ErrorContent}">
<Ellipse StrokeThickness="0" Fill="Red"
Width="{TemplateBinding FontSize}"
Height="{TemplateBinding FontSize}" />
<TextBlock Text="!" FontSize="{TemplateBinding FontSize}"
FontWeight="Bold" Foreground="White"
HorizontalAlignment="Center" />
</Grid>
</code></pre>
<p>Now this shows the tooltip correctly. Everything is fine.</p>
<p><strong>Problem:</strong></p>
<p>As soon as I start styling the ToolTip separately, the binding stops working somehow. Here is the code that I am trying which does not work:</p>
<pre><code><Grid Margin="0,-2,0,-2">
<Ellipse x:Name="ErrorEllipse" StrokeThickness="0" Fill="Red"
Width="{TemplateBinding FontSize}"
Height="{TemplateBinding FontSize}" />
<TextBlock Text="!" FontSize="{TemplateBinding FontSize}"
FontWeight="Bold" Foreground="White"
HorizontalAlignment="Center"/>
<Grid.ToolTip>
<ToolTip Background="Transparent" BorderBrush="Transparent" Height="Auto" Width="Auto">
<Border >
<TextBlock Text= "{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=(Validation.Errors)[0].ErrorContent}"
MinHeight="20"
MinWidth="100"
Foreground="White"
Background="Red"/>
</Border>
</ToolTip>
</Grid.ToolTip>
</Grid>
</code></pre>
<p>What am I missing here and how can I achieve the proper binding? Probably its something basic but I have no idea...</p>
| 3 | 1,335 |
React native create custom modal using render props
|
<p>I want to create a Modal component and I want to have possibility to inject to it everything what I want. Firstly I decided to use HOC but then I've changed my solution to render props. Everything works fine but I don't really like this solution. I'm wondering how could I optimize it to make it better. What is the best practise to create such kind of modal where you have button opening this modal beyond modal component. I really don't like that now I have two components with open/close state of modal. And both of them have a toggle method to open/close modal. Any suggestion? Maybe I should stick with the HOC ? </p>
<p>Here's the code with Component.js where CustomModal is used:</p>
<pre><code>toggleModalVisibility = (visible) => {
this.setState({modalVisible: visible});
};
render() {
const question = this.props.questions[this.props.counter];
return (
<View style={styles.questionContainer}>
<CustomModal
visible={this.state.modalVisible}
toggleModalVisibility={this.toggleModalVisibility}
render={() => (
<>
<Text>{question.text}</Text>
<Text>{question.details}</Text>
</>
)}
/>
<View style={styles.questionTextContainer}>
<Text style={styles.questionText}>{question.text}</Text>
<TouchableOpacity onPress={() => this.toggleModalVisibility(!this.state.modalVisible) }>
<FontAwesome5 name='question-circle' size={30} color='#B7DBF3' light />
</TouchableOpacity>
</View>
</View>
)
}
</code></pre>
<p>and here's the code of CustomModal.js</p>
<pre><code>export default class CustomModal extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: this.props.visible
};
}
componentDidUpdate(prevProps) {
if (prevProps.visible !== this.props.visible) {
this.setState({isOpen: this.props.visible});
}
}
toggle = (isOpen) => {
this.setState({ isOpen });
this.props.toggleModalVisibility(isOpen)
}
render() {
return (
<View>
<Modal
animationType='slide'
transparent={false}
visible={this.state.isOpen}
>
<View style={{marginTop: 30, marginLeft: 5}}>
<TouchableHighlight
onPress={() => {
this.toggle(!this.state.isOpen)
}}>
<FontAwesome5 name='times-circle' size={30} light />
</TouchableHighlight>
<View>{this.props.render()}</View>
</View>
</Modal>
</View>
)
}
</code></pre>
<p>}</p>
| 3 | 1,622 |
How can I change several Active Directory user passwords?
|
<p>I'm trying to programaticaly change several user's password, specifically without using System.DirectoryServices.AccountManagement (PrincipalContext)
I have this piece of working code:</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
namespace ADScriptService.core
{
class ExportTool
{
const AuthenticationTypes = AuthenticationTypes.Secure | AuthenticationTypes.Sealing | AuthenticationTypes.ServerBind;
private static DirectoryEntry directoryEntry = new DirectoryEntry(ADScriptService.Properties.Settings.Default.ActiveDirectoryPath, ADScriptService.Properties.Settings.Default.ServerAdminUser, ADScriptService.Properties.Settings.Default.ServerAdminPwd, AuthenticationTypes.Secure);
private static DirectorySearcher search = new DirectorySearcher(directoryEntry);
public void Export()
{
string path = ADScriptService.Properties.Settings.Default.ActiveDirectoryPath;
string adminUser = ADScriptService.Properties.Settings.Default.ServerAdminUser;
string adminPassword = ADScriptService.Properties.Settings.Default.ServerAdminPwd;
string userName = "exampleUser";
string newPassword = "P455w0rd";
try
{
search.Filter = String.Format("sAMAccountName={0}", userName);
search.SearchScope = SearchScope.Subtree;
search.CacheResults = false;
SearchResult searchResult = search.FindOne();
if (searchResult == null) Console.WriteLine("User Not Found In This Domain");
DirectoryEntry userEntry = searchResult.GetDirectoryEntry();
userEntry.Path = userEntry.Path.Replace(":389", "");
Console.WriteLine(String.Format("sAMAccountName={0}, User={1}, path={2}", userEntry.Properties["sAMAccountName"].Value, userEntry.Username, userEntry.Path));
userEntry.Invoke("SetPassword", new object[] { newPassword });
userEntry.Properties["userAccountControl"].Value = 0x0200 | 0x10000;
userEntry.CommitChanges();
Console.WriteLine("Se ha cambiado la contraseña");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
</code></pre>
<p>This is an example with a single user, but what my program should do is iterate through ~120k users.
However, the operation of setting the search filter, finding one result and getting the DirectoryEntry takes about 2 or 3 seconds per user so I'm trying to use the DirectoryEntries structure given by the DirectoryEntry.Children property, which means replacing the six lines after "try{" with simply <code>DirectoryEntry userentry = directoryEntry.Children.Find("CN=" + userName);</code></p>
<p>So the example's code would look like this:</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
namespace ADScriptService.core
{
class ExportTool
{
const AuthenticationTypes = AuthenticationTypes.Secure | AuthenticationTypes.Sealing | AuthenticationTypes.ServerBind;
private static DirectoryEntry directoryEntry = new DirectoryEntry(ADScriptService.Properties.Settings.Default.ActiveDirectoryPath, ADScriptService.Properties.Settings.Default.ServerAdminUser, ADScriptService.Properties.Settings.Default.ServerAdminPwd, AuthenticationTypes.Secure);
private static DirectorySearcher search = new DirectorySearcher(directoryEntry);
public void Export()
{
string path = ADScriptService.Properties.Settings.Default.ActiveDirectoryPath;
string adminUser = ADScriptService.Properties.Settings.Default.ServerAdminUser;
string adminPassword = ADScriptService.Properties.Settings.Default.ServerAdminPwd;
string userName = "exampleUser";
string newPassword = "P455w0rd";
try
{
DirectoryEntry userEntry = directoryEntry.Children.Find("CN=" + userName);
userEntry.Path = userEntry.Path.Replace(":389", "");
Console.WriteLine(String.Format("sAMAccountName={0}, User={1}, path={2}", userEntry.Properties["sAMAccountName"].Value, userEntry.Username, userEntry.Path));
userEntry.Invoke("SetPassword", new object[] { newPassword });
userEntry.Properties["userAccountControl"].Value = 0x0200 | 0x10000;
userEntry.CommitChanges();
Console.WriteLine("Se ha cambiado la contraseña");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
</code></pre>
<p>But this code gets the following error in the invocation line <code>(userEntry.Invoke("SetPassword", new object[] { newPassword });</code>:</p>
<pre><code>System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException: The RPC server is unavailable. (Excepción de HRESULT: 0x800706BA)
</code></pre>
<p>which in english means RCP server unavailable. I've been stuck here for some days, and I've only found that it can be because of some authentication problem.
Invoking the method "Groups" works (<code>userEntry.Invoke("Groups");</code>) and the administrator, which is the user I'm loging in with to the ActiveDirectory has all the privileges. Also the password policy is completly permissive with no minimum lenght or complexity.</p>
<p>Again, because the program must iterate through, the real program actually iterates through the DirectoryEntry's children with:</p>
<pre><code>foreach(DirectoryEntry child in directoryEntry.Children)
{
child.Invoke("SetPassword", new object[] { newPassword });
child.CommitChanges();
}
</code></pre>
<p>Thank you very much!</p>
| 3 | 1,936 |
ArrayList printing values missing?
|
<ol>
<li><p>When entering my games in this format: </p>
<p>test : 120 : 120<br>
game : 120 : 120<br>
quit</p></li>
<li><p>My txt file is only showing my first entry and not my second entry, in my text file it is displaying this below: </p>
<p>Player : adam </p>
<hr>
<p>Game: test , score= 120 , minutes played= 120</p></li>
<li><p>But I want it to show: </p>
<p>Game: test , score= 120 , minutes played= 120<br>
Game: feff, score= 3412, minutes played= 434</p></li>
</ol>
<p>So far my code is:</p>
<pre class="lang-java prettyprint-override"><code>import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Generator {
private static char[] input;
public static void main(String[] args) {
int[] minutesPlayed = new int [100];
String gamerName, gamerReport;
String[] gameNames = new String[100];
int[] highScores = new int[100];
@SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
System.out.println("-------------- Game Score Report Generator --------------");
System.out.println(" ");
System.out.print("Enter your Name.");
System.out.println(" ");
gamerName = Scan.nextLine();
boolean isEmpty = gamerName == null || gamerName.trim().length() == 0;
if (isEmpty) {
System.out.print("Enter your Name.");
gamerName = Scan.nextLine();
}
System.out.println("Enter details in this format - " + " --> Game : Achievement Score : Minutes Played");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("quit")) {
break;
}
al.add(word);
} else {
break;
}
}
String[] splitUpReport;
splitUpReport = gamerReport.split(":");
int i = 0;
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data.txt", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
public static char[] getInput() {
return input;
}
}
</code></pre>
| 3 | 1,538 |
Substituting text inside buttons with widgets
|
<p>My app (using kivy) needs to substitute text with widgets inside an unspecified number of buttons using iteration. I don't use kv language. Only the last button displays any content.</p>
<p>My app should display an unspecified number of buttons. Simplified example:</p>
<pre><code>import kivy
kivy.require('2.0.0')
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.image import Image
class Layout(Widget):
def __init__(self, app):
super().__init__()
self.layout = BoxLayout(orientation='vertical', size=Window.size)
contents = ['text1', 'text2', 'text3']
for text in contents:
button = Button(height=300, size_hint=(1, None))
button.text = text
self.layout.add_widget(button)
self.add_widget(self.layout)
class MyApp(App):
def build(self):
self.form = Layout(self)
return self.form
def on_pause(self):
return True
if __name__ in ('__main__', '__android__'):
MyApp().run()
</code></pre>
<p>Only instead of text buttons display images with descriptions. I change the code:</p>
<pre><code>import kivy
kivy.require('2.0.0')
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.image import Image
class Layout(Widget):
def __init__(self, app):
super().__init__()
self.layout = BoxLayout(orientation='vertical', size=Window.size)
contents = [('img1', 'text1'), ('img2', 'text2'), ('img3', 'text3')]
for img, text in contents:
button = Button(height=300, size_hint=(1, None))
button_layout = BoxLayout(orientation='vertical', size_hint=(1, 1))
label = Label(text=text)
image = Image(source=f'{img}.jpg', size_hint=(1, 1), allow_stretch=True)
button_layout.add_widget(image)
button_layout.add_widget(label)
button.add_widget(button_layout)
self.layout.add_widget(button)
self.add_widget(self.layout)
class MyApp(App):
def build(self):
self.form = Layout(self)
return self.form
def on_pause(self):
return True
if __name__ in ('__main__', '__android__'):
MyApp().run()
</code></pre>
<p>And only the last button displays content.</p>
<p>As far as I can understand, at some point Python automatically gets read of the content of the previous button. How can I prevent it? Also what is the best way to center it?
I'm not a native speaker, so sorry for bad grammar. Thank you in advance.</p>
| 3 | 1,290 |
Vue - Component abstraction and inheritance
|
<p>I have a Vue application that allows users to create quizzes made up of different types of questions. I have multiple choice questions (both single selection/radio button and multiple selection/checkbox), open answer, attachment answer, so on and so forth.</p>
<p>I'm looking to create a generic <code>Question</code> component that will display the correct type of input (text editor, radio buttons, file input, etc.) depending on the type of question.</p>
<p>Let's assume I am using TS and I have a <code>Question</code> interface with a field <code>questionType</code> that easily allows differentiating among the types of questions.</p>
<p>The solution I've come up with is the following:</p>
<p>I have an <code>AbstractQuestion</code> component that defines the general template of the questions, i.e. there's a slot for displaying the question text and one for the inputs.</p>
<p>Then, for each type of question, there's a component, e.g. <code>OpenAnswerQuestion</code>, in whose template there is an <code>AbstractQuestion</code> with the slots filled with the correct template parts. Finally, I expose to the rest of the app a <code>Question</code> component that uses <code><component :is="..."></code> to dynamically display the correct question type.</p>
<p>AbstractQuestion.vue</p>
<pre><code><template>
<div>
<slot name="questionText">
<p v-html="exercise.text" />
</slot>
<!-- contains the input controls to answer the question
(e.g. checkboxes, textareas...) -->
<slot
v-if="!readOnly || !$slots.readOnlyAnswer?.()"
name="submissionControls"
></slot>
<!-- representation of a read-only answer given to the question (e.g. a code fragment for a programming exercise) -->
<slot v-else name="readOnlyAnswer"></slot>
<slot name="solution"></slot>
</div>
</template>
<script lang="ts">
import { defineComponent, PropType } from "@vue/runtime-core";
export default defineComponent({
name: "AbstractQuestion",
props: {
question: {
type: Object as PropType<Question>,
required: true,
},
readOnly: {
type: Boolean,
default: false,
},
},
});
</script>
</code></pre>
<p>Example of an "inheriting" question type:</p>
<p>OpenAnswerQuestion.vue</p>
<pre><code><template>
<AbstractQuestion v-bind="$props">
<template #submissionControls>
<TextEditor
:disabled="readOnly"
v-model="answerTextProxy"
/>
</template>
<template #readOnlyAnswer>
<p
v-html="answerTextProxy"
/>
</template>
</AbstractQuestion>
</template>
<script lang="ts">
import { defineComponent, PropType } from "@vue/runtime-core";
import TextEditor from "@/components/ui/TextEditor.vue";
import AbstractExercise from "./AbstractQuestion.vue";
export default defineComponent({
name: "OpenAnswerQuestion",
props: {
question: {
type: Object as PropType<Question>,
required: true,
},
answer: {
type: String,
default: "",
},
readOnly: {
type: Boolean,
default: false,
},
},
methods: {},
computed: {
answerTextProxy: {
get() {
return this.answer;
},
set(val: string) {
this.$emit("updateAnswerText", val);
},
},
},
components: { TextEditor, AbstractQuestion },
});
</script>
</code></pre>
<p>And the component actually exposed:
Question.vue</p>
<pre><code><template>
<component :is="questionComponentName" v-bind="$props"></component>
</template>
<script lang="ts">
import { defineComponent, PropType } from "@vue/runtime-core";
export default defineComponent({
name: "Question",
props: {
question: {
type: Object as PropType<Question>,
required: true,
},
readOnly: {
type: Boolean,
default: false,
},
},
methods: {},
computed: {
questionComponentName(): string {
const componentNames: Record<QuestionType, string> = {
[QuestionType.OPEN_ANSWER]: "OpenAnswerQuestion",
// ... rest of the mapping
};
return componentNames[this.question.questionType];
},
},
});
</script>
</code></pre>
<p>This seems to be working, but it feels kinda hacky. Is there a better way to achieve this specialization/dynamic dispatch/abstraction of components in Vue3?</p>
| 3 | 1,875 |
Jest function fails to fire after network request in react component
|
<p>Full Repo</p>
<p><a href="https://github.com/brianbancroft/sample-testing-msw-sb-jest-rtl" rel="nofollow noreferrer">https://github.com/brianbancroft/sample-testing-msw-sb-jest-rtl</a></p>
<p>Using mock service worker (msw) to respond to a network request, I have a React login component. On submit it sends a network request and on success it is supposed to trigger a "handleClose" function which is a prop to the component.</p>
<pre class="lang-js prettyprint-override"><code>async function handleSubmit(event) {
event.preventDefault();
setLoading(true);
const { username, password } = event.target.elements;
try {
const response = await fetch("/login", {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
redirect: "follow",
referrerPolicy: "no-referrer",
body: JSON.stringify({
username: username.value,
password: password.value,
}),
});
await response.json();
if (response.status === 200) {
props.handleClose();
} else {
setInvalidUsernamePassword(true);
setLoading(false);
}
} catch (error) {
alert("Error detected", error);
}
}
</code></pre>
<p>When I test, I validate that the function <code>handleClose</code> is invoked.</p>
<pre class="lang-js prettyprint-override"><code>
const setup = async () => {
const handleClose = jest.fn();
const utils = await render(<Primary handleClose={handleClose} />);
const usernameField = screen.getByLabelText(/Username/);
const passwordField = screen.getByLabelText(/Password/);
const submitButton = screen.getByRole("button", {
name: /Sign In/i,
});
return {
usernameField,
passwordField,
submitButton,
handleClose,
...utils,
};
};
test("The handleClose function prop is triggered", async () => {
const { usernameField, passwordField, submitButton, handleClose } =
await setup();
fireEvent.change(usernameField, { target: { value: faker.lorem.word() } });
fireEvent.change(passwordField, { target: { value: faker.lorem.word() } });
fireEvent.click(submitButton);
expect(handleClose).toHaveBeenCalled();
});
</code></pre>
<p>This fails</p>
<pre><code>
Expected number of calls: >= 1
Received number of calls: 0
</code></pre>
<p>However, when I invoke the prop function before the start of the async function, it passes, which tells me it's not how I am passing the jest.fn() into the component.</p>
<p>I have investigated whether an error gets thrown (it doesn't), and I also know that <code>msw</code> is working as intended, and that the network request responds with a 200 unless I send a password value of "badpassword" which is used to simulate an incorrect email or password in another test in the same file.</p>
<p>I also converted the function to use promises. No change.</p>
| 3 | 1,159 |
Why some methods are not either private or public?
|
<p>I have seen some examples that don't declare methods to be private or public. Just static like: <code>static Bitmap resamplePic(Context context, String imagePath)</code></p>
<p>Why is that? And when to do that?
This is my example code:</p>
<pre><code>/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.emojify;
import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.support.v4.content.FileProvider; import android.util.DisplayMetrics; import android.view.WindowManager; import android.widget.Toast;
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
class BitmapUtils {
private static final String FILE_PROVIDER_AUTHORITY = "com.example.android.fileprovider";
/**
* Resamples the captured photo to fit the screen for better memory usage.
*
* @param context The application context.
* @param imagePath The path of the photo to be resampled.
* @return The resampled bitmap
*/
static Bitmap resamplePic(Context context, String imagePath) {
// Get device screen size information
DisplayMetrics metrics = new DisplayMetrics();
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
manager.getDefaultDisplay().getMetrics(metrics);
int targetH = metrics.heightPixels;
int targetW = metrics.widthPixels;
// Get the dimensions of the original bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
return BitmapFactory.decodeFile(imagePath);
}
/**
* Creates the temporary image file in the cache directory.
*
* @return The temporary image file.
* @throws IOException Thrown if there is an error creating the file
*/
static File createTempImageFile(Context context) throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getExternalCacheDir();
return File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
}
/**
* Deletes image file for a given path.
*
* @param context The application context.
* @param imagePath The path of the photo to be deleted.
*/
static boolean deleteImageFile(Context context, String imagePath) {
// Get the file
File imageFile = new File(imagePath);
// Delete the image
boolean deleted = imageFile.delete();
// If there is an error deleting the file, show a Toast
if (!deleted) {
String errorMessage = context.getString(R.string.error);
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
}
return deleted;
}
/**
* Helper method for adding the photo to the system photo gallery so it can be accessed
* from other apps.
*
* @param imagePath The path of the saved image
*/
private static void galleryAddPic(Context context, String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
/**
* Helper method for saving the image.
*
* @param context The application context.
* @param image The image to be saved.
* @return The path of the saved image.
*/
static String saveImage(Context context, Bitmap image) {
String savedImagePath = null;
// Create the new file in the external storage
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + ".jpg";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Emojify");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
// Save the new Bitmap
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(context, savedImagePath);
// Show a Toast with the save location
String savedMessage = context.getString(R.string.saved_message, savedImagePath);
Toast.makeText(context, savedMessage, Toast.LENGTH_SHORT).show();
}
return savedImagePath;
}
/**
* Helper method for sharing an image.
*
* @param context The image context.
* @param imagePath The path of the image to be shared.
*/
static void shareImage(Context context, String imagePath) {
// Create the share intent and start the share activity
File imageFile = new File(imagePath);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri photoURI = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, imageFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
context.startActivity(shareIntent);
} }
</code></pre>
| 3 | 2,663 |
Error : Cannot call methods on dialog prior to initialization; Attempted to call method 'close'
|
<p>I have cancel button that is not working properly on a JQuery Modal Dialog and I would really appreciate some help. This is the exception I'm getting when I click on the cancel button of the modal: JavaScript runtime error: cannot call methods on dialog prior to initialization; attempted to call method 'close'</p>
<p>This is the partial view I'm displaying on the modal: </p>
<pre><code>@model Models.Office
@{
Layout = null;
}
@Scripts.Render("~/bundles/query-1.8.2.js")
@Scripts.Render("~/bundles/jquery-ui.js")
@Styles.Render("~/Content/bootstrap")
@Scripts.Render("~/bundles/bootstrap")
@Styles.Render("~/Content/css")
@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function CloseModal() {
$(this).dialog("close");
}
</script>
@*@using (Ajax.BeginForm("EditOffice", "Admin", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "edit-Dialog" }))*@
@using (Html.BeginForm("CreateEditOffice", "Admin", "POST"))
{
<fieldset>
<legend>Office</legend>
@if (ViewBag.IsUpdate == true)
{
@Html.HiddenFor(model => model.OfficeId)
}
<div class="display-label">
@Html.DisplayNameFor(model => model.OfficeName)
</div>
<div class="Input-medium">
@Html.EditorFor(model => model.OfficeName)
@Html.ValidationMessageFor(model => Model.OfficeName)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.SupportNo)
</div>
<div class="Input-medium">
@Html.EditorFor(model => model.SupportNo)
@Html.ValidationMessageFor(model => model.SupportNo)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.SupportEmail)
</div>
<div class="Input-medium">
@Html.EditorFor(model => model.SupportEmail)
@Html.ValidationMessageFor(model => model.SupportEmail)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.SupportFax)
</div>
<div class="Input-medium">
@Html.EditorFor(model => model.SupportFax)
@Html.ValidationMessageFor(model => model.SupportFax)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.SupportFtp)
</div>
<div class="Input-medium">
@Html.EditorFor(model => model.SupportFtp)
@Html.ValidationMessageFor(model => model.SupportFtp)
</div>
</fieldset>
<br />
<div class="pull-right">
@if (ViewBag.IsUpdate == true)
{
<button class="btn btn-primary" type="submit" id="btnUpdate" name="Command" value ="Update">Update</button>
}
else
{
<button class="btn btn-primary" type="submit" id="btnSave" name="Command" value="Save">Save</button>
}
<button type="button" id="Cancel" class="btn btn-primary" onclick="CloseModal()">Cancel</button>
</div>
}
//Then this is the scrip on the parent view:
<script type="text/javascript">
$(document).ready(function () {
$(".editDialog").on("click", function (e) {
// e.preventDefault(); use this or return false
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Office',
autoOpen: false,
resizable: false,
height: 450,
width: 380,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$("#dialog-edit").dialog().dialog('close');
}
});
$("#dialog-edit").dialog('open');
return false;
});
});
</script>
</code></pre>
<p>What I'm I doing wrong ????
Also when i remove reference of above jquery file its work perfectly.</p>
| 3 | 2,269 |
Plot rows of numbers that fall within a defined proximity to other rows in R
|
<p>I have a dataframe of numbers (genetics data) on different chromosomes that can be considered factors to separate the numbers on. It looks like this (with adjacent columns containing Sample info for each position): </p>
<pre><code>awk '{print $2 "\t" $3}' log_values | head
Chr Start Sample1 Sample2
1 102447376 0.46957632 0.38415043
1 102447536 0.49194950 0.30094824
1 102447366 0.49874880 -0.17675325
2 102447366 -0.01910729 0.20264680
1 108332063 -0.03295081 0.07738970
1 109472445 0.02216355 -0.02495788
</code></pre>
<p>What I want do is to make a series of plots taking values from other columns in this file. Instead of plotting one for each row (which would represent the results in a different region and/or different sample), I want to draw plots covering ranges if there are values in the Start column close enough to each other. To start, I would like a plot to be made if there are three values in the Start column within say 1000 of each other. That is, a 1000 from A to B to C inclusive so that A to B <= 1000 and B to C is <= 1000 but A to C does not have to be <= 1000. In the code below, this 1000 is "CNV_size". The "flanking_size" variable is just to zoom the plot out a bit so I can give it some context. </p>
<p>Taking the sample values, Rows 1 2 and 3 would be highlighted as one plot for Sample1. These sample numbers are log2Ratios so I only want to plot the significant ones. I define this as above 0.4 or below -0.6. This means that the same three rows would not yield a plot for sample 2. </p>
<p>The fourth row would not be included as the Chr column number/factor is different. That's a separate plot for each column showing the values only in the rows that meet this condition. So I can have more than plot per sample but each set of regions that meets this criterion will be plotted in all samples. If this doesn't make sense, perhaps my ineffective attempt below will help explain what I'm waffling about. </p>
<pre><code>pdf("All_CNVs_closeup.pdf")
CNV_size <- 1000 # bp
flanking_size <- 1000 # bp
#for(chr in 1:24){
for(chr in 1:1){
#for(array in 1:24) {
for(array in 1:4) {
dat <- subset(file, file$Chr == chr )
dat <- subset(dat, dat[,array+6] > 0.4 | dat[,array+6] < -0.6)
if(length(dat$Start) > 1 ) {
dat <- dat[with(dat, order(Start)), ]
x=dat$Start[2:length(dat$Start)]-dat$Start[1:(length(dat$Start)-1)]
cnv <- 1
while(cnv <= length(x)) {
for(i in cnv:length(x) ) {
if(x[i] >= CNV_size) {
plot_title <- paste(sample_info$Sample.ID[array], files[array], sep = " ")
plot(dat$Start, -dat[,array+6], main = plot_title , ylim = c(-2,2), xlim = c(dat$Start[cnv] - flanking_size , dat$Start[i ] + flanking_size) , xlab = chr, ylab = "Log2 Ratio")
abline(h = 0.4, col="blue")
abline(h = 0, col="red")
abline(h = -0.6, col="blue")
break
} # if(x[i] >= CNV_size) {
#if(x[i] < CNV_size) i <- i + 1
} # for(i in cnv:length(x) ) {
cnv <- i
} # while(x[cnv] <= length(x)) {
} # if(length(dat$Start) > 1 ) {
} # for(array in 1:24) {
} # for(chr in 1:24){
dev.off()
</code></pre>
| 3 | 1,225 |
Reading CSV From R returning an error and weird html
|
<p>So my script below reads a csv from google drive:</p>
<pre><code> ---
title: "Funnel"
output:
flexdashboard::flex_dashboard:
orientation: rows
vertical_layout: fill
runtime: shiny
---
</code></pre>
<pre><code>
#rm(list = ls())
library(flexdashboard)
library(dplyr)
library(ggplot2)
library(collapsibleTree)
library(rsconnect)
library(shiny)
library(googledrive)
options(shiny.sanitize.errors = FALSE)
</code></pre>
<pre><code>#id = '1Jj6nj1FivQHC7b5yzd3JeFfPwyTHbsGr'
#df = read.csv(paste0("https://docs.google.com/uc?id=",id,"&export=download"))
id = "1Jj6nj1FivQHC7b5yzd3JeFfPwyTHbsGr"
df = read.csv(sprintf("https://docs.google.com/uc?id=%s&export=download", id))
</code></pre>
<p>The weird part is I get this error despite trouble shooting it 20x times</p>
<pre><code>Warning message:
In read.table(file = file, header = header, sep = sep, quote = quote, :
incomplete final line found by readTableHeader on 'https://docs.google.com/uc?id=1Jj6nj1FivQHC7b5yzd3JeFfPwyTHbsGr&export=download'
</code></pre>
<p>When i see my dataframe object which is supposed to return a table, I get this mess:</p>
<pre><code> X..DOCTYPE.html..html..head..title.Google.Drive...Can..39.t.download.file..title..meta.http.equiv.content.type.content.text.html..charset.utf.8...link.href...47.static..47.doclist..47.client..47.css..47.2417655298..45.untrustedcontent.css.rel.stylesh ...
1 </style><script nonce=8+qjBlQaWdaiN/Ce45c+kQ></script></head><body><div id=gbar><nobr><a target=_blank class=gb1 href=https://www.google.com/webhp?tab=ow>Search</a> <a target=_blank class=gb1 href=http://www.google.com/imghp?hl=en&tab=oi>Images</a> <a target=_blank class=gb1 href=https://maps.google.com/maps?hl=en&tab=ol>Maps</a> <a target=_blank class=gb1 href=https://play.google.com/?hl=en&tab=o8>Play</a> <a target=_blank class=gb1 href=https://www.youtube.com/?gl=US&tab=o1>YouTube</a> <a target=_blank class=gb1 href=https://news.google.com/?tab=on>News</a> <a target=_blank class=gb1 href=https://mail.google.com/mail/?tab=om>Gmail</a> <b class=gb1>Drive</b> <a target=_blank class=gb1 style=text-decoration:none href=https://www.google.com/intl/en/about/products?tab=oh><u>More</u> &raquo;</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a target=_self href=/settings?hl=en_US class=gb4>Settings</a> | <a target=_blank href=//support.google.com/drive/?p=web_home&hl=en_US class=gb4>Help</a> | <a target=_top id=gb_70 href=https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://docs.google.com/uc%3Fid%3D1Jj6nj1FivQHC7b5yzd3JeFfPwyTHbsGr%26export%3Ddownload&service=writely&ec=GAZAMQ class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div><div class=uc-main><div id=uc-text><p class=uc-error-caption>Sorry
X.guser.font.size.13px.padding.top.0px..important...gbar.height.22px..guser.padding.bottom.7px..important.text.align.right..gbh
1 the owner hasn&#39;t given you permission to download this file.</p><p class=uc-error-subcaption>Only the owner and editors can download this file. If you'd like to download it
.gbd.border.top.1px.solid..c9d7f1.font.size.1px..gbh.height.0.position.absolute.top.24px.width.100...media.all..gb1.height.22px.margin.right..5em.vertical.align.top..gbar.float.left..a.gb1
1 please contact the owner.</p></div></div><div class=uc-footer><hr class=uc-footer-divider>&copy; 2021 Google - <a class=goog-link href=//support.google.com/drive/?p=web_home>Help</a> - <a class=goog-link href=//support.google.com/drive/bin/answer.py?hl=en_US&amp;answer=2450387>Privacy & Terms</a></div></body></html>
a.gb4.text.decoration.underline..important.a.gb1
1 NA
a.gb4.color..00c..important..gbi..gb4.color..dd8e27..important..gbf..gb4.color..900..important.
1
</code></pre>
<p>Or in a different view:</p>
<p><a href="https://i.stack.imgur.com/1rQAt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1rQAt.png" alt="Error screen shot" /></a></p>
<p>Unfortunately, while it works if I download the csv and read it, I was hoping to just read it through the g-drive without downloading it locally.</p>
| 3 | 2,428 |
Django Rest Framework serialize additional fields from intermediate model
|
<p>I am developing a small application that lists the customers of a store. I'm trying to retrieve the additional fields of the intermediate model because a contact can belong to several stores but depending on the store it is premium or not and if he is happy or not.</p>
<p>Here's the JSON response I'd like to get for a Store like <strong>/contacts/?store=my_store</strong></p>
<pre><code>[
{
"id": "UX",
"first_name": "UX",
"last_name": "UX",
"email": null,
"mobile": null,
"happy": True,
"premium": True
},
{
"id": "AX",
"first_name": "AX",
"last_name": "AX",
"email": null,
"mobile": null,
"happy": False,
"premium": True
}
]
</code></pre>
<p>here are my models:</p>
<pre><code>class Store(BaseModel):
id = models.CharField(primary_key=True, max_length=200)
name = models.CharField(max_length=100)
class Contact(BaseModel):
id = models.CharField(primary_key=True, max_length=200)
first_name = models.CharField(max_length=100, null=True, blank=True)
last_name = models.CharField(max_length=100, null=True, blank=True)
email = models.CharField(max_length=100, null=True, blank=True)
mobile = models.CharField(max_length=100, null=True, blank=True)
stores = models.ManyToManyField(
Store, through="MemberShip", through_fields=("contact", "store")
)
class MemberShip(BaseModel):
contact = models.ForeignKey(
Contact, on_delete=models.CASCADE, related_name="contact_to_store"
)
store = models.ForeignKey(
Store, on_delete=models.CASCADE, related_name="store_to_contact"
)
happy = models.BooleanField(default=True)
premium = models.BooleanField(default=False)
</code></pre>
<p>and my serializers:</p>
<pre><code>class MemberShipSerializer(serializers.ModelSerializer):
class Meta:
model = MemberShip
fields = ("contact", "store", "happy", "premium")
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = Store
fields = ("id", "name")
class ContactSerializer(serializers.ModelSerializer):
infos = MemberShipSerializer(
source="contact_to_store" many=True, read_only=True
)
class Meta:
model = Contact
fields = (
"id", "first_name", "last_name", "email", "mobile", "infos"
)
</code></pre>
<p>As you can see, I first tried to gather all the information of the intermediate model in a field before displaying <strong>happy</strong> and <strong>premium</strong> but, strangely enough, the <strong>infos</strong> field is returned with an empty array value.
Python v 3.7
Django v 2.1
DRF v 3.9</p>
| 3 | 1,067 |
MVC Parent Child Modal File Upload problem
|
<p>I have a parent child scenario for getting header detail data. here is my code attached, the problem is when i use a file upload it does not work</p>
<p><code>Person</code> Model:</p>
<pre><code>public class Person
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Display(Name = "First Name")]
[Required]
[StringLength(255, MinimumLength = 3)]
public string Name { get; set; }
[Display(Name = "Last Name")]
[Required]
[StringLength(255, MinimumLength = 3)]
public string Surname { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Error: Must Choose a Country")]
[Range(1, int.MaxValue, ErrorMessage = "Select a Country")]
public int CountryID { get; set; }
public virtual Country Country { get; set; }
}
</code></pre>
<p><code>Address</code> Model:</p>
<pre><code>public class Address
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Error: Must Choose a City")]
[Range(1, int.MaxValue, ErrorMessage = "Select a City")]
public int CityID { get; set; }
public virtual City City { get; set; }
[Required]
[Display(Name = "Street Address")]
public string Street { get; set; }
[Required]
[DataType(DataType.ImageUrl)]
public string ImageUrl { get; set; }
[NotMapped]
[DataType(DataType.Upload)]
public HttpPostedFileBase ImageUpload { get; set; }
[Required]
[Phone]
public string Phone { get; set; }
public int PersonID { get; set; }
public virtual Person Person { get; set; }
}
</code></pre>
<p><code>PeopleController</code>:</p>
<pre><code>private DataDb db = new DataDb();
// GET: People
public async Task<ActionResult> Index()
{
return View(await db.People.ToListAsync());
}
// GET: People/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = await db.People.Where(p => p.Id == id).Include(p => p.Addresses).SingleAsync();
if (person == null)
{
return HttpNotFound();
}
return View(person);
}
// GET: People/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var person = await db.People
.Include(p => p.Addresses)
.Where(p => p.Id == id)
.SingleAsync();
if (person == null)
{
return HttpNotFound();
}
ViewBag.CountryID = new SelectList(db.Country, "CountryID", "CountryName", person.CountryID);
return View(person);
}
// POST: People/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit( Person person)
{
if (ModelState.IsValid)
{
db.Entry(person).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.CountryID = new SelectList(db.Country, "CountryID", "CountryName", person.CountryID);
return View(person);
}
// GET: People/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = await db.People.FindAsync(id);
if (person == null)
{
return HttpNotFound();
}
return View(person);
}
// POST: People/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Person person = await db.People.FindAsync(id);
db.People.Remove(person);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
</code></pre>
<p><code>Address</code> Controller:</p>
<pre><code>private DataDb db = new DataDb();
public ActionResult Index(int id)
{
ViewBag.PersonID = id;
var addresses = db.Addresses.Where(a => a.PersonID == id).OrderBy(a => a.City.CityName);
return PartialView("_Index", addresses.ToList());
}
[ChildActionOnly]
public ActionResult List(int id)
{
ViewBag.PersonID = id;
var addresses = db.Addresses.Where(a => a.PersonID == id);
return PartialView("_List", addresses.ToList());
}
public ActionResult Create(int PersonID)
{
//Address address = new Address();
//address.PersonID = PersonID;
//FillCity(address);
Address adv = new Address();
adv.PersonID = PersonID;
FillCityModel(adv);
return PartialView("_Create", adv);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Address address, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
int addressID = clsStatic.newAddressID();
address.Id = addressID;
var uploadDir = "~/images";
var imagePath = Path.Combine(Server.MapPath(uploadDir), address.ImageUpload.FileName);
var imageUrl = Path.Combine(uploadDir, address.ImageUpload.FileName);
address.ImageUpload.SaveAs(imagePath);
address.ImageUrl = imageUrl;
db.Addresses.Add(address);
db.SaveChanges();
string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
return Json(new { success = true, url = url });
}
FillCity(address);
return PartialView("_Create", address);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Address address = db.Addresses.Find(id);
if (address == null)
{
return HttpNotFound();
}
//ViewBag.CityID = new SelectList(db.City, "CityID", "CityName", address.CityID);
FillCity(address);
return PartialView("_Edit", address);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Address address )
{
var uploadDir = "~/images";
if (address.ImageUpload != null)
{
var imagePath = Path.Combine(Server.MapPath(uploadDir), address.ImageUpload.FileName);
var imageUrl = Path.Combine(uploadDir, address.ImageUpload.FileName);
address.ImageUpload.SaveAs(imagePath);
address.ImageUrl = imageUrl;
}
if (ModelState.IsValid)
{
db.Entry(address).State = EntityState.Modified;
db.SaveChanges();
string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
return Json(new { success = true, url = url });
}
//var file = Request.Files[0];
//if (file != null && file.ContentLength > 0)
//{
// var fileName = address.Id + Path.GetExtension(file.FileName);
// var path = Path.Combine(Server.MapPath("~/Images/Addresses/"), fileName);
// file.SaveAs(path);
//}
FillCity(address);
//ViewBag.CityID = new SelectList(db.City, "CityID", "CityName", address.CityID);
return PartialView("_Edit", address);
}
private void FillCity(Address address)
{
List<SelectListItem> city = new List<SelectListItem>();
foreach (City item in db.City)
{
if (item.CityID != address.CityID)
city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString() });
else
city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString(), Selected = true });
}
ViewBag.CityID = city;
}
private void FillCityModel(Address address)
{
List<SelectListItem> city = new List<SelectListItem>();
foreach (City item in db.City)
{
if (item.CityID != address.CityID)
city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString() });
else
city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString(), Selected = true });
}
ViewBag.CityID = city;
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Address address = db.Addresses.Find(id);
if (address == null)
{
return HttpNotFound();
}
return PartialView("_Delete", address);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Address address = db.Addresses.Find(id);
db.Addresses.Remove(address);
db.SaveChanges();
string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
return Json(new { success = true, url = url });
}
</code></pre>
<p>Here in <code>_Edit</code> View of Address I want to have File Upload Field</p>
<pre><code>@model TestAjax.Models.Address
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Edit Address</h4>
</div>
<div class="modal-body">
@using (Html.BeginForm("Edit", "Addresses", FormMethod.Post,
new { id = "editForm", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.PersonID)
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.CityID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CityID, (List<System.Web.Mvc.SelectListItem>)ViewBag.CityID, new { @class = "form-control selectpicker" })
@Html.ValidationMessageFor(model => model.CityID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Street, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Street, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Street, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="editor-field">
@Html.LabelFor(m => m.ImageUpload)
@Html.TextBoxFor(m => m.ImageUpload, new { type = "file" })
</div>
</div>
<button class="btn" type="button" data-dismiss="modal">Cancel</button>
<input class="btn btn-primary" type="submit" value="Save" />
}
</div>
<div class="modal-footer">
Footer
</div>
<script>
$(document).ready(function () {
refill();
});
function refill() {
var id = @Model.CityID;
$('#CityID').val(id);
}
</script>
</code></pre>
<p>But when i press the save button in address controller edit action i don't have the file selected.
please help.</p>
<p><a href="https://drive.google.com/open?id=18mdmf5E39ATxE3dfSXZFkngA6-ouO4QM" rel="nofollow noreferrer">Download Source Code</a></p>
| 3 | 5,055 |
ffmpeg Python command only runs once in PM2 environment
|
<p>PM2 is running as a <code>web</code> user. ffmpeg was installed native to Ubuntu 16.04 LTS using <code>sudo apt install ffmpeg</code>. The Python version is 3.6. The software uses <a href="https://github.com/kkroening/ffmpeg-python" rel="nofollow noreferrer">ffmpeg-python@0.1.17</a>.</p>
<p>The applications spawned produce no errors. When the ffmpeg code executes for the first time, we see an output and the ffmpeg process completes the task as expected. </p>
<p>All subsequent requests stall on the next ffmpeg execution. No output. No return from the ffmpeg process. No errors. The PM2 process does not error out. The application log stalls on the ffmpeg command as though it is hung.</p>
<p><strong>What is the root cause?</strong> Any help is deeply appreciated.</p>
<p>Furthermore, what are the reasons PM2 hangs on a subprocess (like ffmpeg)?</p>
<p>Here is the code:</p>
<pre><code>class ImageHelper:
def __init__(self):
pass
@classmethod
def create_thumb_from_video_ffmpeg(cls, input_video_file_path,
output_image_path,
scale_width,
scale_height
):
"""
This function is used to create the thumb image
from a source video file.
We are using a python wrapper/library for FFMPEG
"""
try:
if Functions.get_attribute_env('ENVIRONMENT') == 'prod':
out, err = (
ffmpeg
.input(input_video_file_path, ss="00:00:00.001")
.filter('scale', scale_width, scale_height)
.output(output_image_path, vframes=1, loglevel='quiet')
.overwrite_output()
.run(capture_stdout=True)
)
print("We only see this once!")
else:
out, err = (
ffmpeg
.input(input_video_file_path, ss="00:00:00.001")
.filter('scale', scale_width, scale_height)
.output(output_image_path, vframes=1)
.overwrite_output()
.run(capture_stdout=True)
)
print("We only see this once!")
if err:
if Functions.get_attribute_env('ENVIRONMENT') != 'prod':
print('ffmpeg video thumb', err)
else:
Functions.logger_function(str(err))
raise Exception(err)
else:
return output_image_path
except Exception as e:
if Functions.get_attribute_env('ENVIRONMENT') != 'prod':
print('in thumb exception', e)
else:
Functions.logger_function(str(e))
raise Exception(e)
</code></pre>
| 3 | 1,320 |
Listview show only last item over and over
|
<p>I am new to android development. I enrolled Udacity course and I get to where I have to use a costume arrayAdapter to display a listView of data (text) I nailed most of it but i have a problem with data displayed which is : when I launch my activity listView displays last item on may arraylist
i have tried almost everything out their nothing worked for me</p>
<p>My Data </p>
<pre><code>/**
* Displays text to the user.
*/
public class Numbers {
//First we Set the Stat of our Class :
// English Translation
public static String englishTranslation;
//Tamazight Translation
public static String tamazightTranslation;
/**
* Create a new Numbers Object :
*
* @param englishTranslation is for ENGLISH NUMBERS
* @param tamazightTranslation is for TAMAZIGHT NUMBERS
*/
//Constructor
public Numbers(String englishTranslation, String tamazightTranslation) {
this.englishTranslation = englishTranslation;
this.tamazightTranslation = tamazightTranslation;
}
//Getter
public static String getEnglishTranslation() {
return englishTranslation;
}
public static String getTamazightTranslation() {
return tamazightTranslation;
}
}
</code></pre>
<p><br>
My ArrayList : </p>
<pre><code>public class ActivityNumbers extends AppCompatActivity {
//Add English numbers to The ARRAYList
ArrayList<Numbers> englishNumbers = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
englishNumbers.add(new Numbers("One", "Yan"));
englishNumbers.add(new Numbers("Two", "Sin"));
englishNumbers.add(new Numbers("Three", "Krad"));
englishNumbers.add(new Numbers("Four", "Koz"));
englishNumbers.add(new Numbers("Five", "Smos"));
englishNumbers.add(new Numbers("Six", "Sdis"));
englishNumbers.add(new Numbers("Seven", "Sa"));
englishNumbers.add(new Numbers("Eight", "Tam"));
englishNumbers.add(new Numbers("Nine", "Tza"));
englishNumbers.add(new Numbers("Ten", "Mraw"));
//EnglishNumbers.remove(0);
//EnglishNumbers.size();
// EnglishNumbers.get(1);
//Create a NEW TV object
/**Creating an ArrayAdapter (DATA HOLDER)
@param Context / the ACTIVITY concerned
@param Android.R.layout : an XML layout file contains TextView predefined by Android
@param Items to display */
NumbersAdapter itemsAdapter = new NumbersAdapter (this, englishNumbers);
// Linking the ListView object to a Variable
ListView numbersListView = (ListView) findViewById(R.id.list);
//Calling setAdapter Method on numbersListView with "itemsAdapter
numbersListView.setAdapter(itemsAdapter);
}
}
</code></pre>
<p><br>
My Adapter : </p>
<pre><code>public class NumbersAdapter extends ArrayAdapter<Numbers> {
public NumbersAdapter(Context context, ArrayList<Numbers> englishNumbers) {
super(context, 0, englishNumbers);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.listitem, parent, false);
}
Numbers numbers = getItem(position);
System.out.println(position);
TextView tamazight_item = (TextView) listItemView.findViewById(R.id.tamazight_item);
TextView english_item = (TextView) listItemView.findViewById(R.id.english_item);
tamazight_item.setText(numbers.getEnglishTranslation());
System.out.println(numbers.getEnglishTranslation());
english_item.setText(numbers.getTamazightTranslation());
System.out.println(numbers.getTamazightTranslation());
return listItemView;
}
}
</code></pre>
| 3 | 1,447 |
Initialize FileInputStream in JMH @Setup and use in @Benchmark
|
<p><code>InputStream</code> initiliazed in <code>@Setup</code>, when trying to use it in <code>@Benchmark</code> its closed. Changing <code>@State</code> doesn't work. Am I doing this correctly? Is there are way to avoid stream initialization overhead and do proper benchmark?</p>
<p>This doesn't work for <code>XMLStreamReader</code> also, I am doing a serialization deserialization benchmark where I want to avoid file read/stream initialization cost into benchmark score.</p>
<p>sample benchmark</p>
<pre><code>@State( Scope.Thread )
public class DeserializationBenchMark
{
@Param( { "1.xml", "10.xml", "100.xml" } )
String file;
private InputStream xmlFileInputStream;
@Setup
public void setup() throws JAXBException, IOException, SAXException, XMLStreamException
{
File xmlFile = new File( "src/main/resources/" + file );
xmlFileInputStream = Files.newInputStream( xmlFile.toPath() );
}
@Benchmark
public void jacksonDeserializeStreamTest( Blackhole bh ) throws IOException
{
bh.consume( objectMapper.readValue( xmlFileInputStream, Cat.class ) );
}
}
</code></pre>
<p>runner</p>
<pre><code>public class BenchMarkRunner
{
public static void main( String[] args ) throws RunnerException
{
Options opt = new OptionsBuilder()
.include( DeserializationBenchMark.class.getSimpleName() )
.forks( 1 )
.resultFormat( ResultFormatType.JSON )
.result( "deserialize-benchmark-report-" + LocalDateTime.now().format( DateTimeFormatter.ofPattern( "ddMMyyyy'T'hhmmss" ) ) + ".json" )
.mode( Mode.AverageTime )
.warmupIterations( 3 )
.measurementIterations( 5 )
.timeUnit( TimeUnit.MICROSECONDS )
.build();
new Runner( opt ).run();
}
}
</code></pre>
<p>This gives</p>
<pre><code>com.fasterxml.jackson.core.JsonParseException: N/A
at com.fasterxml.jackson.dataformat.xml.util.StaxUtil.throwAsParseException(StaxUtil.java:37)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:534)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:29)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:820)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3058)
at com.example.DeserializationBenchMark.jacksonDeserializeStreamTest(DeserializationBenchMark.java:118)
at com.example.generated.DeserializationBenchMark_jacksonDeserializeStreamTest_jmhTest.jacksonDeserializeStreamTest_avgt_jmhStub(DeserializationBenchMark_jacksonDeserializeStreamTest_jmhTest.java:186)
at com.example.generated.DeserializationBenchMark_jacksonDeserializeStreamTest_jmhTest.jacksonDeserializeStreamTest_AverageTime(DeserializationBenchMark_jacksonDeserializeStreamTest_jmhTest.java:150)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.openjdk.jmh.runner.BenchmarkHandler$BenchmarkTask.call(BenchmarkHandler.java:453)
at org.openjdk.jmh.runner.BenchmarkHandler$BenchmarkTask.call(BenchmarkHandler.java:437)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.nio.channels.ClosedChannelException
at sun.nio.ch.FileChannelImpl.ensureOpen(FileChannelImpl.java:110)
at sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:147)
at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:65)
at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:109)
at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:103)
at com.ctc.wstx.io.StreamBootstrapper.ensureLoaded(StreamBootstrapper.java:482)
at com.ctc.wstx.io.StreamBootstrapper.resolveStreamEncoding(StreamBootstrapper.java:306)
at com.ctc.wstx.io.StreamBootstrapper.bootstrapInput(StreamBootstrapper.java:167)
at com.ctc.wstx.stax.WstxInputFactory.doCreateSR(WstxInputFactory.java:573)
at com.ctc.wstx.stax.WstxInputFactory.createSR(WstxInputFactory.java:633)
at com.ctc.wstx.stax.WstxInputFactory.createSR(WstxInputFactory.java:647)
at com.ctc.wstx.stax.WstxInputFactory.createXMLStreamReader(WstxInputFactory.java:334)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:532)
... 18 more
</code></pre>
<p>Any suggestion would be great! Thank you.</p>
<p>PS:</p>
<p>As @dit mentioned It should be stream close, any idea why it happens at first iteration, </p>
<pre><code># Run progress: 0.00% complete, ETA 00:07:30
# Fork: 1 of 1
# Warmup Iteration 1: <failure>
com.fasterxml.jackson.core.JsonParseException: N/A
at com.fasterxml.jackson.dataformat.xml.util.StaxUtil.throwAsParseException(StaxUtil.java:37)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:534)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:29)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:820)
</code></pre>
| 3 | 2,302 |
Property not found in cellForRowAtIndexPath: method
|
<p>I am getting an error which I don't understand because I have declared the property/ies. Have commented out the error in the AllListViewController.m file in the cellForRowAtIndexPath: method.</p>
<p>Here are the files:</p>
<p>Checklist.h</p>
<pre><code>#import <Foundation/Foundation.h>
@interface Checklist : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, copy) NSString *iconName;
-(int)countUncheckedItems;
@end
</code></pre>
<p>Checklist.m</p>
<pre><code>#import "Checklist.h"
#import "ChecklistItem.h"
@implementation Checklist
-(id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super init])) {
self.name = [aDecoder decodeObjectForKey:@"Name"];
self.items = [aDecoder decodeObjectForKey:@"Items"];
self.iconName = [aDecoder decodeObjectForKey:@"IconName"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"Name"];
[aCoder encodeObject:self.items forKey:@"Items"];
[aCoder encodeObject:self.iconName forKey:@"IconName"];
}
-(id)init
{
if ((self = [super init])) {
self.items = [[NSMutableArray alloc] initWithCapacity:20];
self.iconName = @"Appointments";
}
return self;
}
-(int)countUncheckedItems
{
int count = 0;
for (ChecklistItem *item in self.items) {
if (!item.checked) {
count += 1;
}
}
return count;
}
-(NSComparisonResult)compare:(Checklist *)otherChecklist
{
return [self.name localizedStandardCompare:otherChecklist.name];
}
@end
</code></pre>
<p>AllListsViewController.h</p>
<pre><code>#import <UIKit/UIKit.h>
#import "ListDetailViewController.h"
@class DataModel;
@interface AllListsViewController : UITableViewController <ListDetailViewControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) DataModel *dataModel;
@end
</code></pre>
<p>AllListsViewController.m</p>
<pre><code>#import "AllListsViewController.h"
#import "Checklist.h"
#import "ChecklistViewController.h"
#import "ChecklistItem.h"
#import "DataModel.h"
@interface AllListsViewController ()
@end
@implementation AllListsViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.dataModel setIndexOfSelectedChecklist:indexPath.row];
Checklist *checklist = self.dataModel.lists[indexPath.row];
[self performSegueWithIdentifier:@"ShowChecklist" sender:checklist];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"ShowChecklist"]) {
ChecklistViewController *controller = segue.destinationViewController;
controller.checklist = sender;
}
else if ([segue.identifier isEqualToString:@"AddChecklist"]) {
UINavigationController *navigationController = segue.destinationViewController;
ListDetailViewController *controller = (ListDetailViewController *)navigationController.topViewController;
controller.delegate = self;
controller.checklistToEdit = nil;
}
}
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
UINavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"ListNavigationController"];
ListDetailViewController *controller = (ListDetailViewController *)navigationController.topViewController;
controller.delegate = self;
Checklist *checklist = self.dataModel.lists[indexPath.row];
controller.checklistToEdit = checklist;
[self presentViewController:navigationController animated:YES completion:nil];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.dataModel.lists count];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.dataModel.lists removeObjectAtIndex:indexPath.row];
NSArray *indexPaths = @[indexPath];
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
cell.imageView.image = [UIImage imageNamed:Checklist.iconName]; /* Use of undeclared identifier; did you mean 'Checklist'? or Property 'iconName' not found on object of type 'Checklist'*/
return cell;
}
Checklist *checklist = self.dataModel.lists[indexPath.row];
cell.textLabel.text = checklist.name;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d Remaining", [checklist countUncheckedItems]];
int count = [checklist countUncheckedItems];
if ([checklist.items count] == 0) {
cell.detailTextLabel.text = @"(No Items)";
} else if (count == 0) {
cell.detailTextLabel.text = @"All Done";
} else {
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d Remaining", count];
}
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
/*
#pragma mark - Navigation
// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
-(void)listDetailViewControllerDidCancel:(ListDetailViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)listDetailViewController:(ListDetailViewController *)controller didFinishAddingChecklist:(Checklist *)checklist
{
[self.dataModel.lists addObject:checklist];
[self.dataModel sortChecklists];
[self.tableView reloadData];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)listDetailViewController:(ListDetailViewController *)controller didFinishEditingChecklist:(Checklist *)checklist
{
[self.dataModel sortChecklists];
[self.tableView reloadData];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if(viewController == self) {
[self.dataModel setIndexOfSelectedChecklist:-1];
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.navigationController.delegate = self;
NSInteger index = [self.dataModel indexOfSelectedChecklist];
if(index >= 0 && index < [self.dataModel.lists count]) {
Checklist *checklist = self.dataModel.lists[index];
[self performSegueWithIdentifier:@"ShowChecklist" sender:checklist];
}
}
@end
</code></pre>
| 3 | 3,268 |
How to fix 401 error when the credentials work on one end but not the other
|
<p>When I try to log in the angular portion of my app I get a 401 error but the credentials work in the spring portion. No matter what I try I can't seem to fix it. I was following this <a href="https://www.youtube.com/watch?v=QV7ke4a7Lvc&t=11s" rel="nofollow noreferrer">tutorial</a></p>
<p>Header</p>
<pre><code>Request URL: http://localhost:8080/
Request Method: GET
Status Code: 401
Remote Address: [::1]:8080
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Headers: access_token, authorization, content-type
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS, DELETE
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 4200
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Sat, 18 Sep 2021 16:40:45 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
WWW-Authenticate: Basic realm="Realm"
WWW-Authenticate: Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
</code></pre>
<p>Spring Security config This portion works well enough to allow me to sign into the spring server.</p>
<pre><code> @Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CorsConfiguration myCorsFilter;
@Override
public void configure(WebSecurity web) throws Exception
{
// Allow Login API to be accessed without authentication
web.ignoring().antMatchers("/login").antMatchers(HttpMethod.OPTIONS, "/**"); // Request type options should be allowed.
}
//CORS
@Override
protected void configure(HttpSecurity http) throws Exception {
/* http.cors().and().csrf().
disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.anyRequest()
.fullyAuthenticated()
.and()
.httpBasic();*/
http.addFilterBefore(myCorsFilter, ChannelProcessingFilter.class);
http.cors();
http.csrf().disable();
http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and()
.httpBasic();
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication()
.withUser("dave")
.password("{noop}dave").roles("USER");
}
}
</code></pre>
<p>CorsFilter</p>
<pre><code>@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsConfiguration implements Filter {
/**
* CORS filter for http-request and response
*/
public void CORSFilter() {
}
/**
* Do Filter on every http-request.
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "4200");
response.setHeader("Access-Control-Allow-Headers", "access_token, authorization, content-type");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
/**
* Destroy method
*/
@Override
public void destroy() {
}
/**
* Initialize CORS filter
*/
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
</code></pre>
| 3 | 1,618 |
converting text file to comma delimited csv file or json file
|
<p>I have a text file that I want to convert to a comma-delimited CSV file, where the first row(headers) are the MySQL table fields. My text file looks like this</p>
<pre><code> id purchase-date last-updated-date status, name
305-0847312-2761164 2022-04-11T22:23:27+00:00 2022-04-11T22:23:31+00:00 Pending DE DE Core Free Shipping
028-3270261-2897162 2022-04-11T22:17:27+00:00 2022-04-11T22:17:30+00:00 Pending
028-8245400-1649940 2022-04-11T22:15:29+00:00 2022-04-11T22:15:32+00:00 Pending
028-2661715-2120359 2022-04-11T21:57:24+00:00 2022-04-11T21:57:28+00:00 Pending
303-9076983-4225163 2022-04-11T21:53:52+00:00 2022-04-11T21:53:55+00:00 Pending
304-7440363-0208337 2022-04-11T21:49:14+00:00 2022-04-11T21:49:17+00:00 Pending
302-2070657-8345128 2022-04-11T21:30:12+00:00 2022-04-12T01:32:20+00:00 Shipped some names
</code></pre>
<p>What I want to achieve is a file like this</p>
<pre><code> id, purchase-date, last-updated-date, status
305-0847312-2761164, 2022-04-11T22:23:27+00:00, 2022-04-11T22:23:31+00:00, Pending
028-3270261-2897162, 2022-04-11T22:17:27+00:00, 2022-04-11T22:17:30+00:00, Pending
</code></pre>
<p>I need this file to save in the database where the first row are the column names</p>
<p>I tried pandas</p>
<pre><code> read_file = pd.read_csv("reports/report.txt")
read_file.to_csv("reports/report.csv", index=None, sep="\n")
exit()
</code></pre>
<p>BUt I got error</p>
<pre><code> pandas.errors.ParserError: Error tokenizing data. C error: Expected 2 fields in line 194, saw 4
</code></pre>
<p>Questions</p>
<ol>
<li><p>How do you convert this text file to a comma delimited csv file?</p>
</li>
<li><p>Or a more preferable way, to convert this txt file to json file, saving this to db is much easier if its in json format, something like:</p>
<pre><code>[
{
id: 305-0847312-2761164,
purchase_date: 2022-04-11T22:23:27+00:00
},
{
id: 305-0847312-2761165,
purchase_date: 2022-05-11T22:23:27+00:00,
name: null( some names is empty)
},
{
id: 305-0847312-2761165,
purchase_date: 2022-05-11T22:23:27+00:00,
name: 'some name'
},
.......................
]
with open(file) as f:
for i in f:
myTable.objects.create(id=id,**i)
</code></pre>
</li>
</ol>
<p>I tried to convert to json format and I think its pretty close</p>
<pre><code>text = "reports/download/sellingpartner/report.txt"
l = 1
dict1 = []
with open(text) as fh:
first_line = fh.readline()
fields = [e.replace("-", "_") for e in first_line.split()]
l = 1
lines = fh.readlines()[1:]
for line in lines:
description = line
print(description)
i = 0
dict2 = {}
while i < len(fields):
dict2[fields[i]] = description[i]
i = i + 1
dict1.append(dict2)
l = l + 1
output = open("reports/download/sellingpartner/file.json", "w")
json.dump(dict1, output, indent=4)
output.close()
</code></pre>
<p>result</p>
<pre><code>[
{
"amazon_order_id": "3",
"merchant_order_id": "0",
"purchase_date": "4",
"last_updated_date": "-",
"order_status": "8",
"fulfillment_channel": "5",
"sales_channel": "9",
"order_channel": "2",
"ship_service_level": "7",
"product_name": "7",
"sku": "5",
"asin": "-",
"item_status": "1",
"quantity": "5",
"currency": "3",
"item_price": "1",
"item_tax": "5",
"shipping_price": "3",
"shipping_tax": "1",
"gift_wrap_price": "\t",
"gift_wrap_tax": "3",
"item_promotion_discount": "0",
"ship_promotion_discount": "4",
"ship_city": "-",
"ship_state": "8",
"ship_postal_code": "5",
"ship_country": "9",
"promotion_ids": "2",
"is_business_order": "7",
"purchase_order_number": "7",
"price_designation": "5",
"is_iba": "-",
"order_invoice_type": "1"
},
{
"amazon_order_id": "3",
"merchant_order_id": "0",
"purchase_date": "5",
"last_updated_date": "-",
"order_status": "5",
"fulfillment_channel": "4",
"sales_channel": "1",
"order_channel": "2",
"ship_service_level": "3",
"product_name": "9",
"sku": "1",
"asin": "-",
"item_status": "1",
"quantity": "7",
"currency": "2",
"item_price": "2",
"item_tax": "7",
"shipping_price": "1",
"shipping_tax": "2",
"gift_wrap_price": "\t",
"gift_wrap_tax": "3",
"item_promotion_discount": "0",
"ship_promotion_discount": "5",
"ship_city": "-",
"ship_state": "5",
"ship_postal_code": "4",
"ship_country": "1",
"promotion_ids": "2",
"is_business_order": "3",
"purchase_order_number": "9",
"price_designation": "1",
"is_iba": "-",
"order_invoice_type": "1"
},
{
"amazon_order_id": "3",
"merchant_order_id": "0",
"purchase_date": "5",
"last_updated_date": "-",
"order_status": "6",
"fulfillment_channel": "5",
"sales_channel": "4",
"order_channel": "7",
"ship_service_level": "1",
"product_name": "4",
"sku": "7",
"asin": "-",
"item_status": "8",
"quantity": "7",
"currency": "4",
"item_price": "8",
"item_tax": "3",
"shipping_price": "6",
"shipping_tax": "3",
"gift_wrap_price": "\t",
"gift_wrap_tax": "3",
"item_promotion_discount": "0",
"ship_promotion_discount": "5",
"ship_city": "-",
"ship_state": "6",
"ship_postal_code": "5",
"ship_country": "4",
"promotion_ids": "7",
"is_business_order": "1",
"purchase_order_number": "4",
"price_designation": "7",
"is_iba": "-",
"order_invoice_type": "8"
},
{
"amazon_order_id": "3",
"merchant_order_id": "0",
"purchase_date": "5",
"last_updated_date": "-",
"order_status": "1",
"fulfillment_channel": "9",
"sales_channel": "4",
"order_channel": "5",
"ship_service_level": "9",
"product_name": "1",
"sku": "5",
"asin": "-",
"item_status": "3",
"quantity": "8",
"currency": "1",
"item_price": "5",
"item_tax": "5",
"shipping_price": "2",
"shipping_tax": "4",
"gift_wrap_price": "\t",
"gift_wrap_tax": "3",
"item_promotion_discount": "0",
"ship_promotion_discount": "5",
"ship_city": "-",
"ship_state": "1",
"ship_postal_code": "9",
"ship_country": "4",
"promotion_ids": "5",
"is_business_order": "9",
"purchase_order_number": "1",
"price_designation": "5",
"is_iba": "-",
"order_invoice_type": "3"
},
</code></pre>
<p>One thing I need to solve is how to separate the <code>line</code> by commas, because each values contains spaces, and commas too.Values are separated by multiple spaces, see below</p>
<pre><code> 406-4733989-6345153 406-4733989-6345153 2022-04-12T05:37:01+00:00 2022-04-12T05:37:05+00:00 Pending Amazon Amazon.it Expedited Impact Fixy - Supporto per cellulare a 360° per bicicletta e moto, estremamente stabile, con giunto sferico a 360° e gomma di sicurezza, supporto pe 4Z-LVBE-IGD9 B08MXYS4S3 Unshipped 1 EUR 16.95 milano mi 20161 IT PAWS-V2-27105377117-91 false false
</code></pre>
<p>I converted the .tx extension to csv file and opened it with libre office, see screenshot<a href="https://i.stack.imgur.com/l0zqb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l0zqb.png" alt="enter image description here" /></a></p>
<p>I tried another approach,</p>
<pre><code>jsonArray = []
output = "reports/download/sellingpartner/file.json"
text = "reports/download/sellingpartner/report.txt"
# read csv file
with open(text, encoding="utf-8") as csvf:
# load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
# convert each csv row into python dict
for row in csvReader:
# add this python dict to json array
jsonArray.append(row)
# convert python jsonArray to JSON String and write to file
with open(output, "w", encoding="utf-8") as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
</code></pre>
<p>Here's the result:</p>
<pre><code> [
{
"amazon-order-id\tmerchant-order-id\tpurchase-date\tlast-updated-date\torder-status\tfulfillment-channel\tsales-channel\torder-channel\tship-service-level\tproduct-name\tsku\tasin\titem-status\tquantity\tcurrency\titem-price\titem-tax\tshipping-price\tshipping-tax\tgift-wrap-price\tgift-wrap-tax\titem-promotion-discount\tship-promotion-discount\tship-city\tship-state\tship-postal-code\tship-country\tpromotion-ids\tis-business-order\tpurchase-order-number\tprice-designation\tis-iba\torder-invoice-type": "304-3907519-7764337\t304-3907519-7764337\t2022-04-12T17:10:44+00:00\t2022-04-12T17:10:47+00:00\tPending\tAmazon\tAmazon.de\t\tExpedited\tImpact Ketten\u00c3\u00b6l Fahrrad 120ml - Einzigartiges 8 Komponenten Fahrradketten \u00c3\u0096l als Alternative zu Kettenfett & Kettenspray f\u00c3\u00bcr E-Bike",
"null": [
" Mountainbike\tL9-3CSN-J1GL\tB08DVJ95DS\tUnshipped\t1\tEUR\t9.95\t\t\t\t\t\t\t\tLichtenfels\t\t96215\tDE\t\tfalse\t\t\tfalse\t"
]
},
{
........................
}
]
</code></pre>
| 3 | 6,428 |
Janus VideoRoom plugin subscribe operation took too much seconds before i saw remote video
|
<p><br/>Im using Janus VideoRoom plugin and i want to subscribe/unsubscribe 2 or more different publishers.
<br/>First 4 or 5 subscriptions (start subscribe -> got video visible) take 2-3 seconds.
<br/>I call it <strong>NORMAL</strong>.
<br/>But next subscriptions take MUCH more time.
<br/>I call it <strong>UNNORMAL</strong>.
<br/>Please tell me where is my mistake ?</p>
<p>Here is my JS (TypeScript)</p>
<pre><code>declare var Janus: any;
export class SubscriberClientSimple {
private login:string;
private opaqueId:string;
private videoPlayer:any;
private streamName:string;
private serverUri:string;
private serverURL:string;
private api:any;
private plugin:any;
private remoteStream:any;
public static STARTING:string = "STARTING";
public static STARTED:string = "STARTED";
public static STOPPING:string = "STOPPING";
public static STOPPED:string = "STOPPED";
private state:string;
constructor(login:string){
this.login = login;
this.opaqueId = "subscriber-" + this.login + "-" + Janus.randomString(12);
}
public destroy():void{
}
public setPlayerElement(element:any):void{
this.videoPlayer = element;
}
public hasVideoPlayerElement():boolean{
return this.videoPlayer!=null;
}
public isAudioEnabled():boolean{
return false;
}
public isVideoEnabled():boolean{
return true;
}
public getStreamName():string{
return this.streamName;
}
public subscribe(streamName: string, serverUri: string, audio:boolean, video:boolean):void{
this.log("Start requested");
this.state = SubscriberClientSimple.STARTING;
this.streamName = streamName;
this.serverUri = serverUri;
this.serverURL = MEDIA_SERVER_URL + MEDIA_SERVER_PATH + "/janus-debug";
EventBus.dispatchEvent(StreamingEvent.REMOTE_VIDEO_RECEIVE_INTENT, null);
//this.log("server url : "+this.serverURL);
Janus.init({
userId: parseInt(this.login),
backendUrl: this.serverURL,
environment: environment,
debug: false, // fixme это вынужденно отключено, чтобы можно было использовать Janus.noop как коллбэк для логирования
callback: () => this.initCallback()
});
}
public unsubscribe():void{
this.log("unsubscribe state="+this.state);
if(this.state == SubscriberClientSimple.STARTED){
this.state = SubscriberClientSimple.STOPPING;
EventBus.dispatchEvent(StreamingEvent.SUBSCRIBER_BUSY, null);
if(this.plugin){
this.log("sending leave command...");
this.plugin.send({message: {request: "leave"}});
}
}
}
public disableAudio():void{
this.log("Disable AUDIO");
}
public disableVideo():void{
this.log("Disable VIDEO");
}
public enableAudio():void{
}
public enableVideo():void{
}
public reset():void{
}
public setSocketService(socketService:any):void{
}
public setModalService(modalService):void{
}
public isMyCurrentPublisher(id:string):boolean{
return this.streamName == id;
}
public getSubscribeState():any{
var data:any = {userId:this.login, audio: {state:""}, video:{state:"OFF"}};
data.audio.state = "OFF";
if(this.state == SubscriberClientSimple.STARTED){
data.video.state = "ON";
}
return data;
}
public isSubscribing():boolean{
return this.state == SubscriberClientSimple.STARTED;
}
private initCallback():void{
this.log("initCallback");
if (!Janus.isWebrtcSupported()) {
this.onWebRTCNotSupported();
}
this.createSession();
}
private createSession():void {
// Create session
this.log("createSession");
this.api = new Janus({
server: this.serverUri,
iceServers: ICE_SERVERS,
success: () => this.onStreamingServerCreateSuccess(),
error: (err) => this.onStreamingServerCreateError(err),
destroyed: () => this.onStreamingServerDestroyed()
});
}
private onStreamingServerCreateSuccess():void{
this.log("onStreamingServerCreateSuccess");
this.attachPlugin();
}
private attachPlugin():void{
this.log("attachPlugin");
let remoteFeed = null;
this.api.attach(
{
plugin: "janus.plugin.videoroom",
opaqueId: this.opaqueId,
success: (pluginHandle) => {
this.log("plugin attached");
remoteFeed = pluginHandle;
remoteFeed.simulcastStarted = false;
// We wait for the plugin to send us an offer
remoteFeed.send({
"message": {
"request": "listparticipants",
"room": +this.streamName
},
success: (res) => {
this.log("Total participants="+res.participants.length);
var canJoin:boolean = res.participants && res.participants.length > 0;
this.log("canJoin="+canJoin);
if (canJoin) {
var publisherParticipant:any = res.participants[0];
var publisherId:string = publisherParticipant.id;
const subscriptionData:any = {
"request": "join",
"room": +this.streamName,
"ptype": "subscriber",
"feed": publisherId,
"private_id": parseInt(this.login)
};
this.log("subscriptionData="+JSON.stringify(subscriptionData));
remoteFeed.send({"message": subscriptionData});
}
else {
this.log("Requested stream is not available anymore.");
}
}
});
},
error: (error) => {
const message = "Error attaching subscribe plugin. " + error.toString();
this.log(message);
},
onmessage: (msg, jsep) => {
this.onPluginMessage(msg, jsep, remoteFeed);
},
webrtcState: (on, reason) => {
if (reason === "Close PC") {
var message:string = "Closed PeerConnection";
this.log(message);
}
},
iceState: (state) => {
this.onICEState(state);
},
onlocalstream: function (stream) {
// The subscriber stream is recvonly, we don't expect anything here
},
onremotestream: (stream) => {
this.onSubscriberGotRemoteStream(stream);
},
oncleanup: () => {
this.onCleanUp();
}
});
}
private onPluginMessage(msg, jsep, remoteFeed):void{
this.log("onPluginMessage");
this.log("msg:"+JSON.stringify(msg));
this.log("jsep:"+JSON.stringify(jsep));
this.log("remoteFeed:"+remoteFeed);
const event = msg["videoroom"];
if (msg["error"]){
if (msg["error"] !== "No such room") {
this.log("Janus ERROR:"+msg["error"]);
}
}
else if (event) {
if (event === "attached") {
// Subscriber created and attached
this.log("Subscriber created and attached");
if (this.plugin === undefined || this.plugin === null) {
this.plugin = remoteFeed;
}
remoteFeed.rfid = msg["id"];
remoteFeed.rfdisplay = msg["display"];
}
else if(event === "event"){
var leftRoomResult:any = msg["left"];
if(leftRoomResult){
if(leftRoomResult == "ok"){
var roomId:string = msg["room"].toString();
this.onLeftRoom(roomId);
}
}
}
else if (event === "slow_link") {
}
}
if (jsep) {
// Answer and attach
this.log("create answer");
remoteFeed.createAnswer(
{
jsep: jsep,
media: {audioSend: false, videoSend: false}, // We want recvonly audio/video
success: (_jsep) => {
this.log("Got SDP!", _jsep);
const body = {"request": "start", "room": this.streamName};
remoteFeed.send({"message": body, "jsep": _jsep});
},
error: (err) => {
this.log("WebRTC error:", err);
}
});
}
}
private onSubscriberGotRemoteStream(stream:any):void{
this.log("onSubscriberGotRemoteStream this.state="+this.state);
if(this.state == SubscriberClientSimple.STARTING){
const videoTracks = stream.getVideoTracks();
this.remoteStream = stream;
this.attachRemoteStream();
this.startRemoteVideo();
this.state = SubscriberClientSimple.STARTED;
}
}
private onLeftRoom(roomId:string):void{
if(roomId == this.streamName){
this.log("Left room");
this.plugin.ondetached();
this.plugin.detach();
this.plugin = null;
this.log("VIDEO stopped");
this.state = SubscriberClientSimple.STOPPED;
EventBus.dispatchEvent(StreamingEvent.REMOTE_VIDEO_DISABLED, null);
}
}
private onCleanUp():void{
this.log("onCleanUp");
}
private onICEState(state:string):void{
this.log("ICE state of this WebRTC PeerConnection changed to " + state);
}
private attachRemoteStream():void {
Janus.attachMediaStream(this.videoPlayer, this.remoteStream );
this.videoPlayer.muted = "muted";
}
private startRemoteVideo():void {
this.videoPlayer.play();
this.log("VIDEO started");
EventBus.dispatchEvent(StreamingEvent.REMOTE_VIDEO_RECEIVING_STARTED, null);
}
private onStreamingServerCreateError(err:any):void{
this.log("Streaming Server Error:",err);
}
private onStreamingServerDestroyed():void{
this.log("Janus destroyed");
}
private onWebRTCNotSupported():void{
this.log("WebRTC Not Supported");
}
protected log(value:any, ...rest:any[]):void{
EventBus.dispatchEvent(AppEvent.SEND_LOG, {className:this.getClassName(), value:value, rest:rest});
}
protected getClassName():string{
return "SubscriberClientSimple";
}
}
</code></pre>
<p><br/>Here is my log after 4 or 5 <strong>NORMAL</strong> subscription launches
<br/>// Watching publisher's video
<br/>// stop prev subscription
<br/>04:01:50 unsubscribe state=STARTED
<br/>04:01:50 sending leave command...
<br/>04:01:50 unsubscribe state=STOPPING
<br/>04:01:50 unsubscribe state=STOPPING
<br/>04:01:50 onPluginMessage
<br/>04:01:50 msg:{"videoroom":"event","room":681365,"left":"ok"}
<br/>04:01:50 jsep:undefined
<br/>04:01:50 remoteFeed:[object Object]
<br/>04:01:50 Left room
<br/>04:01:50 onCleanUp
<br/>04:01:50 VIDEO stopped
<br/>04:01:50 Closed PeerConnection
<br/>04:01:50 onCleanUp
<br/>// new subscription <strong>NORMAL</strong> start
<br/>04:01:53 Start requested
<br/>04:01:53 initCallback
<br/>04:01:53 createSession
<br/>04:01:54 onStreamingServerCreateSuccess
<br/>04:01:54 attachPlugin
<br/>04:01:54 plugin attached
<br/>04:01:54 Total participants=1
<br/>04:01:54 canJoin=true
<br/>04:01:54 subscriptionData={"request":"join","room":724240,"ptype":"subscriber","feed":3606687285964170,"private_id":680291}
<br/>04:01:54 onPluginMessage
<br/>04:01:54 msg:{"videoroom":"attached","room":724240,"id":3606687285964170,"display":"724240"}
<br/>04:01:54 jsep:{"type":"offer","sdp":"v=0\r\no=- 1615780141548001 1 IN IP4 185.12.12.24\r\ns=VideoRoom 724240\r\nt=0 0\r\na=group:BUNDLE audio video\r\na=msid-semantic: WMS janus\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 185.12.12.24\r\na=sendonly\r\na=mid:audio\r\na=rtcp-mux\r\na=ice-ufrag:NVx5\r\na=ice-pwd:Tz3hjJNIxACUULUbBBREaL\r\na=ice-options:trickle\r\na=fingerprint:sha-256 53:C2:82:E2:61:73:BC:B5:0D:66:E8:2E:11:90:97:66:92:52:62:FE:2C:6B:45:95:A1:EF:08:D6:05:C6:8E:A1\r\na=setup:actpass\r\na=rtpmap:111 opus/48000/2\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=extmap:2 urn:ietf:params:rtp-hdrext:sdes:mid\r\na=rtcp-fb:111 transport-cc\r\na=msid:janus janusa0\r\na=ssrc:3479227141 cname:janus\r\na=ssrc:3479227141 msid:janus janusa0\r\na=ssrc:3479227141 mslabel:janus\r\na=ssrc:3479227141 label:janusa0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96 97\r\nc=IN IP4 185.12.12.24\r\na=sendonly\r\na=mid:video\r\na=rtcp-mux\r\na=ice-ufrag:NVx5\r\na=ice-pwd:Tz3hjJNIxACUULUbBBREaL\r\na=ice-options:trickle\r\na=fingerprint:sha-256 53:C2:82:E2:61:73:BC:B5:0D:66:E8:2E:11:90:97:66:92:52:62:FE:2C:6B:45:95:A1:EF:08:D6:05:C6:8E:A1\r\na=setup:actpass\r\na=rtpmap:96 VP8/90000\r\na=rtcp-fb:96 ccm fir\r\na=rtcp-fb:96 nack\r\na=rtcp-fb:96 nack pli\r\na=rtcp-fb:96 goog-remb\r\na=extmap:2 urn:ietf:params:rtp-hdrext:sdes:mid\r\na=extmap:3 <a href="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01%5Cr%5Cna=extmap:12" rel="nofollow noreferrer">http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=extmap:12</a> <a href="http://www.webrtc.org/experiments/rtp-hdrext/playout-delay%5Cr%5Cna=extmap:13" rel="nofollow noreferrer">http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\r\na=extmap:13</a> urn:3gpp:video-orientation\r\na=rtpmap:97 rtx/90000\r\na=fmtp:97 apt=96\r\na=ssrc-group:FID 462666388 1246572010\r\na=msid:janus janusv0\r\na=ssrc:462666388 cname:janus\r\na=ssrc:462666388 msid:janus janusv0\r\na=ssrc:462666388 mslabel:janus\r\na=ssrc:462666388 label:janusv0\r\na=ssrc:1246572010 cname:janus\r\na=ssrc:1246572010 msid:janus janusv0\r\na=ssrc:1246572010 mslabel:janus\r\na=ssrc:1246572010 label:janusv0\r\n"}
<br/>04:01:54 remoteFeed:[object Object]
<br/>04:01:54 Subscriber created and attached
<br/>04:01:54 create answer
<br/>04:01:54 onSubscriberGotRemoteStream this.state=STARTING
<br/>04:01:54 VIDEO started
<br/>04:01:54 onSubscriberGotRemoteStream this.state=STARTED
<br/>04:01:54 onSubscriberGotRemoteStream this.state=STARTED
<br/>04:01:54 Got SDP! [RTCSessionDescription]
<br/>04:01:54 ICE state of this WebRTC PeerConnection changed to checking
<br/>04:01:54 ICE state of this WebRTC PeerConnection changed to connected
<br/>04:01:55 onPluginMessage
<br/>04:01:55 msg:{"videoroom":"event","room":724240,"started":"ok"}
<br/>04:01:55 jsep:undefined
<br/>04:01:55 remoteFeed:[object Object]
<br/>
<br/>// <strong>NORMAL</strong> start subscribing took 2 seconds
<br/>// Watching publisher's video
<br/>// Stop prev subscription
<br/>
<br/>04:09:55 unsubscribe state=STARTED
<br/>04:09:55 sending leave command...
<br/>04:09:55 unsubscribe state=STOPPING
<br/>04:09:55 unsubscribe state=STOPPING
<br/>04:09:55 onPluginMessage
<br/>04:09:55 msg:{"videoroom":"event","room":681365,"left":"ok"}
<br/>04:09:55 jsep:undefined
<br/>04:09:55 remoteFeed:[object Object]
<br/>04:09:55 Left room
<br/>04:09:55 onCleanUp
<br/>04:09:55 VIDEO stopped
<br/>04:09:56 Closed PeerConnection
<br/>04:09:56 onCleanUp
<br/>
<br/>// new subscription <strong>UNNORMAL</strong> start
<br/>
<br/>04:09:58 Start requested
<br/>04:09:58 initCallback
<br/>04:09:58 createSession
<br/>04:09:58 onStreamingServerCreateSuccess
<br/>04:09:58 attachPlugin
<br/>// <strong>huge pause !!!</strong>
<br/>04:10:17 plugin attached
<br/>// <strong>huge pause !!!</strong>
<br/>04:10:22 Total participants=1
<br/>04:10:22 canJoin=true
<br/>04:10:22 subscriptionData={"request":"join","room":724240,"ptype":"subscriber","feed":3606687285964170,"private_id":680291}
<br/>04:10:28 onPluginMessage
<br/>04:10:28 msg:{"videoroom":"attached","room":724240,"id":3606687285964170,"display":"724240"}
<br/>04:10:28 jsep:{"type":"offer","sdp":"v=0\r\no=- 1615780141548001 1 IN IP4 185.12.12.24\r\ns=VideoRoom 724240\r\nt=0 0\r\na=group:BUNDLE audio video\r\na=msid-semantic: WMS janus\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 185.12.12.24\r\na=sendonly\r\na=mid:audio\r\na=rtcp-mux\r\na=ice-ufrag:WETD\r\na=ice-pwd:ch2L786bEYlY6OIi+AJ4no\r\na=ice-options:trickle\r\na=fingerprint:sha-256 53:C2:82:E2:61:73:BC:B5:0D:66:E8:2E:11:90:97:66:92:52:62:FE:2C:6B:45:95:A1:EF:08:D6:05:C6:8E:A1\r\na=setup:actpass\r\na=rtpmap:111 opus/48000/2\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=extmap:2 urn:ietf:params:rtp-hdrext:sdes:mid\r\na=rtcp-fb:111 transport-cc\r\na=msid:janus janusa0\r\na=ssrc:1576733354 cname:janus\r\na=ssrc:1576733354 msid:janus janusa0\r\na=ssrc:1576733354 mslabel:janus\r\na=ssrc:1576733354 label:janusa0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96 97\r\nc=IN IP4 185.12.12.24\r\na=sendonly\r\na=mid:video\r\na=rtcp-mux\r\na=ice-ufrag:WETD\r\na=ice-pwd:ch2L786bEYlY6OIi+AJ4no\r\na=ice-options:trickle\r\na=fingerprint:sha-256 53:C2:82:E2:61:73:BC:B5:0D:66:E8:2E:11:90:97:66:92:52:62:FE:2C:6B:45:95:A1:EF:08:D6:05:C6:8E:A1\r\na=setup:actpass\r\na=rtpmap:96 VP8/90000\r\na=rtcp-fb:96 ccm fir\r\na=rtcp-fb:96 nack\r\na=rtcp-fb:96 nack pli\r\na=rtcp-fb:96 goog-remb\r\na=extmap:2 urn:ietf:params:rtp-hdrext:sdes:mid\r\na=extmap:3 <a href="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01%5Cr%5Cna=extmap:12" rel="nofollow noreferrer">http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=extmap:12</a> <a href="http://www.webrtc.org/experiments/rtp-hdrext/playout-delay%5Cr%5Cna=extmap:13" rel="nofollow noreferrer">http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\r\na=extmap:13</a> urn:3gpp:video-orientation\r\na=rtpmap:97 rtx/90000\r\na=fmtp:97 apt=96\r\na=ssrc-group:FID 4137684267 1240900261\r\na=msid:janus janusv0\r\na=ssrc:4137684267 cname:janus\r\na=ssrc:4137684267 msid:janus janusv0\r\na=ssrc:4137684267 mslabel:janus\r\na=ssrc:4137684267 label:janusv0\r\na=ssrc:1240900261 cname:janus\r\na=ssrc:1240900261 msid:janus janusv0\r\na=ssrc:1240900261 mslabel:janus\r\na=ssrc:1240900261 label:janusv0\r\n"}
<br/>04:10:28 remoteFeed:[object Object]
<br/>04:10:28 Subscriber created and attached
<br/>04:10:28 create answer
<br/>04:10:28 onSubscriberGotRemoteStream this.state=STARTING
<br/>04:10:28 VIDEO started
<br/>04:10:28 onSubscriberGotRemoteStream this.state=STARTED
<br/>04:10:28 onSubscriberGotRemoteStream this.state=STARTED
<br/>04:10:28 Got SDP! [RTCSessionDescription]
<br/>04:10:28 ICE state of this WebRTC PeerConnection changed to checking
<br/>04:10:28 ICE state of this WebRTC PeerConnection changed to connected
<br/>04:10:35 onSubscriberGotRemoteStream this.state=STARTED
<br/>04:10:47 onPluginMessage
<br/>04:10:47 msg:{"videoroom":"event","room":724240,"started":"ok"}
<br/>04:10:47 jsep:undefined
<br/>04:10:47 remoteFeed:[object Object]
<br/>
<br/>// <strong>UNNORMAL start subscribing took 49 seconds</strong></p>
| 3 | 10,792 |
Calculator GUI problems
|
<p>I'm in my first semester of programming as a first year college and we were tasked to make a calculator GUI. I'm almost done but I need to make the "Error" appear if the denominator is 0 but it outputs 0.0. My other problem is that I need the gui to restart after showing the final answer but what happens is that after I clicked equals then clicked the number it just continues. So if I press 1+1 then clicked =, it outputs 2 but when I clicked a number for example 1, it just becomes 21.</p>
<p>Also, how do I remove the .0 at the end of every answer? I tried endsWith and replace after every equation but it's not working.</p>
<pre><code> @Override
public void actionPerformed(ActionEvent e){
for(int i=0;i<10;i++) {
if(e.getSource() == numbers[i]) {
text.setText(text.getText().concat(String.valueOf(i)));
}
}
if(e.getSource()==dec) {
if (text.getText().contains(".")) {
return;
} else {
text.setText(text.getText() + ".");
}
}
if(e.getSource()==add) {
num1 = Double.parseDouble(text.getText());
operator ='+';
label.setText(text.getText() + "+");
text.setText("");
}
if(e.getSource()==sub) {
num1 = Double.parseDouble(text.getText());
operator ='-';
label.setText(text.getText() + "-");
text.setText("");
}
if(e.getSource()==mult) {
num1 = Double.parseDouble(text.getText());
operator ='*';
label.setText(text.getText() + "*");
text.setText("");
}
if(e.getSource()==div) {
num1 = Double.parseDouble(text.getText());
operator ='/';
label.setText(text.getText() + "/");
text.setText("");
}
if(e.getSource()==neg) {
Double neg = Double.parseDouble(text.getText());
neg*=-1;
text.setText(String.valueOf(neg));
}
if(e.getSource()==per) {
num1 = Double.parseDouble(text.getText())/100;
label.setText(text.getText() + "%");
text.setText(String.valueOf(num1));
label.setText("");
}
if(e.getSource()==equ) {
num2=Double.parseDouble(text.getText());
switch(operator) {
case'+':
ans=num1+num2;
break;
case'-':
ans=num1-num2;
break;
case'*':
ans=num1*num2;
break;
case'/':
if (num2==0)
text.setText("Error");
else
ans=num1/num2;
break;
}
label.setText("");
text.setText(String.valueOf(ans));
}
}
}
}
</code></pre>
| 3 | 1,383 |
ExpressJS & AJAX - Session Returns Undefined
|
<h2><strong>Structure</strong></h2>
<p>I have an API hosted on a secure server with HTTPS.</p>
<p>as such: <code>https://example.com</code></p>
<p>Also, I have a frontend <code>index.html</code> located on my Desktop.</p>
<hr />
<h2><strong>Goal</strong></h2>
<p>I would like to send an ajax post request to the api and have the api save a value in the session and retrieve it. Like so:</p>
<ol>
<li>Index.html makes POST ajax request to API</li>
<li>API saves a value in session</li>
<li>Index.html makes POST ajax request to API</li>
<li>API prints out the value in session</li>
</ol>
<hr />
<h2>API Code</h2>
<p>First I allowed connections from all origins by using <code>cors()</code>.
And I have set up my <code>session()</code> as so.</p>
<pre><code>app.use(
cors({
origin: true,
optionsSuccessStatus: 200,
credentials: true,
})
);
app.options(
'*',
cors({
origin: true,
optionsSuccessStatus: 200,
credentials: true,
})
);
app.use(session({
secret: "wefwefwe",
cookie: {
sameSite: "none",
secure: false,
maxAge: 360000000
},
saveUninitialized: false
}))
</code></pre>
<p>And then there's these 2 routes which will be called by the <code>index.html</code></p>
<pre><code>app.post('/createSession', async (req, res) => {
req.session['test'] = "HIIIII";
res.send("200");
})
app.post('/getSession', async (req, res) => {
console.log(req.session['test']);
res.send("200");
})
</code></pre>
<hr />
<h2>AJAX Code</h2>
<p>There are 2 ajax calls, one is to create the session and the other is to retrieve the session.</p>
<pre><code>$.ajax({
url: `https://example.com/createSession`,
type: "POST",
dataType: "json",
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (result) {
console.log(result);
}
});
$.ajax({
url: `https://example.com/getSession`,
type: "POST",
dataType: "json",
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (result) {
console.log(result);
}
});
</code></pre>
<hr />
<h2>Problem</h2>
<p>Upon POST to <code>/createSession</code>, I received this issue
<a href="https://i.stack.imgur.com/sWuoW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sWuoW.png" alt="enter image description here" /></a></p>
<p>However, when I changed secure to true - <code>secure: true</code>, The <code>/createSession</code> request doesn't even contain a <code>set-cookie</code> header.</p>
<p>Thus, when I POST to <code>/getSession</code>, it shows as <code>undefined</code>.</p>
<p>Could someone help me out with this please? For some reason I seem to get stuck with sessions on almost every project I embark on. :/</p>
| 3 | 1,230 |
Add and edit form in one page
|
<p>I have two buttons 'Add' and 'Edit' in my page. When I try to click the 'Add' button I get one popup form and I fill the details and will be added in to the database. The same thing when I click the 'Edit' button the same form should be displayed with the filled in details. I know how to get the data from the backend. But I am not aware of how should I differentiate the add and edit in one form.</p>
<p><a href="https://jqueryui.com/dialog/#modal-form" rel="nofollow noreferrer">https://jqueryui.com/dialog/#modal-form</a></p>
<p>I have refered this link and I have added the details for add form.
Can some one help me how do I do the edit?</p>
<pre><code><html>
<input class="btn btn-info" type="button" id="create-user" value="Add user">
<div class="row-fluid top-space-20">
{% if result | length == 0 %}
<div>
<p>There are no user details ,If you want you can add it </p>
</div>
{% else %}
<table class="table table-striped">
<thead>
<th>user name</th>
<th>user duration</th>
<th>user Description</th>
<th>user requirements</th>
<th>Actions</th>
</thead>
{% for each_item in result %}
<tbody>
<td>{{each_item.user_name}}</td>
<td>{{each_item.user_time}}</td>
<td>{{each_item.user_description}}</td>
<td>{{each_item.user_requirement}}</td>
<td>
<input class="btn btn-info" type="button" id="edituser" value="Edit">
</td>
</tbody>
{% endfor %}
{% endif %}
</table>
</div>
</div>
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="username">user name</label>
<input type="text" name="username" id="username" class="text ui-widget-content ui-corner-all">
<label for="duration">Duration</label>
<input type="text" name="duration" id="duration" class="text ui-widget-content ui-corner-all">
<label for="description">Description</label>
<input type="text" name="description" id="description" class="text ui-widget-content ui-corner-all">
<label for="requirements">Requirements</label>
<input type="requirements" name="requirements" id="requirements"
class="text ui-widget-content ui-corner-all">
<input type="hidden" id='departmentId' ,value="{{department_id}}">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<script>
$(function () {
var dialog, form,
username = $("#username"),
duration = $("#duration"),
description = $("#description"),
requirements = $("#requirements"),
allFields = $([]).add(username).add(duration).add(description).add(requirements),
tips = $(".validateTips");
function updateTips(t) {
console.log(t);
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
var username = $("#username");
var duration = $("#duration");
var description = $("#description");
var requirements = $("#requirements");
var departmentId = document.getElementById("departmentId").value;
valid = valid && checkLength(username, "username", 3, 16);
valid = valid && checkLength(duration, "duration", 3, 16);
valid = valid && checkLength(description, "description", 3, 300);
valid = valid && checkLength(requirements, "requirments", 5, 300);
if (valid) {
var username = $("#username").val();
var duration = $("#duration").val();
var description = $("#description").val();
var requirements = $("#requirements").val();
var departmentId = document.getElementById("departmentId").value;
$("#users tbody").append("<tr>" +
"<td>" + username + "</td>" +
"<td>" + duration + "</td>" +
"<td>" + description + "</td>" +
"<td>" + requirements + "</td>" +
"</tr>");
$.ajax({
type: 'POST',
url: '/department/%d/user' % departmentId,
data: {
'username': username,
'duration': duration,
'description': description,
'requirements': requirements
},
success: function (result) {
console.log(result);
alert("The user has been added");
document.location.href = "/departments";
},
})
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Create user": addUser,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
addUser();
});
$("#create-user").button().on("click", function () {
console.log("I am first");
dialog.dialog("open");
});
});
</script>
</body>
</html>
</code></pre>
| 3 | 4,268 |
Get prop that passed from child component
|
<p>I have an react native app where I render map in App.js and this is the states of App.js:</p>
<pre><code>this.state = {
region: null,
shops: [
{
name: "name",
rating: 0,
coords: {
latitude: 543543,
longitude: 656546
}
}
]
};
</code></pre>
<p>and this is the render code of it:</p>
<pre><code> render() {
const { region, shops } = this.state;
return (
<SafeAreaView style={styles.container}>
<Map region={region} places={shops} />
</SafeAreaView>
);
}
</code></pre>
<p>as you can see I pass the shops state to Map component and in map component I have this main render to render the MapView:</p>
<pre><code>render() {
const region = this.props.region;
return (
<MapView
style={styles.container}
region={region}
showsUserLocation
showsMyLocationButton
>
{this.renderMarkers()}
</MapView>
);
</code></pre>
<p>you can see the this.renderMarkers() where the markers of shops exist:</p>
<pre><code>renderMarkers() {
return this.props.places.map((marker, i) => (
<Marker key={i} title={marker.name} coordinate={marker.coords} >
<View style={{
flexDirection: 'row', width: 70, height: 60,
backgroundColor: 'none',
}}>
<Svg
width={60} height={50}>
<Image
href={require('icon.png')}
/>
<Rating rating={marker.rating} />
</Svg>
</View>
</Marker>
));
}
</code></pre>
<p>each marker contain Image and Rating components and what I'm trying to do it to pass the rating like this: rating={marker.rating} to the component of Rating</p>
<p>now in the Rating component I'm trying to get the rating like this:</p>
<pre><code>render() {
let ratings = this.props.places;
let stars = [];
for (var i = 1; i <= 5; i++) {
if (i > ratings.rating) {
// do something
}
}
return (
<View style={styles.container}>
{ stars }
</View>
);
}
</code></pre>
<p>now you understand that I pass the whole object of states from App component to Map component then I want to pass only the rating prop from Map component to Rating component
how to do that?</p>
| 3 | 1,160 |
Pass a named list of models to anova.merMod
|
<p>I want to be able to pass a named list of models (merMod objects) to anova() and preserve the model names in the output. This is particularly useful in the context of using mclapply() to run a batch of slow models like glmers more efficiently in parallel. The best I've come up with is to use do.call on a de-named version of the model list, but that's not ideal because I might have models named (say) "mod12", "mod17", and "mod16" and these model names get translated to "MODEL1", "MODEL2", and "MODEL3" in the output. (That might seem trivial when looking at a single batch, but over the course of a long modeling session with dozens of models it's a surefire recipe for confusion.)</p>
<p>Note that this isn't the same issue as <a href="https://stackoverflow.com/questions/18108045/create-and-call-linear-models-from-list">Create and Call Linear Models from List</a> because I'm not trying to compare pairs of models across lists. It's also more complex than <a href="https://stackoverflow.com/questions/15172738/using-lapply-on-a-list-of-models">Using lapply on a list of models</a> because I'm using anova() in a non-unary way.</p>
<p>Here's a minimal reprex:</p>
<pre><code>library(lme4)
formList <- c(mod12 = angle ~ recipe + temp + (1|recipe:replicate),
mod17 = angle ~ recipe + temperature + (1|recipe:replicate),
mod16 = angle ~ recipe * temperature + (1|recipe:replicate))
modList <- lapply(formList, FUN=lmer, data=cake)
# Fails because modList is named so it's interpreted as arg-name:arg pairs
do.call(anova, modList)
# Suboptimal because model names aren't preserved
do.call(anova, unname(modList))
# Fails because object isn't merMod (or some other class covered by methods("anova"))
do.call(anova, list(object=modList[1], ...=modList[-1], model.names=names(modList)))
</code></pre>
<p>The second do.call returns this:</p>
<pre><code>Data: ..1
Models:
MODEL1: angle ~ recipe + temp + (1 | recipe:replicate)
MODEL2: angle ~ recipe + temperature + (1 | recipe:replicate)
MODEL3: angle ~ recipe * temperature + (1 | recipe:replicate)
Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq)
MODEL1 6 1708.2 1729.8 -848.08 1696.2
MODEL2 10 1709.6 1745.6 -844.79 1689.6 6.5755 4 0.1601
MODEL3 20 1719.0 1791.0 -839.53 1679.0 10.5304 10 0.3953
</code></pre>
<p>Ideally, the output would look like this:</p>
<pre><code>Data: ..1
Models:
mod12: angle ~ recipe + temp + (1 | recipe:replicate)
mod17: angle ~ recipe + temperature + (1 | recipe:replicate)
mod16: angle ~ recipe * temperature + (1 | recipe:replicate)
Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq)
mod12 6 1708.2 1729.8 -848.08 1696.2
mod17 10 1709.6 1745.6 -844.79 1689.6 6.5755 4 0.1601
mod16 20 1719.0 1791.0 -839.53 1679.0 10.5304 10 0.3953
</code></pre>
<p>How do I do this? I'm more than happy with an ugly wrapper around anova() if it means I get a more intelligible output.</p>
| 3 | 1,158 |
PHP cURL GET request is not returning JSON object
|
<p>I'm attempting to use PHP cURL to write a GET request that returns information in JSON format so I can decode it and store the header values accordingly in a Response class. My request goes through successfully with a 200 Status code, but the actual response is coming back as a string rather than an object that I can work with. I am using the generated code from Postman for cURL.</p>
<p>Here my PHP code for the request:</p>
<pre><code>
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://example.com",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array('Content-Type: application/json',
'Accept: application/json')
));
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);
</code></pre>
<p>And here is the result I get from the var_dump($result):</p>
<pre><code>string(1619) "HTTP/1.1 200 OK
Content-Encoding: gzip
Age: 455672
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Tue, 23 Jun 2020 21:42:08 GMT
Etag: "3147526947+ident+gzip"
Expires: Tue, 30 Jun 2020 21:42:08 GMT
Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
Server: ECS (sjc/4E73)
Vary: Accept-Encoding
X-Cache: HIT
Content-Length: 648
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
div {
margin: 0 auto;
width: auto;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
"
</code></pre>
| 3 | 1,481 |
Cassandra UNREACHABLE node
|
<p>I have Cassandra v3.9, 3 node cluster. Replication factor 2</p>
<p>10.0.0.11,10.0.0.12,10.0.0.13</p>
<p>10.0.0.11,10.0.0.12 are seed nodes</p>
<p><strong>What could be the possible reasons</strong> for following error in /etc/cassandra/conf/debug.log</p>
<p>The error is</p>
<p>DEBUG [RMI TCP Connection(174)-127.0.0.1] 2017-07-12 04:47:49,002 StorageProxy.java:2254 - Hosts not in agreement. Didn't get a response from everybody: 10.0.0.13</p>
<p><strong>UPDATE1:</strong> </p>
<p>At the time of the error here are some statistics from all the servers</p>
<pre><code>[user1@ip-10-0-0-11 ~]$ nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
-- Address Load Tokens Owns (effective) Host ID Rack
UN 10.0.0.12 2.55 MiB 256 67.2% 83a68750-2238-4a6e-87be-03a3d7246824 rack1
UN 10.0.0.11 1.78 GiB 256 70.6% 052fda9d-0474-4dfb-b2f8-0c5cbec15266 rack1
UN 10.0.0.13 1.78 GiB 256 62.2% 86438dc9-77e0-43b2-a672-5b2e7cf216bf rack1
[user1@ip-10-0-0-11 ~]$ nodetool describecluster
Cluster Information:
Name: PiedmontCluster
Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
Schema versions:
3c8d9e82-c688-3d16-a3e9-b84894168283: [10.0.0.12, 10.0.0.11]
UNREACHABLE: [10.0.0.13]
[pnm@ip-10-0-0-13 ~]$ nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
-- Address Load Tokens Owns (effective) Host ID Rack
UN 10.0.0.12 2.55 MiB 256 67.2% 83a68750-2238-4a6e-87be-03a3d7246824 rack1
UN 10.0.0.11 1.78 GiB 256 70.6% 052fda9d-0474-4dfb-b2f8-0c5cbec15266 rack1
UN 10.0.0.13 1.78 GiB 256 62.2% 86438dc9-77e0-43b2-a672-5b2e7cf216bf rack1
[pnm@ip-10-0-0-13 ~]$ nodetool describecluster
Cluster Information:
Name: PiedmontCluster
Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
Schema versions:
3c8d9e82-c688-3d16-a3e9-b84894168283: [10.0.0.12, 10.0.0.13]
UNREACHABLE: [10.0.0.11]
[user1@ip-10-0-0-12 ~]$ nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
-- Address Load Tokens Owns (effective) Host ID Rack
UN 10.0.0.12 2.55 MiB 256 67.2% 83a68750-2238-4a6e-87be-03a3d7246824 rack1
UN 10.0.0.11 1.78 GiB 256 70.6% 052fda9d-0474-4dfb-b2f8-0c5cbec15266 rack1
UN 10.0.0.13 1.78 GiB 256 62.2% 86438dc9-77e0-43b2-a672-5b2e7cf216bf rack1
[user1@ip-10-0-0-12 ~]$ nodetool describecluster
Cluster Information:
Name: PiedmontCluster
Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
Schema versions:
3c8d9e82-c688-3d16-a3e9-b84894168283: [10.0.0.12, 10.0.0.11, 10.0.0.13]
</code></pre>
<p>The above mentioned error is in the /var/log/cassandra/debug.log on 10.0.0.11</p>
<p>Error in /var/log/cassandra/debug.php on 10.0.0.13 is</p>
<pre><code> DEBUG [RMI TCP Connection(4)-127.0.0.1] 2017-07-13 02:31:23,846 StorageProxy.java:2254 - Hosts not in agreement. Didn't get a response from everybody: 10.0.0.11
ERROR [MessagingService-Incoming-/10.0.0.11] 2017-07-13 02:35:04,982 CassandraDaemon.java:226 - Exception in thread Thread[MessagingService-Incoming-/10.0.0.11,5,main]
java.lang.ArrayIndexOutOfBoundsException: 4
at org.apache.cassandra.db.filter.AbstractClusteringIndexFilter$FilterSerializer.deserialize(AbstractClusteringIndexFilter.java:74) ~[apache-cassandra-3.9.0.jar:3.9.0]
at org.apache.cassandra.db.SinglePartitionReadCommand$Deserializer.deserialize(SinglePartitionReadCommand.java:1041) ~[apache-cassandra-3.9.0.jar:3.9.0]
at org.apache.cassandra.db.ReadCommand$Serializer.deserialize(ReadCommand.java:696) ~[apache-cassandra-3.9.0.jar:3.9.0]
at org.apache.cassandra.db.ReadCommand$Serializer.deserialize(ReadCommand.java:626) ~[apache-cassandra-3.9.0.jar:3.9.0]
at org.apache.cassandra.io.ForwardingVersionedSerializer.deserialize(ForwardingVersionedSerializer.java:50) ~[apache-cassandra-3.9.0.jar:3.9.0]
at org.apache.cassandra.net.MessageIn.read(MessageIn.java:114) ~[apache-cassandra-3.9.0.jar:3.9.0]
at org.apache.cassandra.net.IncomingTcpConnection.receiveMessage(IncomingTcpConnection.java:190) ~[apache-cassandra-3.9.0.jar:3.9.0]
at org.apache.cassandra.net.IncomingTcpConnection.receiveMessages(IncomingTcpConnection.java:178) ~[apache-cassandra-3.9.0.jar:3.9.0]
at org.apache.cassandra.net.IncomingTcpConnection.run(IncomingTcpConnection.java:92) ~[apache-cassandra-3.9.0.jar:3.9.0]
</code></pre>
<p>No error in /var/log/cassandra/debug.php on 10.0.0.12</p>
<p>Remember 10.0.0.11 & 10.0.0.12 are seed nodes</p>
<p>Thanks</p>
| 3 | 2,703 |
OpenSSL error while loading RubyMine on Snow Loepard 10.6
|
<p>I installed Rais and Ruby 2.x via RVM months ago when I was using OSX 10.6. Today I made blunder to try installing <code>PhantonJS</code> via HomeBrew. it also tried to install <code>openssl-1.0.1i.tar.gz</code> and installed too. I could not install PhantomJS as it was taking time but resta assured OpenSSL was installed. This evening when I tried to load <code>RubyMine</code> for work I got following errors:</p>
<pre><code>10:36:04 PM Failed to load remote gems
Error loading RubyGems plugin "/Users/JhonDoe/.rvm/gems/ruby-2.1.2@global/gems/executable-hooks-1.3.2/lib/rubygems_plugin.rb": dlopen(/Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Referenced from: /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle
Reason: image not found - /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle (LoadError)
Error loading RubyGems plugin "/Users/JhonDoe/.rvm/gems/ruby-2.1.2@global/gems/gem-wrappers-1.2.5/lib/rubygems_plugin.rb": dlopen(/Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Referenced from: /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle
Reason: image not found - /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle (LoadError)
/Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require': dlopen(/Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (LoadError)
Referenced from: /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle
Reason: image not found - /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/openssl.rb:17:in `'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/https.rb:22:in `'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/request.rb:39:in `configure_connection_for_https'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/request.rb:93:in `connection_for'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/request.rb:122:in `fetch'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/remote_fetcher.rb:337:in `request'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/remote_fetcher.rb:231:in `fetch_http'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/remote_fetcher.rb:266:in `fetch_path'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/remote_fetcher.rb:296:in `cache_update_path'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/source.rb:177:in `load_specs'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/spec_fetcher.rb:266:in `tuples_for'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/spec_fetcher.rb:231:in `block in available_specs'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/source_list.rb:97:in `each'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/source_list.rb:97:in `each_source'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/spec_fetcher.rb:222:in `available_specs'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/spec_fetcher.rb:147:in `detect'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/commands/query_command.rb:165:in `show_gems'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/commands/query_command.rb:109:in `block in execute'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/commands/query_command.rb:109:in `each'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/commands/query_command.rb:109:in `execute'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/command.rb:305:in `invoke_with_build_args'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/command_manager.rb:167:in `process_args'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/command_manager.rb:137:in `run'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/gem_runner.rb:54:in `run'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/bin/gem:21:in `'
Please check proxy settings and gem urls (show balloon)
10:36:05 PM Failed to load remote gems http://gems.github.com
Error loading RubyGems plugin "/Users/JhonDoe/.rvm/gems/ruby-2.1.2@global/gems/executable-hooks-1.3.2/lib/rubygems_plugin.rb": dlopen(/Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Referenced from: /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle
Reason: image not found - /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle (LoadError)
Error loading RubyGems plugin "/Users/JhonDoe/.rvm/gems/ruby-2.1.2@global/gems/gem-wrappers-1.2.5/lib/rubygems_plugin.rb": dlopen(/Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Referenced from: /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle
Reason: image not found - /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle (LoadError)
/Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require': dlopen(/Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (LoadError)
Referenced from: /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle
Reason: image not found - /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin10.0/openssl.bundle
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/openssl.rb:17:in `'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/https.rb:22:in `'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/request.rb:39:in `configure_connection_for_https'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/request.rb:93:in `connection_for'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/request.rb:122:in `fetch'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/remote_fetcher.rb:337:in `request'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/remote_fetcher.rb:231:in `fetch_http'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/remote_fetcher.rb:266:in `fetch_path'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/remote_fetcher.rb:296:in `cache_update_path'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/source.rb:177:in `load_specs'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/spec_fetcher.rb:266:in `tuples_for'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/spec_fetcher.rb:231:in `block in available_specs'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/source_list.rb:97:in `each'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/source_list.rb:97:in `each_source'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/spec_fetcher.rb:222:in `available_specs'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/spec_fetcher.rb:147:in `detect'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/commands/query_command.rb:165:in `show_gems'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/commands/query_command.rb:109:in `block in execute'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/commands/query_command.rb:109:in `each'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/commands/query_command.rb:109:in `execute'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/command.rb:305:in `invoke_with_build_args'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/command_manager.rb:167:in `process_args'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/command_manager.rb:137:in `run'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/gem_runner.rb:54:in `run'
from /Users/JhonDoe/.rvm/rubies/ruby-2.1.2/bin/gem:21:in `'
Please check proxy settings and gem urls (show balloon)
10:36:07 PM RubyMine Gem Manager
RubyMine has detected that
some of the gems required for 'HITS'
are not installed
Install missing gems
(show balloon)
</code></pre>
<p>As you can see it is not finding required <code>openssl</code> libs. How do I sort this out? </p>
| 3 | 5,815 |
Networking not working on Docker / Centos 7.9
|
<p>I'm running Docker on Centos 7.9.2009 and have a very strange issue. The containers do not have network access and cannot be accessed from the host. I've searched for potential solutions, a lot of which seem to be related to DNS issues (which I don't think is what's going on here since even pinging 8.8.8.8 from within the container does not work). I've tried installing iptables-service, restarting iptables & docker in that order, full reboot etc.</p>
<p>In my efforts to try and find what the problem might be, I ran tcpdump in a separate terminal. As soon as I did, everything works fine! Kill the tcpdump process and it all stops - no network access. Any suggestions of why running tcpdump may resolve the problem? Is it something to do with tcpdump listening on docker0 and establishing a network state?</p>
<p>Output of tcpdump on startup:</p>
<pre><code>tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on docker0, link-type EN10MB (Ethernet), capture size 262144 bytes
</code></pre>
<p>Output of uname -a:</p>
<pre><code>Linux 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19 22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
</code></pre>
<p>Output of /etc/redhat-release:</p>
<pre><code>CentOS Linux release 7.9.2009 (Core)
</code></pre>
<p>Output of ip addr:</p>
<pre><code>3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:8b:94:46:19 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:8bff:fe94:4619/64 scope link
valid_lft forever preferred_lft forever
</code></pre>
<p>Output of iptables --list -t nat:</p>
<pre><code> Chain PREROUTING (policy ACCEPT)
target prot opt source destination
DOCKER all -- anywhere anywhere ADDRTYPE match dst-type LOCAL
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
DOCKER all -- anywhere !loopback/8 ADDRTYPE match dst-type LOCAL
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
MASQUERADE all -- 172.17.0.0/16 anywhere
Chain DOCKER (2 references)
target prot opt source destination
RETURN all -- anywhere anywhere
</code></pre>
<p>Output of docker version:</p>
<pre><code> Client: Docker Engine - Community
Version: 19.03.13
API version: 1.40
Go version: go1.13.15
Git commit: 4484c46d9d
Built: Wed Sep 16 17:03:45 2020
OS/Arch: linux/amd64
Experimental: false
Server: Docker Engine - Community
Engine:
Version: 19.03.13
API version: 1.40 (minimum version 1.12)
Go version: go1.13.15
Git commit: 4484c46d9d
Built: Wed Sep 16 17:02:21 2020
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.3.7
GitCommit: 8fba4e9a7d01810a393d5d25a3621dc101981175
runc:
Version: 1.0.0-rc10
GitCommit: dc9208a3303feef5b3839f4323d9beb36df0a9dd
docker-init:
Version: 0.18.0
GitCommit: fec3683
</code></pre>
<p>Thanks in advance!</p>
| 3 | 1,365 |
Using LESS how to target the granparent from child element?
|
<p>I'm trying to target a specific popover that a div with class "s-formgroup" and set its background RED as I have multiple popovers. Either my js nor my less do the trick</p>
<p><a href="http://jsfiddle.net/2XmVC/" rel="nofollow">FIDDLE</a></p>
<h1>HTML</h1>
<pre><code><div class="popover>
<div class="popover-content">
<div class="form-group s-formgroup">
</div>
</div>
</div>
</code></pre>
<h1>CSS LESS</h1>
<pre><code>.popover {
.popover-content{
.s-formgroup {
& &.popover {
left: 120px;
}
}
}
}
</code></pre>
<h1>JS</h1>
<pre><code> w = $(window).width();
if (w < 320){
$('.s-formgroup').parents('.popover').css('background-color', 'red');
}
</code></pre>
<h1>Code on inspecting popover (press12)</h1>
<pre><code><div class="popover fade right in" style="top: -41.5px; left: 16px; display: block;"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p>
<div class="form-group s-formgroup">
<div class="age-grp1 pull-left">
<label for="kid19">UNDER 19 YEARS</label>
<input type="text" class="pull-left numbersOnlyField" maxlength="2" value="" id="kid19">
</div>
<div class="age-grp2 pull-right">
<label for="kid26">19-26 YEARS</label>
<input type="text" class="pull-left numbersOnlyField" maxlength="2" value="" id="kid26">
</div>
<div class="row-fluid">
<button class="btn btn-default btn-block btn-lg" id="kids" type="button">ok</button>
</div>
</div>
</p></div></div></div>
</code></pre>
| 3 | 1,503 |
Is there a way to pass certain info, that is specific to a user, to the fields of a (new) django form?
|
<p>I have the following "problem":
I have automated a "prediction-game" where users can win points when they predict the correct winners in a sports event over multiple weeks (for example: Tour de France).
They are allowed to choose 5 athletes of which they think that will win in the races.
At the end of every week, the users are allowed to make some changes in their prediction for the next week.</p>
<p>Until a certain date (start of the event or week), the users can choose athletes for their prediction. The users can fill in the form and if they change their minds before the start, they are still able to change/update their prediction. But after the start, they can't change it anymore and their input will be used to calculate their score. After the first week (in which their scores are calculate with the input they made in the "PredictionWeek1" model), they will have a change to make a new prediction for the next week ("PredictionWeek2" model) for which they also have the change to update it as much as they want before a certain date.</p>
<p>In reality, the input for the second week, will be very similar to the first week: the users probably only want to change one or two athletes. Therefore, and this is the question, it will be best that the input form of "PredictionWeek2" is already filled in with their predictions for week 1, so that they don't have to select every athlete again.</p>
<p>I have already tried to look for a way that their input from "PredictionWeek1" gets passed to the "default" argument for the 'charfield' in the models, but without any luck: I do not get it to be user specific...
I also tried to do something similar as the "UpdateView", but this was also not a solution the input for PredictionWeek2 can't be an "update" for PredictionWeek1: the point calculations in the first week need to be done with the input of PredictionWeek1 and the point calculations for the second week need to be done with the input of PredictionWeek2, so this need to be always a seperate input)</p>
<p>The used code below (a little bit simplified for better comprehension):</p>
<p>In views.py:</p>
<p>class PredictionWeek1CreateView(LoginRequiredMixin, CreateView):</p>
<pre><code>model = PredictionWeek1
fields = ['prediction1', 'prediction2', 'prediction3', 'prediction4', 'prediction5']
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
</code></pre>
<p>class TourPronoWeek1UpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):</p>
<pre><code>model = PredictionWeek1
template_name = 'folder/prediction1_update.html'
fields = ['prediction1', 'prediction2', 'prediction3', 'prediction4', 'prediction5']
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
def test_func(self):
prediction = self.get_object()
if self.request.user == prediction.user:
return True
return False
</code></pre>
<p>class PredictionWeek2CreateView(LoginRequiredMixin, CreateView):</p>
<pre><code>model = PredictionWeek2
fields = ['prediction1', 'prediction2', 'prediction3', 'prediction4', 'prediction5']
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
</code></pre>
<p>class PredictionWeek2UpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):</p>
<pre><code>model = PredictionWeek2
template_name = 'folder/predictionweek2_update.html'
fields = ['prediction1', 'prediction2', 'prediction3', 'prediction4', 'prediction5']
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
def test_func(self):
prediction = self.get_object()
if self.request.user == prediction.user:
return True
return False
</code></pre>
<p>in models.py:</p>
<p>#FYI:'startlist' is the list of athletes that compete and which the users can choose from</p>
<p>class PredictionWeek1(models.Model):</p>
<pre><code>prediction1 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
prediction2 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
prediction3 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
prediction4 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
prediction5 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def clean(self):
prediction = [self.prediction1, self.prediction2, self.prediction3, self.prediction4, self.prediction5]
if len(prediction) != len(set(prediction)):
raise ValidationError('Error, you have chosen the same athlete two times!')
def __str__(self):
return str(self.user)
def get_absolute_url(self):
return reverse('MyPrediction')
</code></pre>
<p>class PredictionWeek2(models.Model):</p>
<pre><code>prediction1 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
prediction2 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
prediction3 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
prediction4 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
prediction5 = models.CharField(verbose_name = False, max_length=100, choices = startlist)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def clean(self):
prediction = [self.prediction1, self.prediction2, self.prediction3, self.prediction4, self.prediction5]
if len(prediction) != len(set(prediction)):
raise ValidationError('Error, you have chosen the same athlete two times!')
def __str__(self):
return str(self.user)
def get_absolute_url(self):
return reverse('MyPrediction')
</code></pre>
<p>Thanks in advance!</p>
| 3 | 1,859 |
CSS file is styling unintended elements
|
<p>Bear with me as I am new to web development and will try to explain my issue properly.</p>
<p>So basically I'm trying to style a certain element on my web page but the issue is that it is also applying that styling to the footer as well, which is not what I want. Here's what I'm trying to achieve:</p>
<pre><code><div id="message" class="bg-dark">
<div class="container-fluid padding">
<div class="row text-center padding">
<div class="col-md-12 col-lg-6">
<h2>CEO's Message</h2>
<p>content</p>
</div>
<div class="col-lg-5">
<img src="images/ceo.jpg" class="img-fluid">
</div>
</div>
<hr class="my-4">
</div>
</div>
</code></pre>
<p>Now, I've even given the id tag to specifically style this div.</p>
<p>and the footer is as follows:</p>
<pre><code><footer>
<div class="container-fluid padding">
<div class="row text-center">
<div class="col-md-4">
<img src="images/irco.png">
<hr class="light">
<p>(+92)51 21301</p>
<p>info@irco</p>
<p>address</p>
<p>address</p>
<p>address</p>
</div>
<div class="col-md-4">
<hr class="light">
<h5>Information</h5>
<hr class="light">
<p>About Us</p>
<p>Help Desk</p>
<p>Support</p>
<p>Privacy Policy</p>
<p>Terms & Conditions</p>
</div>
<div class="col-md-4">
<h5>Subscribe to our newsletter</h5>
<p>Stay updated with all the latest updates.</p>
</div>
<div class="col-12">
<hr class="light">
<h5>&copy; irco</h5>
</div>
</div>
</div>
</footer>
</code></pre>
<p>And the styling done in the CSS file:</p>
<pre><code>#message h2, p{
color: white;
padding-top: 4rem;
}
footer{
background-color: #3f3f3f;
color: #d5d5d5;
padding-top: 2rem;
}
</code></pre>
<p>Now, even that white color and the 4rem padding is being applied to the footer and the padding is being applied in between the <p> elements so everything's all stretched out and I can't figure out what I am doing wrong here. What I want is to just simply apply the white color and the padding to the #message portion and leave the footer alone.</p>
| 3 | 1,268 |
Laravel 6.10 Application works locally but fails on production server with "Target class [] does not exist."
|
<p>This problem deals specifically with Laravel 6.10 and queue processing. On my local machine, the program runs fine, and all queued jobs load well and process to completion. On my GoDaddy server, I get a mysterious error when the job tries to load that reads:</p>
<pre>
Error thrown on line 805 in /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Container/Container.php with message:
Target class [] does not exist.
Trace:
#0 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(681): Illuminate\Container\Container->build(NULL)
#1 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(629): Illuminate\Container\Container->resolve(NULL, Array)
#2 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(776): Illuminate\Container\Container->make(NULL, Array)
#3 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(215): Illuminate\Foundation\Application->make(NULL)
#4 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(88): Illuminate\Queue\Jobs\Job->resolve(NULL)
#5 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(354): Illuminate\Queue\Jobs\Job->fire()
#6 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(300): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#7 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(134): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#8 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(112): Illuminate\Queue\Worker->daemon('database', 'default', Object(Illuminate\Queue\WorkerOptions))
#9 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(96): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')
#10 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#11 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#12 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Container/Util.php(36): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#13 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
#14 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#15 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(590): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#16 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Console/Command.php(201): Illuminate\Container\Container->call(Array)
#17 /home/jaredclemence/public_html/theninjaassistant.com/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#18 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Console/Command.php(188): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#19 /home/jaredclemence/public_html/theninjaassistant.com/vendor/symfony/console/Application.php(1011): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#20 /home/jaredclemence/public_html/theninjaassistant.com/vendor/symfony/console/Application.php(272): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#21 /home/jaredclemence/public_html/theninjaassistant.com/vendor/symfony/console/Application.php(148): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#22 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Console/Application.php(93): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#23 /home/jaredclemence/public_html/theninjaassistant.com/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(131): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#24 /home/jaredclemence/public_html/theninjaassistant.com/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#25 {main}
</pre>
<p>I believe the problem starts and will be solved by fixing the trace at item #4 where the following is called: <code>Illuminate\Queue\Jobs\Job->resolve(NULL)</code>. I see this in both failing jobs on the GoDaddy server, but it does not happen in local. I don't know enough about laravel to understand where the NULL value is coming from and how to fix it. This occurs before the job class is loaded, but it does not happen for all queued jobs. Only jobs of this class.</p>
<p>In both the local copy and the production copy I use the GoDaddy databases, so both systems talk to the same database host. I use a database named CMP_dev and CMP_core to differentiate between the development and production tables. Because I am using the same database source, I can rule out changes in the mysql settings.</p>
<p>I upgraded all composer packages and retested. Then, I committed the composer.lock file and updated the GoDaddy server to match. So, I can rule out problems with old buggy code that have already been fixed by someone else.</p>
<p>The PHP version on the server is 7.3.11, and the PHP version on local dev is 7.3.6. The good news is that they are both 7.3.X, which reduces risk of language variations, but there still may be an issue between 7.3.6 and 7.3.11, but GoDaddy does not allow me to control the PHP setting beyond the minor version number of 7.3.</p>
<p>---- Added on January 09, 2020------
I thought it might be the difference in web servers. On my local machine, I use <code>php artisan serve</code> to host the software. On GoDaddy, I use Nginx. However, then I realized that it is not the server that runs the queue. The command line runs the queue, and both commands are being run using <code>php artisan schedule:run</code>. This rules out the web server software and all its components.
-<em>-</em>-<em>-</em>-<em>-</em>-<em>-</em>-</p>
<p>I have successfully run queued mail jobs, which means that the queue works. This should localize the issue to the two classes that are generating problems for me. If I can find the issue with one, I will likely find the issue with the second, so I will include the first job causing issue here:</p>
<p>app/Jobs/ConvertCsvFileToIntermediateFile.php:
<pre><code>namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\ContactCsvFile;
use Illuminate\Support\Facades\Log;
class ConvertCsvFileToIntermediateFile implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 500;
/** @var ContactCsvFile */
private $file;
private $delegate;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(ContactCsvFile $file, $delegate = null)
{
$this->file = $file;
$this->delegate = $delegate;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->file->process($this->delegate);
}
}
</code></pre>
<p>The error is occurring before handle() is ever called. I know this because, when I include a <code>dd($this->file)</code> as the first line of handle, the line is never reached.</p>
<p>Also, I think it is important to note that when most jobs fail, their class name is listed in the queue:failed table. But in this case, the queue:failed table reads the time: "2020-01-08 09:23:23."</p>
<pre>
+----+------------+---------+---------------------+-----------+
| ID | Connection | Queue | Class | Failed At |
+----+------------+---------+---------------------+-----------+
| 2 | database | default | 2020-01-08 09:23:23 | |
+----+------------+---------+---------------------+-----------+
</pre>
| 3 | 3,159 |
HTTPS Giving Segfault in cpp-httplib
|
<p>I'm trying to do some HTTP(<strong>S</strong>) requests with cpp-httplib. Why does</p>
<pre><code>#include <iostream>
#include "httplib.h"
using namespace std;
int main()
{
cout << "hi" << endl;
auto res = httplib::Client("http://stackoverflow.com").Get("/");
cout << res << endl;
return 0;
}
</code></pre>
<p>print</p>
<pre><code>hi
0x5605c058db50
</code></pre>
<p>(OK), but</p>
<pre><code>#include <iostream>
#include "httplib.h"
using namespace std;
int main()
{
cout << "hi" << endl;
auto res = httplib::Client("https://stackoverflow.com").Get("/");
cout << res << endl;
return 0;
}
</code></pre>
<p>(same code, just changed <code>http</code> to <code>https</code>)</p>
<pre><code>hi
Segmentation fault (core dumped)
</code></pre>
<p>?</p>
<p>GDB <code>backtrace</code> gives me this after the segfault:</p>
<pre><code>#0 0x000055555555eee8 in httplib::ClientImpl::Socket::is_open (this=0x50) at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:822
#1 0x0000555555569a20 in httplib::ClientImpl::send (this=0x0, req=..., res=...) at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:4579
#2 0x000055555556bb8b in httplib::ClientImpl::Get(char const*, std::multimap<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, httplib::detail::ci, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > const&, std::function<bool (unsigned long, unsigned long)>) (this=0x0, path=0x5555555bc887 "/", headers=std::multimap with 0 elements, progress=...) at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:4980
#3 0x000055555556ba1d in httplib::ClientImpl::Get (this=0x0, path=0x5555555bc887 "/") at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:4958
#4 0x000055555556c345 in httplib::Client::Get (this=0x7fffffffe320, path=0x5555555bc887 "/") at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:6015
#5 0x000055555555d767 in main () at /home/viktor/delayWatcher/cpp-fetcher/fetcher/main.cpp:11
</code></pre>
| 3 | 1,129 |
"The replica master 0 ran out of disk." During Sklearn Fit in Google Cloud ML Engine
|
<p>I'm trying to use Google Cloud ML Engine to do an <code>sklearn LDA gridsearch</code> on 500 MB data (10000 rows x 26000 columns) to find what number of topics would be the best for my topic modeling project.</p>
<p>The maximum number of iterations for each CV fold was set to 100.
After 47 iterations, the job would fail, citing the below error. I tried this using <code>BASIC</code> tier, <code>STANDARD</code> tier, and a <code>CUSTOM</code> tier with <code>masterType=complex_model_m</code>, and the same error happened every time.</p>
<p>I can't find much else on stackoverflow that talks about this problem, although I did come across <a href="https://stackoverflow.com/questions/55452871/solved-no-space-left-on-device-in-google-cloudml-basic-tier-what-is-the-disk">this link</a>, which seems to be related in some way. A solution was provided by the original asker:</p>
<pre><code>Solved : This error was coming not because of Storage Space instead coming because of shared memory tmfs. The sklearn fit was consuming all the shared memory while training. Solution : setting JOBLIB_TEMP_FOLDER environment variable , to /tmp solved the problem.
</code></pre>
<p>I'm afraid I'm not entirely sure how to interpret or implement the solution.</p>
<p>Here are the three lines relevant to where the problem comes from:</p>
<pre><code>lda = LatentDirichletAllocation(learning_method='batch', max_iter=100, n_jobs=-1, verbose=1)
gscv = GridSearchCV(lda, tuned_parameters, cv=3, verbose=10, n_jobs=1)
gscv.fit(data)
</code></pre>
<p>and I would call the job in the format:</p>
<pre><code>gcloud ai-platform jobs submit training $JOB_NAME \
--package-path $TRAINER_PACKAGE_PATH \
--module-name $MAIN_TRAINER_MODULE \
--job-dir $JOB_DIR \
--region $REGION \
--config config.yaml
</code></pre>
<p>This is the absolutely abhorrent error message in the logs:</p>
<pre><code>sklearn.externals.joblib.externals.loky.process_executor._RemoteTraceback: """ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/externals/loky/backend/queues.py", line 150, in _feed obj_ = dumps(obj, reducers=reducers) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/externals/loky/backend/reduction.py", line 243, in dumps dump(obj, buf, reducers=reducers, protocol=protocol) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/externals/loky/backend/reduction.py", line 236, in dump _LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/externals/cloudpickle/cloudpickle.py", line 284, in dump return Pickler.dump(self, obj) File "/usr/lib/python3.5/pickle.py", line 408, in dump self.save(obj) File "/usr/lib/python3.5/pickle.py", line 520, in save self.save_reduce(obj=obj, *rv) File "/usr/lib/python3.5/pickle.py", line 623, in save_reduce save(state) File "/usr/lib/python3.5/pickle.py", line 475, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python3.5/pickle.py", line 810, in save_dict self._batch_setitems(obj.items()) File "/usr/lib/python3.5/pickle.py", line 836, in _batch_setitems save(v) File "/usr/lib/python3.5/pickle.py", line 520, in save self.save_reduce(obj=obj, *rv) File "/usr/lib/python3.5/pickle.py", line 623, in save_reduce save(state) File "/usr/lib/python3.5/pickle.py", line 475, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python3.5/pickle.py", line 810, in save_dict self._batch_setitems(obj.items()) File "/usr/lib/python3.5/pickle.py", line 841, in _batch_setitems save(v) File "/usr/lib/python3.5/pickle.py", line 520, in save self.save_reduce(obj=obj, *rv) File "/usr/lib/python3.5/pickle.py", line 623, in save_reduce save(state) File "/usr/lib/python3.5/pickle.py", line 475, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python3.5/pickle.py", line 810, in save_dict self._batch_setitems(obj.items()) File "/usr/lib/python3.5/pickle.py", line 836, in _batch_setitems save(v) File "/usr/lib/python3.5/pickle.py", line 475, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python3.5/pickle.py", line 770, in save_list self._batch_appends(obj) File "/usr/lib/python3.5/pickle.py", line 797, in _batch_appends save(tmp[0]) File "/usr/lib/python3.5/pickle.py", line 475, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python3.5/pickle.py", line 725, in save_tuple save(element) File "/usr/lib/python3.5/pickle.py", line 475, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python3.5/pickle.py", line 740, in save_tuple save(element) File "/usr/lib/python3.5/pickle.py", line 481, in save rv = reduce(obj) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/_memmapping_reducer.py", line 339, in __call__ for dumped_filename in dump(a, filename): File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/numpy_pickle.py", line 502, in dump NumpyPickler(f, protocol=protocol).dump(value) File "/usr/lib/python3.5/pickle.py", line 408, in dump self.save(obj) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/numpy_pickle.py", line 289, in save wrapper.write_array(obj, self) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/numpy_pickle.py", line 104, in write_array pickler.file_handle.write(chunk.tostring('C')) OSError: [Errno 28] No space left on device """ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/root/.local/lib/python3.5/site-packages/experiment_trainer/experiment.py", line 87, in <module> gscv.fit(data) File "/usr/local/lib/python3.5/dist-packages/sklearn/model_selection/_search.py", line 722, in fit self._run_search(evaluate_candidates) File "/usr/local/lib/python3.5/dist-packages/sklearn/model_selection/_search.py", line 1191, in _run_search evaluate_candidates(ParameterGrid(self.param_grid)) File "/usr/local/lib/python3.5/dist-packages/sklearn/model_selection/_search.py", line 711, in evaluate_candidates cv.split(X, y, groups))) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/parallel.py", line 917, in __call__ if self.dispatch_one_batch(iterator): File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/parallel.py", line 759, in dispatch_one_batch self._dispatch(tasks) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/parallel.py", line 716, in _dispatch job = self._backend.apply_async(batch, callback=cb) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/_parallel_backends.py", line 182, in apply_async result = ImmediateResult(func) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/_parallel_backends.py", line 549, in __init__ self.results = batch() File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/parallel.py", line 225, in __call__ for func, args, kwargs in self.items] File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/parallel.py", line 225, in <listcomp> for func, args, kwargs in self.items] File "/usr/local/lib/python3.5/dist-packages/sklearn/model_selection/_validation.py", line 526, in _fit_and_score estimator.fit(X_train, **fit_params) File "/usr/local/lib/python3.5/dist-packages/sklearn/decomposition/online_lda.py", line 570, in fit batch_update=True, parallel=parallel) File "/usr/local/lib/python3.5/dist-packages/sklearn/decomposition/online_lda.py", line 453, in _em_step parallel=parallel) File "/usr/local/lib/python3.5/dist-packages/sklearn/decomposition/online_lda.py", line 406, in _e_step for idx_slice in gen_even_slices(X.shape[0], n_jobs)) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/parallel.py", line 930, in __call__ self.retrieve() File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/parallel.py", line 833, in retrieve self._output.extend(job.get(timeout=self.timeout)) File "/usr/local/lib/python3.5/dist-packages/sklearn/externals/joblib/_parallel_backends.py", line 521, in wrap_future_result return future.result(timeout=timeout) File "/usr/lib/python3.5/concurrent/futures/_base.py", line 398, in result return self.__get_result() File "/usr/lib/python3.5/concurrent/futures/_base.py", line 357, in __get_result raise self._exception _pickle.PicklingError: Could not pickle the task to send it to the workers.
</code></pre>
<p>The most important of which I can only assume is:</p>
<p><code>OSError: [Errno 28] No space left on device</code></p>
<p>The message: <code>The replica master 0 ran out of disk.</code> was the official cause of the problem according to the console.</p>
<p>I can run this on my own desktop to 100 iterations no problem. Any insight on what's happening is greatly appreciated. Thank you!</p>
| 3 | 3,180 |
Navigating to the Nested child Attribute and Merge with the another Element
|
<p>Here i am stuck with the XSLT transformation as i am very new and started learning.</p>
<p>Input XML</p>
<pre><code><SHOW_LIST>
<SHOW ID="12345">
<SHOW_INFO>xxx</SHOW_INFO>
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="1">
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="12345678"></SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
</SHOW_ELEMENT>
<SHOW_ELEMENT ID="2">
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="12345666"></SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
</SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
<SECONDARY_ELEMENT_LIST/>
<ALTERNATIVE_SHOW_LIST>
<SHOW ID="54321">
<SHOW_INFO>xxxa</SHOW_INFO>
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="3"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="4"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="5"> </SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
<SECONDARY_ELEMENT_LIST/>
</SHOW>
<SHOW ID="54322">
<SHOW_INFO>xxxb</SHOW_INFO>
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="6"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="7"> </SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
<SECONDARY_ELEMENT_LIST/>
</SHOW>
</ALTERNATIVE_SHOW_LIST>
</SHOW>
</code></pre>
<p></p>
<p>OUTPUT XML :</p>
<pre><code><SHOW_LIST>
<SHOW ID="12345">
<SHOW_INFO>xxx</SHOW_INFO>
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="1"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="2"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="3"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="4"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="5"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="6"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="7"> </SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
<SECONDARY_ELEMENT_LIST/>
<ALTERNATIVE_SHOW_LIST>
<SHOW ID="54321">
<SHOW_INFO>xxxa</SHOW_INFO>
<SECONDARY_ELEMENT_LIST/>
</SHOW>
<SHOW ID="54322">
<SHOW_INFO>xxxb</SHOW_INFO>
<SECONDARY_ELEMENT_LIST/>
</SHOW>
</ALTERNATIVE_SHOW_LIST>
</SHOW>
</SHOW_LIST>
</code></pre>
<p>I am able to navigate till Alternative_show_list and couldnt copy the SHOW_ELEMENTS and merge with the main SHOW_ELEMENT_LIST.</p>
<p>Anyone kindly help me in performing this</p>
<p>Another output of the same input file</p>
<pre><code><SHOW_LIST>
<SHOW ID="12345">
<SHOW_INFO>xxx</SHOW_INFO>
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="1"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="2"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="3"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="4"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="5"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="6"> </SHOW_ELEMENT>
<SHOW_ELEMENT ID="7"> </SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
<SECONDARY_ELEMENT_LIST/>
</SHOW>
</SHOW_LIST>
</code></pre>
<p>Now i am trying for this kind of output.</p>
<p>New Output XML</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SHOW_LIST>
<SHOW ID="12345">
<SHOW_INFO>xxx</SHOW_INFO>
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="1">
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="12345678"></SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
</SHOW_ELEMENT>
<SHOW_ELEMENT ID="2">
<SHOW_ELEMENT_LIST>
<SHOW_ELEMENT ID="12345666"></SHOW_ELEMENT>
</SHOW_ELEMENT_LIST>
</SHOW_ELEMENT>
<SHOW_ELEMENT ID="3"/>
<SHOW_ELEMENT ID="4"/>
<SHOW_ELEMENT ID="5"/>
<SHOW_ELEMENT ID="6"/>
<SHOW_ELEMENT ID="7"/>
</SHOW_ELEMENT_LIST>
<SECONDARY_ELEMENT_LIST/>
</SHOW>
</SHOW_LIST>
</code></pre>
| 3 | 3,003 |
Overflow:hidden not working
|
<p>When I run my code in a browser, the background is exactly where I already want it to be, the problem is that I can still scroll down, revealing the part of the background which is originally hidden. I need it so that the picture which I am trying to input does not come off the page, and does not reveal any more of the background.
Here is my code (Sorry I know it's sloppy):</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>XXX</title>
<meta charset="utf-8" />
<style>
body {
background-image:url("Images/Background2.png");
background-size: cover;
background-repeat: no-repeat;
}
.cf img.bottom:hover {
opacity:0;
overflow:hidden;
}
#container1 {
position:relevant;
}
#positioning {
position:absolute;
Top:500px;
Left:500px;
Width:1000px;
Height:600px;
overflow:hidden;
}
</style>
</head>
<body>
<IMG STYLE="position:absolute; TOP:38px; LEFT:90px; WIDTH:220px; HEIGHT:25px" SRC="Images\Logo.png" border:"0" draggable="false" style="-moz-user-select: none;">
<div class="cf">
<img class="top" IMG STYLE="position:absolute; TOP:255px; LEFT:106px; WIDTH:140px; HEIGHT:26px" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\Contact_001.png" border:"0" draggable="false" style="-moz-user-select: none;">
<img class="bottom" IMG STYLE="position:absolute; TOP:255px; LEFT:106px; WIDTH:140px; HEIGHT:26px" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\Contact_002.png" border:"0" draggable="false" style="-moz-user-select: none;">
<img class="top" IMG STYLE="position:absolute; TOP:355px; LEFT:105px; WIDTH:120px; HEIGHT:25px" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\About_001.png" border:"0" draggable="false" style="-moz-user-select: none;">
<img class="bottom" IMG STYLE="position:absolute; TOP:355px; LEFT:105px; WIDTH:120px; HEIGHT:25px" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\About_002.png" border:"0" draggable="false" style="-moz-user-select: none;">
<img class="top" IMG STYLE="position:absolute; TOP:455px; LEFT:108px; WIDTH:100px; HEIGHT:24px" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\Work_001.png" border:"0" draggable="false" style="-moz-user-select: none;">
<img class="bottom" IMG STYLE="position:absolute; TOP:455px; LEFT:108px; WIDTH:100px; HEIGHT:24px" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\Work_002.png" border:"0" draggable="false" style="-moz-user-select: none;">
<img class="top" IMG STYLE="position:absolute; TOP:555px; LEFT:115px; WIDTH:280px; HEIGHT:30px" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\WTU_001.png" border:"0" draggable="false" style="-moz-user-select: none;">
<img class="bottom" IMG STYLE="position:absolute; TOP:555px; LEFT:115px; WIDTH:280px; HEIGHT:30px" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\WTU_002.png" border:"0" draggable="false" style="-moz-user-select: none;">
</div>
<div id="container1">
<div id="positioning">
<img class="bottom" SRC="C:\Users\children\Desktop\PortfolioConcept_001\Images\Photoshop1.png">
</div>
</div>
</body>
</html>
</code></pre>
<p>I did not use a stylesheet at all, thanks in advance to anyone who trys to help.</p>
| 3 | 1,550 |
Change button name when the button is clicked
|
<pre><code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:paylater/res/asset_strings.dart';
import 'package:paylater/res/motito_colors.dart';
import 'package:paylater/res/string_en.dart';
import 'package:paylater/res/style.dart';
import 'package:paylater/screens/motito_stepper.dart';
import 'package:paylater/screens/reset_password_verify.dart';
import 'package:paylater/util/validator.dart';
import 'package:paylater/widget/motito_dialog.dart';
import 'package:paylater/widget/motito_flat_button.dart';
class Resetsteps extends StatefulWidget {
@override
_ResetstepsState createState() => _ResetstepsState();
}
class _ResetstepsState extends State<Resetsteps> {
final _formKey = GlobalKey<FormBuilderState>();
final _phoneController = TextEditingController();
bool phoneFieldEmpty = true;
@override
Widget build(BuildContext context) {
MotitoDialog md = MotitoDialog(
context,
isDismissible: false,
);
md.style(
borderRadius: 8.0,
messageTextStyle: CustomTextStyles.kBody.copyWith(
color: MotitoColors.kNeutralsGrey4,
fontSize: 14.0,
),
);
return MotitoStepper(
step: 1,
total: 3,
leading: GestureDetector(onTap: () {}, child: Icon(CupertinoIcons.arrow_left),),
helpMessage: 'I need help on the forgot my password page',
body: SingleChildScrollView(
child: FormBuilder(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 50.0),
Text(
'Forgot my Password',
style: CustomTextStyles.kHeader3.copyWith(
color: MotitoColors.kSecondaryTextColor1,
),
),
SizedBox(height: 2.0),
Text(
'Please type in your phone number and we will send you a 6 digit code',
style: CustomTextStyles.kBody.copyWith(
color: MotitoColors.kNeutralsGrey5,
fontSize: 14.0,
),
),
SizedBox(height: 32.0),
textFieldLabel(
StringEn.kPhoneNumber,
required: true,
),
TextFormField(
textInputAction: TextInputAction.next,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
controller: _phoneController,
keyboardType: TextInputType.phone,
decoration: inputDecoration(
context,
hint: StringEn.kPhoneHint,
prefixText: '(+233)',
),
onChanged: (phone) {
if (phone != null && phone.isNotEmpty) {
setState(() {
phoneFieldEmpty = false;
});
} else {
setState(() {
phoneFieldEmpty = true;
});
}
},
validator: FormBuilderValidators.compose([
FormBuilderValidators.minLength(context, 9,
errorText: AssetStrings.kInvalidPhone),
FormBuilderValidators.maxLength(context, 10,
errorText: AssetStrings.kInvalidPhone),
Validator.leadingZeroValidator,
]),
),
SizedBox(height: 8.0),
SizedBox(height: 120.0),
</code></pre>
<p>I am a junior intern and was assigned a task to add a new feature on an existing app. I am all done with the UI but cant get a particular function on my code to work here is the code for the button and I want the text to change on the button to "Loading...".</p>
<p>What can I do to achieve that?</p>
<pre><code> MotitoFlatButton(
label: StringEn.kContinue,
enabled: !phoneFieldEmpty,
onTap: () {
if (_formKey.currentState.validate()) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ResetPasswordVerify()));
}
},
),
SizedBox(height: 56.0),
],
),
),
),
);
}
}
</code></pre>
<p>Here is also the code for the button widget.</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:paylater/res/motito_colors.dart';
import 'package:paylater/res/style.dart';
const _buttonRadius = 8.0;
class MotitoFlatButton extends StatelessWidget {
final String label;
final VoidCallback onTap;
final Color bg;
final Color textColor;
final Color disabledBg;
final Color disabledTextColor;
final double width;
final bool enabled;
const MotitoFlatButton({
@required this.label,
@required this.onTap,
this.bg = MotitoColors.kMotitoBlue,
this.textColor = Colors.white,
this.disabledBg = MotitoColors.kButtonDisabled,
this.disabledTextColor = MotitoColors.kButtonDisabledText,
this.width = double.infinity,
this.enabled = true,
});
@override
Widget build(BuildContext context) {
return Material(
borderRadius: BorderRadius.circular(_buttonRadius),
child: InkWell(
onTap: enabled ? onTap : null,
borderRadius: BorderRadius.circular(_buttonRadius),
child: Ink(
padding: const EdgeInsets.symmetric(vertical: 16.0),
width: width,
decoration: BoxDecoration(
color: enabled ? bg : disabledBg,
borderRadius: BorderRadius.circular(_buttonRadius),
),
child: Center(
child: Text(
label,
style: CustomTextStyles.kBody
.copyWith(color: enabled ? textColor : disabledTextColor),
),
),
),
),
);
}
}
</code></pre>
<p>I have tried my best and can't get it to work.</p>
| 3 | 2,966 |
How to set the environment when using `conda build`?
|
<p>Trying to take advantage of Conda's build function to install a package not in conda repositories. I've downloaded the source files for the package I want. At the same level I created a folder for my <em>conda recipes</em> which contains the <code>meta.yaml</code> setting <code>source: path: ../<package-name></code>. So, <em>look up one directory to find the source files</em>. This works.</p>
<p>The problem happens at the end when build attempts to test importing the package. It says <em>x module not found</em>, but I'm invoking <code>conda build</code> from a conda environment where the missing package is installed as shown by <code>conda list</code>. </p>
<p>How do I know from what environment <code>conda build</code> is performing these tests?</p>
<p>How to set the environment when using <code>conda build</code>?</p>
<p>Doesn't help that <a href="https://conda.io/projects/conda-build/en/latest/index.html" rel="nofollow noreferrer">Conda Build</a> docs are full of the word <em>environment</em>, but which mostly refers to <a href="https://docs.conda.io/projects/conda-build/en/latest/user-guide/environment-variables.html" rel="nofollow noreferrer">environmental variables</a> and not <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/concepts/environments.html" rel="nofollow noreferrer">conda environments</a></p>
<pre><code>(base) C:\Users\myhome\PyTools\bin>conda info
active environment : base
active env location : C:\Users\myhome\Miniconda3_64-4.5.4
shell level : 1
user config file : C:\Users\myhome\.condarc
populated config files : C:\Users\myhome\.condarc
conda version : 4.5.4
conda-build version : 3.18.9
python version : 3.6.5.final.0
base environment : C:\Users\myhome\Miniconda3_64-4.5.4 (writable)
channel URLs : https://conda.anaconda.org/anaconda/win-64
https://conda.anaconda.org/anaconda/noarch
https://repo.anaconda.com/pkgs/main/win-64
https://repo.anaconda.com/pkgs/main/noarch
https://repo.anaconda.com/pkgs/free/win-64
https://repo.anaconda.com/pkgs/free/noarch
https://repo.anaconda.com/pkgs/r/win-64
https://repo.anaconda.com/pkgs/r/noarch
https://repo.anaconda.com/pkgs/pro/win-64
https://repo.anaconda.com/pkgs/pro/noarch
https://repo.anaconda.com/pkgs/msys2/win-64
https://repo.anaconda.com/pkgs/msys2/noarch
https://conda.anaconda.org/conda-forge/win-64
https://conda.anaconda.org/conda-forge/noarch
package cache : C:\Users\myhome\Miniconda3_64-4.5.4\pkgs
C:\Users\myhome\AppData\Local\conda\conda\pkgs
envs directories : C:\Users\myhome\Miniconda3_64-4.5.4\envs
C:\Users\myhome\AppData\Local\conda\conda\envs
C:\Users\myhome\.conda\envs
platform : win-64
user-agent : conda/4.5.4 requests/2.18.4 CPython/3.6.5 Windows/10 Windows/10.0.17763
administrator : False
netrc file : None
offline mode : False
(myenv) C:\Users\myhome\PyTools\bin>conda build <module to install>
...
set PREFIX=C:\Users\myhome\Miniconda3_64-4.5.4\conda-bld\swaggerpy_1568484873987\_test_env
set SRC_DIR=C:\Users\myhome\Miniconda3_64-4.5.4\conda-bld\swaggerpy_1568484873987\test_tmp
(myenv) %SRC_DIR%>call "%SRC_DIR%\conda_test_env_vars.bat"
(myenv) %SRC_DIR%>call "C:\Users\myhome\Miniconda3_64-4.5.4\Scripts\activate.bat" "%PREFIX%"
(%PREFIX%) %SRC_DIR%>IF 0 NEQ 0 exit 1
(%PREFIX%) %SRC_DIR%>IF 0 NEQ 0 exit 1
(%PREFIX%) %SRC_DIR%>"%PREFIX%\python.exe" -s "%SRC_DIR%\run_test.py"
Traceback (most recent call last):
import: 'swaggerpy'
File "C:\Users\myhome\Miniconda3_64-4.5.4\conda-bld\swaggerpy_1568484873987\test_tmp\run_test.py", line 2, in <module>
import swaggerpy
File "C:\Users\myhome\Miniconda3_64-4.5.4\conda-bld\swaggerpy_1568484873987\_test_env\lib\site-packages\swaggerpy\__init__.py", line 13, in <module>
from .swagger_model import load_file, load_json, load_url, Loader
File "C:\Users\myhome\Miniconda3_64-4.5.4\conda-bld\swaggerpy_1568484873987\_test_env\lib\site-packages\swaggerpy\swagger_model.py", line 15, in <module>
from swaggerpy.http_client import SynchronousHttpClient
File "C:\Users\myhome\Miniconda3_64-4.5.4\conda-bld\swaggerpy_1568484873987\_test_env\lib\site-packages\swaggerpy\http_client.py", line 11, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
(%PREFIX%) %SRC_DIR%>IF 1 NEQ 0 exit 1
Tests failed for swaggerpy-0.2.1-py36_0.tar.bz2 - moving package to C:\Users\myhome\Miniconda3_64-4.5.4\conda-bld\broken
WARNING:conda_build.build:Tests failed for swaggerpy-0.2.1-py36_0.tar.bz2 - moving package to C:\Users\myhome\Miniconda3_64-4.5.4\conda-bld\broken
TESTS FAILED: swaggerpy-0.2.1-py36_0.tar.bz2
(myenv) C:\Users\myhome\PyTools\bin>conda list
# packages in environment at C:\Users\myhome\Miniconda3_64-4.5.4\envs\myenv:
#
# Name Version Build Channel
...
requests 2.22.0 py36_0 anaconda
...
</code></pre>
| 3 | 2,560 |
Plotting polygons from SQL type geo column in Python
|
<p>I have an Sqlite database with a table that includes a geo column. When I add this table into QGIS as a layer, it shows a map of Chicago with polygons as shown below. I think, the polygon points are stored in the column named geo.</p>
<p><a href="https://i.stack.imgur.com/ZZvh2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZZvh2.png" alt="enter image description here" /></a></p>
<p>I am trying to plot the same in Python to be able to add more things on top of this layout using Matplotlib. To begin with, I could load the table named "Zone" in Python using the following (that I wrote):</p>
<pre><code>import sqlite3 # Package for SQLite
### BEGIN DEFINING A READER FUNCTION ###
def Conditional_Sqdb_reader(Sqdb,Tablename,Columns,Condition):
conn = sqlite3.connect(Sqdb) # Connects the file to Python
print("\nConnected to %s.\n"%(Sqdb))
conn.execute('pragma foreign_keys = off') # Allows making changes into the SQLite file
print("SQLite Foreign_keys are unlocked...\n")
c = conn.cursor() # Assigns c as the cursor
print("Importing columns: %s \nin table %s from %s.\n"%(Columns,Tablename,Sqdb))
c.execute('''SELECT {columns}
FROM {table}
{condition}'''.format(table=Tablename,
columns=Columns,
condition=Condition)) # Selects the table to read/fetch
Sql_headers = [description[0] for description in c.description]
Sql_columns = c.fetchall() # Reads the table and saves into the memory as Sql_rows
print("Importing completed...\n")
conn.commit() # Commits all the changes made
conn.execute('pragma foreign_keys = on') # Locks the SQLite file
print("SQLite Foreign_keys are locked...\n")
conn.close() # Closes the SQLite file
print("Disconnected from %s.\n"%(Sqdb))
return Sql_headers,Sql_columns
### END DEFINING A READER FUNCTION ###
Sqdb = '/mypath/myfile.sqlite'
Tablename = "Zone" # Change this with your desired table to play with
Columns = """*""" # Changes this with your desired columns to import
Condition = '' # Add your condition and leave blank if no condition
headings,data = Conditional_Sqdb_reader(Sqdb,Tablename,Columns,Condition)
</code></pre>
<p>The data on the table is stored in "data" as a list. So, <code>data[0][-1]</code> yields the geo of the polygon of the first row, which looks something like: <code>b'\x00\x01$i\x00\x00@\xd9\x94\x8b\xd6<\x1bAb\xda7\xb6]\xb1QA\xf0\xf7\x8b\x19UC\x1bA\x9c\xde\xc5\r\xc3\xb1QA|\x03\x00\x00\x00\x01\x00\x00\x00\x06\x00\x00\x00Hlw\xef-C\x1bA\x9c\xde\xc5\r\xc3\xb1QA\xf0\xf7\x8b\x19UC\x1bAv\xc0u)^\xb1QA\xbcw\xd4\x88\xf1<\x1bAb\xda7\xb6]\xb1QA\xa5\xdc}n\xd7<\x1bA\x84.\xe1r\xbe\xb1QA@\xd9\x94\x8b\xd6<\x1bA\xce\x8eT\xef\xc1\xb1QAHlw\xef-C\x1bA\x9c\xde\xc5\r\xc3\xb1QA\xfe'</code> I do not know how to decode this and convert to a meaningful series of points, but that is what it is and QGIS apparently can do it with no hassle. How can I plot all these polygons in Python while being able to add other things within the Matplotlib world later on?</p>
| 3 | 1,381 |
Insert a dict into a sql table
|
<p>i wanted to insert some data into my sql but having trouble because there is alot of columns so i would have to write alot of parameters after VALUE. I have a table with all attributes from the json file and a player_id which i add myself</p>
<pre><code>#Gamelogs for players and Teams
import requests
import json
import psycopg2
# Connect to your postgres DB
conn = psycopg2.connect("dbname=NBA user=postgres password=********")
# Open a cursor to perform database operations
cur = conn.cursor()
cur.execute('CREATE TABLE player_logs("player_id" int,"GameId" int,"Date" int,"Team" VARCHAR(10),"Opponent" VARCHAR(10),"Minutes" int,"Arc3Assists" int,"Arc3FGA" int,"Arc3Frequency" int,"AssistPoints" int,"Assists" int,"AtRimAssists" int,"AtRimFG3AFrequency" int,"Avg2ptShotDistance" int,"Avg3ptShotDistance" int,"BadPassOutOfBoundsTurnovers" int,"BadPassSteals" int,"BadPassTurnovers" int,"Corner3FGA" int,"Corner3Frequency" int,"DeadBallTurnovers" int,"DefArc3ReboundPct" int,"DefFGReboundPct" int,"DefPoss" int,"DefRebounds" int,"DefThreePtReboundPct" int,"DefThreePtRebounds" int,"EfgPct" int,"FG2A" int,"FG2M" int,"FG3A" int,"FG3APct" int,"FTA" int,"Fg2Pct" int,"FirstChancePoints" int,"Fouls" int,"FoulsDrawn" int,"FtPoints" int,"LiveBallTurnoverPct" int,"LiveBallTurnovers" int,"LongMidRangeAccuracy" int,"LongMidRangeAssists" int,"LongMidRangeFGA" int,"LongMidRangeFGM" int,"LongMidRangeFrequency" int,"Loose Ball Fouls" int,"LostBallTurnovers" int,"NonHeaveArc3FGA" int,"OffFGReboundPct" int,"OffPoss" int,"OffRebounds" int,"OffShortMidRangeReboundPct" int,"OffTwoPtReboundPct" int,"OffTwoPtRebounds" int,"OnDefRtg" int,"OnOffRtg" int,"PenaltyArc3FGA" int,"PenaltyArc3Frequency" int,"PenaltyDefPoss" int,"PenaltyEfgPct" int,"PenaltyFG2A" int,"PenaltyFG2M" int,"PenaltyFG3A" int,"PenaltyFg2Pct" int,"PenaltyOffPoss" int,"PenaltyOffPossExcludingTakeFouls" int,"PenaltyOffPossPct" int,"PenaltyPoints" int,"PenaltyPointsExcludingTakeFouls" int,"PenaltyPointsPct" int,"PenaltyShotQualityAvg" int,"PenaltyTsPct" int,"PenaltyTurnovers" int,"Period2Fouls2Minutes" int,"Period3Fouls3Minutes" int,"PlusMinus" int,"Points" int,"PtsUnassisted2s" int,"Rebounds" int,"SecondChanceOffPoss" int,"SelfOReb" int,"SelfORebPct" int,"ShootingFouls" int,"ShootingFoulsDrawnPct" int,"ShortMidRangeAccuracy" int,"ShortMidRangeAssists" int,"ShortMidRangeFGA" int,"ShortMidRangeFGM" int,"ShortMidRangeFrequency" int,"ShortMidRangeOffReboundedPct" int,"ShotQualityAvg" int,"Steals" int,"ThreePtAssists" int,"TotalPoss" int,"TsPct" int,"Turnovers" int,"TwoPtAssists" int,"TwoPtShootingFoulsDrawn" int,"TwoPtShootingFoulsDrawnPct" int,"UnblockedLongMidRangeAccuracy" int,"UnblockedShortMidRangeAccuracy" int,"Usage" int,"Arc3Accuracy" int,"Arc3FGM" int,"Arc3PctAssisted" int,"Assisted2sPct" int,"Assisted3sPct" int,"AtRimAccuracy" int,"AtRimFGA" int,"AtRimFGM" int,"AtRimFrequency" int,"AtRimOffReboundedPct" int,"AtRimPctBlocked" int,"Blocked2s" int,"BlockedShortMidRange" int,"Blocks" int,"BlocksRecoveredPct" int,"Corner3Assists" int,"DefAtRimReboundPct" int,"DefLongMidRangeReboundPct" int,"DefShortMidRangeReboundPct" int,"DefTwoPtReboundPct" int,"DefTwoPtRebounds" int,"FG2APctBlocked" int,"FG3M" int,"Fg2aBlocked" int,"Fg3Pct" int,"LongMidRangeOffReboundedPct" int,"LostBallSteals" int,"NonHeaveArc3Accuracy" int,"NonHeaveArc3FGM" int,"NonHeaveFg3Pct" int,"NonPutbacksAssisted2sPct" int,"NonShootingFoulsDrawn" int,"NonShootingPenaltyNonTakeFoulsDrawn" int,"OffLongMidRangeReboundPct" int,"Offensive Fouls Drawn" int,"PenaltyArc3Accuracy" int,"PenaltyArc3FGM" int,"PenaltyAtRimAccuracy" int,"PenaltyAtRimFGA" int,"PenaltyAtRimFGM" int,"PenaltyAtRimFrequency" int,"PenaltyFG3M" int,"PenaltyFg3Pct" int,"PenaltyFtPoints" int,"PtsAssisted2s" int,"PtsAssisted3s" int,"PtsPutbacks" int,"PtsUnassisted3s" int,"RecoveredBlocks" int,"SecondChanceArc3FGA" int,"SecondChanceArc3Frequency" int,"SecondChanceEfgPct" int,"SecondChanceFG2A" int,"SecondChanceFG2M" int,"SecondChanceFG3A" int,"SecondChanceFg2Pct" int,"SecondChancePoints" int,"SecondChancePointsPct" int,"SecondChanceShotQualityAvg" int,"SecondChanceTsPct" int,"ShortMidRangePctAssisted" int,"ShortMidRangePctBlocked" int,"ThreePtShootingFoulsDrawn" int,"ThreePtShootingFoulsDrawnPct" int,"UnblockedArc3Accuracy" int,"UnblockedAtRimAccuracy" int,"OffArc3ReboundPct" int,"OffThreePtReboundPct" int,"OffThreePtRebounds" int,"Offensive Fouls" int,"Corner3Accuracy" int,"Corner3FGM" int,"ThreePtOffReboundedPct" int,"UnblockedCorner3Accuracy" int,"DefFTReboundPct" int,"FTDefRebounds" int,"Technical Free Throw Trips" int,"BlockedAtRim" int,"LostBallOutOfBoundsTurnovers" int,"OffAtRimReboundPct" int,"BlockedLongMidRange" int,"Charge Fouls Drawn" int,"LongMidRangePctAssisted" int,"NonShootingPenaltyNonTakeFouls" int,"SecondChanceTurnovers" int,"Travels" int,"SecondChanceAtRimFGA" int,"SecondChanceAtRimFrequency" int,"Clear Path Fouls" int,"DefCorner3ReboundPct" int,"HeaveAttempts" int,"LongMidRangePctBlocked" int,"2pt And 1 Free Throw Trips" int,"AtRimPctAssisted" int,"Period3Fouls4Minutes" int,"Period4Fouls4Minutes" int,"Charge Fouls" int,"Loose Ball Fouls Drawn" int,"PeriodOTFouls4Minutes" int,"SecondChanceAtRimAccuracy" int,"SecondChanceAtRimFGM" int,"PenaltyCorner3FGA" int,"PenaltyCorner3Frequency" int,"Corner3PctAssisted" int,"SecondChanceFtPoints" int,"OffCorner3ReboundPct" int,"SecondChanceArc3Accuracy" int,"SecondChanceArc3FGM" int,"SecondChanceFG3M" int,"SecondChanceFg3Pct" int,"3pt And 1 Free Throw Trips" int,"Defensive 3 Seconds Violations" int,"Period4Fouls5Minutes" int,"StepOutOfBoundsTurnovers" int,"Period1Fouls2Minutes"int)')
x = 'https://api.pbpstats.com/get-all-players-for-league/nba'
headers = {'user-agent': 'Chrome/88.0.4324.190'}
jsonData1 = requests.get(x, headers=headers).json() # Player id and name
EntityId = json.loads(json.dumps(jsonData1)[12:-1])
SeasonType = {'R':'Regular+Season','P':'Playoff+Season','A':'All'}
EntityType = {'P':'Player','T':'Team'}
Season = {
'2008-09',
'2009-10',
'2010-11',
'2011-12',
'2012-13',
'2013-14',
'2014-15',
'2015-16',
'2016-17',
'2017-18',
'2018-19',
'2019-20',
'2020-21'
}
def log (S:Season,ST:SeasonType,EI:EntityId,ET:EntityType):
url = 'https://api.pbpstats.com/get-game-logs/nba'
payload = {
'Season': S,
'SeasonType': ST,
'EntityId': EI,
'EntityType': ET
}
r = requests.get(url, headers=headers, params=payload).json()
if r == {'error': 'no results'} :
return()
else :
for c in r['multi_row_table_data']:
j = {'Player_id':EI}
c.update(j)
cur.execute('INSERT INTO player_log (Player_id,GameId,Date,Team,Opponent,Minutes,Arc3Assists,Arc3FGA,Arc3Frequency,AssistPoints,Assists,AtRimAssists,AtRimFG3AFrequency,Avg2ptShotDistance,Avg3ptShotDistance,BadPassOutOfBoundsTurnovers,BadPassSteals,BadPassTurnovers,Corner3FGA,Corner3Frequency,DeadBallTurnovers,DefArc3ReboundPct,DefFGReboundPct,DefPoss,DefRebounds,DefThreePtReboundPct,DefThreePtRebounds,EfgPct,FG2A,FG2M,FG3A,FG3APct,FTA,Fg2Pct,FirstChancePoints,Fouls,FoulsDrawn,FtPoints,LiveBallTurnoverPct,LiveBallTurnovers,LongMidRangeAccuracy,LongMidRangeAssists,LongMidRangeFGA,LongMidRangeFGM,LongMidRangeFrequency,Loose_Ball_Fouls,LostBallTurnovers,NonHeaveArc3FGA,OffFGReboundPct,OffPoss,OffRebounds,OffShortMidRangeReboundPct,OffTwoPtReboundPct,OffTwoPtRebounds,OnDefRtg,OnOffRtg,PenaltyArc3FGA,PenaltyArc3Frequency,PenaltyDefPoss,PenaltyEfgPct,PenaltyFG2A,PenaltyFG2M,PenaltyFG3A,PenaltyFg2Pct,PenaltyOffPoss,PenaltyOffPossExcludingTakeFouls,PenaltyOffPossPct,PenaltyPoints,PenaltyPointsExcludingTakeFouls,PenaltyPointsPct,PenaltyShotQualityAvg,PenaltyTsPct,PenaltyTurnovers,Period2Fouls2Minutes,Period3Fouls3Minutes,PlusMinus,Points,PtsUnassisted2s,Rebounds,SecondChanceOffPoss,SelfOReb,SelfORebPct,ShootingFouls,ShootingFoulsDrawnPct,ShortMidRangeAccuracy,ShortMidRangeAssists,ShortMidRangeFGA,ShortMidRangeFGM,ShortMidRangeFrequency,ShortMidRangeOffReboundedPct,ShotQualityAvg,Steals,ThreePtAssists,TotalPoss,TsPct,Turnovers,TwoPtAssists,TwoPtShootingFoulsDrawn,TwoPtShootingFoulsDrawnPct,UnblockedLongMidRangeAccuracy,UnblockedShortMidRangeAccuracy,Usage,Arc3Accuracy,Arc3FGM,Arc3PctAssisted,Assisted2sPct,Assisted3sPct,AtRimAccuracy,AtRimFGA,AtRimFGM,AtRimFrequency,AtRimOffReboundedPct,AtRimPctBlocked,Blocked2s,BlockedShortMidRange,Blocks,BlocksRecoveredPct,Corner3Assists,DefAtRimReboundPct,DefLongMidRangeReboundPct,DefShortMidRangeReboundPct,DefTwoPtReboundPct,DefTwoPtRebounds,FG2APctBlocked,FG3M,Fg2aBlocked,Fg3Pct,LongMidRangeOffReboundedPct,LostBallSteals,NonHeaveArc3Accuracy,NonHeaveArc3FGM,NonHeaveFg3Pct,NonPutbacksAssisted2sPct,NonShootingFoulsDrawn,NonShootingPenaltyNonTakeFoulsDrawn,OffLongMidRangeReboundPct,Offensive_Fouls_Drawn,PenaltyArc3Accuracy,PenaltyArc3FGM,PenaltyAtRimAccuracy,PenaltyAtRimFGA,PenaltyAtRimFGM,PenaltyAtRimFrequency,PenaltyFG3M,PenaltyFg3Pct,PenaltyFtPoints,PtsAssisted2s,PtsAssisted3s,PtsPutbacks,PtsUnassisted3s,RecoveredBlocks,SecondChanceArc3FGA,SecondChanceArc3Frequency,SecondChanceEfgPct,SecondChanceFG2A,SecondChanceFG2M,SecondChanceFG3A,SecondChanceFg2Pct,SecondChancePoints,SecondChancePointsPct,SecondChanceShotQualityAvg,SecondChanceTsPct,ShortMidRangePctAssisted,ShortMidRangePctBlocked,ThreePtShootingFoulsDrawn,ThreePtShootingFoulsDrawnPct,UnblockedArc3Accuracy,UnblockedAtRimAccuracy,OffArc3ReboundPct,OffThreePtReboundPct,OffThreePtRebounds,Offensive_Fouls,Corner3Accuracy,Corner3FGM,ThreePtOffReboundedPct,UnblockedCorner3Accuracy,DefFTReboundPct,FTDefRebounds,Technical_Free_Throw_Trips,BlockedAtRim,LostBallOutOfBoundsTurnovers,OffAtRimReboundPct,BlockedLongMidRange,Charge_Fouls_Drawn,LongMidRangePctAssisted,NonShootingPenaltyNonTakeFouls,SecondChanceTurnovers,Travels,SecondChanceAtRimFGA,SecondChanceAtRimFrequency,Clear_Path_Fouls,DefCorner3ReboundPct,HeaveAttempts,LongMidRangePctBlocked,"2pt_And_1_Free_Throw_Trips",AtRimPctAssisted,Period3Fouls4Minutes,Period4Fouls4Minutes,Charge_Fouls,Loose_Ball_Fouls_Drawn,PeriodOTFouls4Minutes,SecondChanceAtRimAccuracy,SecondChanceAtRimFGM,PenaltyCorner3FGA,PenaltyCorner3Frequency,Corner3PctAssisted,SecondChanceFtPoints,OffCorner3ReboundPct,SecondChanceArc3Accuracy,SecondChanceArc3FGM,SecondChanceFG3M,SecondChanceFg3Pct,"3pt_And_1_Free_Throw_Trips",Defensive_3_Seconds_Violations,Period4Fouls5Minutes,StepOutOfBoundsTurnovers,Period1Fouls2Minutes) VALUES',
c)
return()
y=log('2020-21','Regular+Season','101108','Player')
conn.commit()
conn.close()
cur.close()
</code></pre>
<p>So was wondering if i could insert the data so it matched with the key and the column name. So the table and dict isnt order the same way either if it makes a difference.</p>
| 3 | 5,824 |
I have 10 buttons that I want when I press a button, a function occurs
|
<p>I have a page with 10 buttons I want when I press a button the speech inside it changes
And div appears, and when you click the second time, everything returns as it was</p>
<p>button 10 html</p>
<pre><code><button class="button" id="movetool">click 1</button>
<button class="button" id="movetool2">click 2</button>
<button class="button" id="movetool3">click 3</button>
<button class="button" id="movetool4">click 4</button>
<button class="button" id="movetool5">click 5</button>
<button class="button" id="movetool6">click 6</button>
<button class="button" id="movetool7">click 7</button>
<button class="button" id="movetool8">click 8</button>
<button class="button" id="movetool9">click 9</button>
<button class="button" id="movetool0">click 10</button>
</code></pre>
<p>button javacsript</p>
<pre><code>var activeButton = localStorage.getItem('activeButton');
var isActive = localStorage.getItem('isActive');
const allButtons = document.querySelectorAll(".button");
[...allButtons].forEach(function(thisButton) {
if (isActive === 'true') {
if (activeButton !== thisButton.id) {
thisButton.disabled = true;
}
}
});
const movetool = event => {
activeButton = localStorage.getItem('activeButton');
const target = event.target.closest("button");
if (activeButton === target.id) {
var enableAll = false;
Array.from(allButtons).forEach(function(thisButton) {
if (thisButton.disabled) {
enableAll = true;
return;
}
});
if (enableAll) {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = false;
});
localStorage.setItem('isActive', false);
} else {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = true;
});
if (target.classList.contains("button")) {
target.disabled = false;
localStorage.setItem('isActive', true);
localStorage.setItem('activeButton', target.id);
}
}
} else {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = true;
});
if (target.classList.contains("button")) {
target.disabled = false;
localStorage.setItem('isActive', true);
localStorage.setItem('activeButton', target.id);
}
}
}
document.querySelector('.button_container').addEventListener('click', movetool);
</code></pre>
<p>I want to change the text when I press the button to "clicked"
and show div</p>
<p>code</p>
the button is clicked
| 3 | 1,189 |
ReactJS issue with map and find
|
<p>so i have an array of this type,</p>
<pre><code> (5) [{…}, {…}, {…}, {…}, {…}]
0: {naam: "Tafel 1 ", id: 1, aantalPersonen: 3, aantalMinuten: 3, bezet: 1, …}
1: {naam: "Tafel 2 ", id: 2, aantalPersonen: 1, aantalMinuten: 3, bezet: 1, …}
2: {naam: "Tafel 3 ", id: 3, aantalPersonen: 2, aantalMinuten: 6, bezet: 1, …}
3: {naam: "Tafel 4", id: 4, aantalPersonen: 0, bezet: 0, tafelLayout: {…}}
4: {naam: "Tafel 5", id: 5, bezet: 0, aantalPersonen: 0, tafelLayout: {…}}
length: 5
__proto__: Array(0)
</code></pre>
<p>i can map it to a component which then renders them all in divs and that works perfectly. Now what i want to do is render just a specific one.</p>
<pre><code>this.state.tafels.find(tafel =>(tafel.id = 1))
</code></pre>
<p>finds for example the one i want to use</p>
<p>it has to be mapped to a component using props </p>
<pre><code> <PlattegrondResto
tafelNr={tafel.id}
tafelNaam = {tafel.naam}
tafelLayout={tafel.tafelLayout}
tafelaantalPersonen={tafel.aantalPersonen}
tafelMinuten = {tafel.aantalMinuten}
tafelBezet = {tafel.bezet}
tafelSelect={(tafelNr) => this.tafelSelect(tafelNr)}
tafelTijdInterval = {this.state.tijdInterval}
/>
</code></pre>
<p>is there any way i can do that effectively ?
i tried everything i can think of so far</p>
<p>to map them all i use </p>
<pre><code> {this.state.tafels.map((tafel) =>
<PlattegrondResto
tafelNr={tafel.id}
tafelNaam = {tafel.naam}
tafelLayout={tafel.tafelLayout}
tafelaantalPersonen={tafel.aantalPersonen}
tafelMinuten = {tafel.aantalMinuten}
tafelBezet = {tafel.bezet}
tafelSelect={(tafelNr) => this.tafelSelect(tafelNr)}
tafelTijdInterval = {this.state.tijdInterval}
/>
)}
</code></pre>
<p>so i want to know is there a way to first use find and then map it to the component that is shown below</p>
<p>Thanks in advance</p>
| 3 | 1,290 |
setup.py ignores full path dependencies, instead looks for "best match" in pypi
|
<p><em>Similar to <a href="https://stackoverflow.com/questions/12518499/pip-ignores-dependency-links-in-setup-py_">https://stackoverflow.com/questions/12518499/pip-ignores-dependency-links-in-setup-py</em></a></p>
<p>I'm modifying <a href="https://github.com/joke2k/faker" rel="nofollow noreferrer">faker</a> in anticipation to an open PR I have open with <a href="https://github.com/kvesteri/validators" rel="nofollow noreferrer">validators</a>, and I want to be able to test the new dependency i will have.</p>
<pre><code>setup(
name='Faker',
...
install_requires=[
"python-dateutil>=2.4",
"six>=1.10",
"text-unidecode==1.2",
],
tests_require=[
"validators@https://github.com/kingbuzzman/validators/archive/0.13.0.tar.gz#egg=validators-0.13.0", # TODO: this will change # noqa
"ukpostcodeparser>=1.1.1",
...
],
...
)
</code></pre>
<p><code>python setup.py test</code> refuses to install the 0.13.0 version.</p>
<p>If I move the trouble line up to <code>install_requires=[..]</code> (which SHOULD not be there)</p>
<pre><code>setup(
name='Faker',
...
install_requires=[
"python-dateutil>=2.4",
"six>=1.10",
"text-unidecode==1.2",
"validators@https://github.com/kingbuzzman/validators/archive/0.13.0.tar.gz#egg=validators-0.13.0", # TODO: this will change # noqa
],
tests_require=[
"ukpostcodeparser>=1.1.1",
...
],
...
)
</code></pre>
<ul>
<li>using <code>pip install -e .</code> everything works great -- the correct version gets installed.</li>
<li>using <code>python setup.py develop</code> same issue.</li>
</ul>
<p>My guess is setuptools/distutils doing something weird -- <code>pip</code> seems to address the issue. My question: how do I fix this?</p>
<p>Problematic code and references can be found here: </p>
<ul>
<li><a href="https://github.com/kingbuzzman/faker/commit/20f69082714fae2a60d356f4c63a061ce99a975e#diff-2eeaed663bd0d25b7e608891384b7298R72" rel="nofollow noreferrer">https://github.com/kingbuzzman/faker/commit/20f69082714fae2a60d356f4c63a061ce99a975e#diff-2eeaed663bd0d25b7e608891384b7298R72</a></li>
<li><a href="https://github.com/kingbuzzman/faker" rel="nofollow noreferrer">https://github.com/kingbuzzman/faker</a></li>
<li><a href="https://gist.github.com/kingbuzzman/e3f39ba217e2c14a9065fb14a502b63d" rel="nofollow noreferrer">https://gist.github.com/kingbuzzman/e3f39ba217e2c14a9065fb14a502b63d</a></li>
<li><a href="https://github.com/pypa/setuptools/issues/1758" rel="nofollow noreferrer">https://github.com/pypa/setuptools/issues/1758</a></li>
</ul>
<p>Easiest way to see the issue at hand:</p>
<pre><code>docker run -it --rm python:3.7 bash -c "git clone https://github.com/kingbuzzman/faker.git; cd faker; pip install -e .; python setup.py test"
</code></pre>
<p><em>UPDATE: Since this has been fixed, the issue wont be replicated anymore -- all tests will pass</em></p>
| 3 | 1,285 |
Hover box position issue
|
<p>I have a great(for me) problem</p>
<p>I'm building a website, trying to make a category top bar with a box showing downside of text on hover.</p>
<p>But when I hover on the category name, appearing box makes the categories go down.</p>
<p>How to make them stay up, and just make box going down overlapping content?</p>
<p>I have the following code: <a href="https://jsfiddle.net/oqshbxge/" rel="nofollow noreferrer">https://jsfiddle.net/oqshbxge/</a></p>
<pre><code> <div id="categories">
<div class="top-category"> <a class="top-category-link noka uppercase" href="http://mode-m.pl/kategoria/syntezatory-modularne">Syntezatory Modularne</a>
<div class="hover-box-outline">
<a class="hover-box-category-top noka uppercase" href="http://mode-m.pl/kategoria/syntezatory-modularne">Syntezatory Modularne</a>
</div>
</div>
<div class="divider-15"></div>
<div class="top-category"> <a class="top-category-link noka uppercase" href="http://mode-m.pl/kategoria/automaty-perkusyjne">Automaty perkusyjne</a>
<div class="hover-box-outline">
<a class="hover-box-category-top noka uppercase" href="http://mode-m.pl/kategoria/automaty-perkusyjne">Automaty perkusyjne</a>
<br><br><br><br>
</div>
</div>
<div class="divider-15"></div>
<div class="top-category"> <a class="top-category-link noka uppercase" href="http://mode-m.pl/kategoria/sprzet-studyjny">Sprzęt Studyjny</a>
<div class="hover-box-outline">
<a class="hover-box-category-top noka uppercase" href="http://mode-m.pl/kategoria/sprzet-studyjny">Sprzęt Studyjny</a>
</div>
</div>
<div class="divider-15"></div>
<div class="top-category"> <a class="top-category-link noka uppercase" href="http://mode-m.pl/kategoria/syntezatory">Syntezatory</a>
<div class="hover-box-outline">
<a class="hover-box-category-top noka uppercase" href="http://mode-m.pl/kategoria/syntezatory">Syntezatory</a>
</div>
</div>
<div class="divider-15"></div>
<div class="top-category"> <a class="top-category-link noka uppercase" href="http://mode-m.pl/kategoria/sekwencery">Sekwencery</a>
<div class="hover-box-outline">
<a class="hover-box-category-top noka uppercase" href="http://mode-m.pl/kategoria/sekwencery">Sekwencery</a>
</div>
</div>
<div class="divider-15"></div>
<div class="top-category"> <a class="top-category-link noka uppercase" href="http://mode-m.pl/kategoria/kable">Kable</a>
<div class="hover-box-outline">
<a class="hover-box-category-top noka uppercase" href="http://mode-m.pl/kategoria/kable">Kable</a>
</div>
</div>
<div class="divider-15"></div>
<div class="top-category"> <a class="top-category-link noka uppercase" href="http://mode-m.pl/kategoria/sprzet-gitarowy">Sprzęt Gitarowy</a>
<div class="hover-box-outline">
<a class="hover-box-category-top noka uppercase" href="http://mode-m.pl/kategoria/sprzet-gitarowy">Sprzęt Gitarowy</a>
</div>
</div> </div>
</code></pre>
<p>with css:</p>
<pre><code> .top-category {
display: inline-block;
}
.top-category-link {
color: #1a1a1a;
font-size: 10pt;
transition: text-shadow 0.5s, color 0.5s, font-size 0.5s;
}
.top-category:hover > a{
color: white;
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
font-size: 15pt;
}
.top-category:hover > .hover-box-outline {
display: block;
}
.hover-box-outline {
border: 1px solid;
background-color: rgba(255,255,255,0.75);
width: auto;
display: none;
margin-top: 25px;
}
.hover-box-category-top {
color: #1a1a1a;
}
.divider-15{
width: 15px;
display: inline-block;
}
</code></pre>
| 3 | 1,997 |
Debug Test in vscode fails inside container
|
<h2>Configuration:</h2>
<p>I am using the following version of VSCode:</p>
<pre><code>Version: 1.46.1
Commit: cd9ea6488829f560dc949a8b2fb789f3cdc05f5d
Date: 2020-06-17T21:13:08.304Z
Electron: 7.3.1
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Linux x64 5.3.0-59-generic snap
</code></pre>
<p>With the Python Extension <code>ms-python.python</code> version <code>v2020.6.8</code>. The only PIPs installed are:</p>
<pre><code>Package Version
----------------- -------
astroid 2.4.2
attrs 19.3.0
autopep8 1.5.3
isort 4.3.21
lazy-object-proxy 1.4.3
mccabe 0.6.1
more-itertools 8.4.0
packaging 20.4
pip 20.1.1
pluggy 0.13.1
py 1.8.2
pycodestyle 2.6.0
pylint 2.5.3
pyparsing 2.4.7
pytest 5.4.3
setuptools 47.1.1
six 1.15.0
toml 0.10.1
wcwidth 0.2.4
wheel 0.34.2
wrapt 1.12.1
</code></pre>
<h2>Problem:</h2>
<p>I am trying to debug my python tests in vscode and i get the following error in the debug console:</p>
<pre><code>============================= test session starts ==============================
platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.2, pluggy-0.13.1
rootdir: /workspaces/test_python_debugging
collected 0 items / 1 error
==================================== ERRORS ====================================
_________________ ERROR collecting tst/dummy/test_unit_math.py _________________
ImportError while importing test module '/workspaces/test_python_debugging/tst/dummy/test_unit_math.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tst/dummy/test_unit_math.py:5: in <module>
from dummy.math import add
E ModuleNotFoundError: No module named 'dummy'
--------------- generated xml file: /tmp/tmp-188wLObs4r6II9x.xml ---------------
=========================== short test summary info ============================
ERROR tst/dummy/test_unit_math.py
=============================== 1 error in 0.19s ===============================
ERROR: not found: /workspaces/test_python_debugging/tst/dummy/test_unit_math.py::test_addition
(no name '/workspaces/test_python_debugging/tst/dummy/test_unit_math.py::test_addition' in any of [<Module tst/dummy/test_unit_math.py>])
</code></pre>
<p>The tests themselves run fine in the terminal. In other terms there is no issue with not being able to find the "missing" module. Example:</p>
<pre><code>0f617e2a72ee [/workspaces/test_python_debugging]$ python -m pytest tst/**/te
st*.py -k test_addition
=========================== test session starts ============================
platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.2, pluggy-0.13.1
rootdir: /workspaces/test_python_debugging
collected 1 item
tst/dummy/test_unit_math.py . [100%]
============================ 1 passed in 0.01s =============================
0f617e2a72ee [/workspaces/test_python_debugging]$
</code></pre>
<p>The way I am launching the debugger is by clicking on the <code>Debug Test</code> link for the given test. Example:</p>
<p><a href="https://i.stack.imgur.com/0Q9TM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Q9TM.png" alt="Launching debugger on test" /></a></p>
<p>Below is the <code>.devcontainer.json</code> configuration being used:</p>
<pre><code>{
"image": "test_python_debugging",
"extensions": [
"ms-python.python"
],
"mounts": [
"source=${localWorkspaceFolder},target=/app,type=bind,consistency=cached"
],
"settings": {
"terminal.integrated.shell.linux": "/bin/ash",
"terminal.integrated.shellArgs.linux": [
"-l"
],
"python.testing.pytestArgs": [
"tst",
"-k test_unit"
],
"python.testing.unittestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.pytestEnabled": true,
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.pythonPath": "/usr/local/bin/python"
},
"containerUser": "app",
"containerEnv": {
"PYTHONPATH": "/app/src"
}
}
</code></pre>
<p>Would someone know what I am missing in terms of configurations?</p>
| 3 | 1,996 |
use a custom function to find all words in a column
|
<p><strong>Background</strong></p>
<p>The following question is a variation from <a href="https://stackoverflow.com/questions/56826420/unnest-grab-keywords-nextwords-beforewords-function">Unnest grab keywords/nextwords/beforewords function</a>. </p>
<p><strong>1)</strong> I have the following <code>word_list</code></p>
<pre><code>word_list = ['crayons', 'cars', 'camels']
</code></pre>
<p><strong>2)</strong> And <code>df1</code></p>
<pre><code>l = ['there are many crayons, in the blue box crayons that are',
'cars! i like a lot of sports cars because they go fast',
'the camels, in the middle east have many camels to ride ']
df1 = pd.DataFrame(l, columns=['Text'])
df1
Text
0 there are many crayons, in the blue box crayons that are
1 cars! i like a lot of sports cars because they go fast
2 the camels, in the middle east have many camels to ride
</code></pre>
<p><strong>3)</strong> I also have a function <code>find_next_words</code> which uses <code>word_list</code> to grab words from <code>Text</code> column in <code>df1</code></p>
<pre><code>def find_next_words(row, word_list):
sentence = row[0]
trigger_words = []
next_words = []
for keyword in word_list:
words = sentence.split()
for index in range(0, len(words) - 1):
if words[index] == keyword:
trigger_words.append(keyword)
next_words.append(words[index + 1:index + 3])
return pd.Series([trigger_words, next_words], index = ['TriggerWords','NextWords'])
</code></pre>
<p><strong>4)</strong> And it's pieced together with the following</p>
<pre><code>df2 = df1.join(df.apply(lambda x: find_next_words(x, word_list), axis=1))
</code></pre>
<p><strong>Output</strong></p>
<pre><code> Text TriggerWords NextWords
0 [crayons] [[that, are]]
1 [cars] [[because, they]]
2 [camels] [[to, ride]]
</code></pre>
<p><strong>Problem</strong></p>
<p><strong>5)</strong> The output misses the following </p>
<p><code>crayons,</code> from row <code>0</code> of <code>Text</code> column <code>df1</code></p>
<p><code>cars!</code> from row <code>1</code> of <code>Text</code> column <code>df1</code></p>
<p><code>camels,</code> from row <code>2</code> of <code>Text</code> column <code>df1</code></p>
<p><strong>Goal</strong></p>
<p><strong>6)</strong> Grab all corresponding words from <code>df1</code> even if the words in <code>df1</code> have a slight variation e.g. <code>crayons,</code> <code>cars!</code> from the words in <code>word_list</code> </p>
<p><em>(For this toy example, I know I can easily fix this problem by just adding these word variations to <code>word_list = ['crayons,','crayons', 'cars!',</code>cars<code>, 'camels,', 'camels'].</code> But this would be impractical to do with my my real word_list, which contains ~20K words)</em></p>
<p><strong>Desired Output</strong></p>
<pre><code>Text TriggerWords NextWords
0 [crayons, crayons] [[in, the], [that, are]]
1 [cars, cars] [[i,like],[because, they]]
2 [camels, camels] [[in, the], [to, ride]]
</code></pre>
<p><strong>Questions</strong></p>
<p>How do I 1) tweak my <code>word_list</code> (e.g. regex?) 2) or <code>find_next_words</code> function to achieve my desired output?</p>
| 3 | 1,399 |
MediaWiki $wgUser to $this->getUser() and $context->getUser() not working
|
<p>I am learning Mediawiki and looking at some of the extensions.</p>
<p><a href="https://www.mediawiki.org/wiki/Manual:$wgUser" rel="nofollow noreferrer">Manual:$wgUser</a> on mediawiki.org states the global variable <code>$wgUser</code> should not be used for new code.</p>
<p><a href="https://www.mediawiki.org/wiki/Manual:RequestContext.php" rel="nofollow noreferrer">Manual:RequestContext.php</a> says the context object should be used instead, by using either <code>$this->getUser()</code> or <code>$context->getUser()</code>.</p>
<p>However, when I try to use <code>$this->getUser()->getName()</code> in the extension for Who's Online I get the following error:</p>
<pre><code>Fatal error: Using $this when not in object context in /home/ghsfhaco/public_html/wiki/extensions/WhosOnline/WhosOnlineHooks.php on line 19
</code></pre>
<p>And when I change it to <code>$context->getUser()->getName()</code> I get this error:</p>
<pre><code>Fatal error: Call to a member function getUser() on null in /home/ghsfhaco/public_html/wiki/extensions/WhosOnline/WhosOnlineHooks.php on line 19
</code></pre>
<p>The full <a href="https://www.mediawiki.org/wiki/Extension:WhosOnline" rel="nofollow noreferrer">Extension:WhosOnline</a> can be found at Mediawiki, but here's the specific page:</p>
<pre><code> class WhosOnlineHooks {
// update online data
public static function onBeforePageDisplay() {
global $wgUser;
// write to DB (use master)
$dbw = wfGetDB( DB_MASTER );
$now = gmdate( 'YmdHis', time() );
// row to insert to table
$row = array(
'userid' => $wgUser->getId(),
'username' => $wgUser->getName(),
'timestamp' => $now
);
$method = __METHOD__;
$dbw->onTransactionIdle( function() use ( $dbw, $method, $row ) {
$dbw->upsert(
'online',
$row,
array( array( 'userid', 'username' ) ),
array( 'timestamp' => $row['timestamp'] ),
$method
);
} );
return true;
}
public static function onLoadExtensionSchemaUpdates( $updater ) {
$updater->addExtensionUpdate( array( 'addTable', 'online',
__DIR__ . '/whosonline.sql', true ) );
return true;
}
}
</code></pre>
<p>How exactly should it be done?</p>
<p>BTW, I'm using Mediawiki 1.28.0.</p>
| 3 | 1,080 |
Dynamic initial form data
|
<p>I am attempting to add a button to the customer's page to add a new device but when rendering the form I would like to pass the customer's name as an initial value.</p>
<p>This was my personal Christmas project to make my work projects a bit more centralized in 2021.
Im almost over the finish line but I've hit this bump. Any help would be appreciated.
Thanks.</p>
<p>I have two models in separate apps.</p>
<pre><code>class Customer(models.Model):
nameF = models.CharField("First Name", max_length=255, blank = True, null = True)
nameL = models.CharField("Last Name", max_length=255, blank = True, null = True)
nameN = models.CharField("Nickname", max_length=255, blank = True, null = True)
address = models.CharField("Address", max_length=255, blank = True, null = True)
phone = models.CharField("Phone", max_length=255, blank = True, null = True)
email = models.EmailField("Email", max_length=254, blank = True, null = True)
dateC = models.DateTimeField("Date Created", auto_now_add=True)
dateU = models.DateTimeField("Last Updated", auto_now=True)
note = models.TextField("Notes", blank = True, null = True)
def __str__(self):
return self.nameF
def get_absolute_url(self):
return reverse ("cfull", kwargs={"pk": self.id})
</code></pre>
<p>and</p>
<pre><code>class Device(models.Model):
CONNECTION = (
('Local', 'Local'),
('IP/DOMAIN', 'IP/DOMAIN'),
('P2P', 'P2P')
)
TYPE = (
('DVR', 'DVR'),
('NVR', 'NVR'),
('Router', 'Router'),
('WLAN Controller', 'WLAN Controller'),
('AP', 'AP'),
('Doorbell', 'Doorbell'),
('Audio Controller', 'Audio Controller'),
('Other', 'Other')
)
BRAND = (
('HikVision', 'HikVision'),
('Dahua', 'Dahua'),
('Luxul', 'Luxul'),
('Trendnet', 'Trendnet'),
('Russound', 'Russound'),
('Ring', 'Ring'),
('Other', 'Other')
)
customer = models.ForeignKey('customer.Customer', null = True, on_delete=models.SET_NULL)
alias = models.CharField("Alias", max_length=255, blank = True, null = True)
dbrand = models.CharField("Brand", max_length=255, null = True, blank = True, choices=BRAND)
dtype = models.CharField("Device Type", max_length=255, null = True, blank = True, choices=TYPE)
connection = models.CharField("Remote Protocol", max_length=255, null = True, blank = True, choices=CONNECTION)
localaddr = models.CharField("Local IP", max_length=255, blank = True, null = True)
hostname = models.CharField("Hostname/IP", max_length=255, blank = True, null = True)
username = models.CharField("Username", max_length=255, blank = True, null = True)
password = models.CharField("Password", max_length=255, blank = True, null = True)
model = models.CharField("Model Number", max_length=255, blank = True, null = True)
serial = models.CharField("Serial Number", max_length=255, blank = True, null = True)
dateU = models.DateTimeField("Date Uploaded", auto_now_add=True)
note = models.TextField("Notes", blank = True, null = True)
def __str__(self):
return self.alias
def get_absolute_url(self):
return reverse ("dfull", kwargs={"pk": self.id})
</code></pre>
<p>In my project, the individual customer pages are populated with a list of each customer's devices.</p>
<pre><code>def CustomerDetailView(request, pk):
customer = Customer.objects.get(id=pk)
devices = customer.device_set.all()
context = {'object':customer, 'devices':devices}
return render(request, 'customer/cfull.html', context)
</code></pre>
<p>This is some HTML for the customer's page.</p>
<pre><code> <hr>
<div class="card-header">
<h2 class="card-title text-center">Customer Options</h2>
</div>
<div class="card card-body">
<a href="" class="btn btn-primary btn-lg btn-block">Add Device</a>
<a href="{% url 'cedit' object.id %}" class="btn btn-secondary btn-lg btn-block">Edit Customer</a>
<a href="{% url 'cdelete' object.id %}" class="btn btn-danger btn-lg btn-block">Delete Customer</a>
</div>
</code></pre>
| 3 | 1,839 |
How to normalise my data
|
<p>First post i have been lurking for many years but finally stumped enough to ask for help? Please excuse the formatting</p>
<p>I have generated a mind map (categories, subcategories, questions and responses) Im trying to find a data structure to map this. Once I map the data I end up with lots of repetition where a question and its children fit under multiple categories and subcategories. This leads me to believe my structure is poor and this can be normalised in some way which is eluding me.</p>
<p>E.g. <strong>Thinking of shopping and advertising, which of the following have you ever done?</strong> </p>
<ul>
<li>(cat_id = 1) SHOPPING & ADVERTISING (parent Category)
<ul>
<li>(cat_id = 41) Shopping information/Purchases (Sub category)
<ul>
<li>(ID- 1234) Thinking of shopping and advertising, which of the following have you ever done?
<ul>
<li>(ID- 4111) How often do you do this via your TV screen?</li>
<li>(ID- 4112) How often do you do this via your desktop computer?</li>
<li>(ID- 4113) How often do you do this via your laptop computer?</li>
</ul></li>
</ul></li>
</ul></li>
<li><p>(cat_id = 1) SHOPPING & ADVERTISING (parent Category)</p>
<ul>
<li>(cat_id = 44) No split - shopping and advertising (Sub category)
<ul>
<li>(ID- 1234) Thinking of shopping and advertising, which of the following have you ever done?
<ul>
<li>(ID- 4111) How often do you do this via your TV screen?</li>
<li>(ID- 4112) How often do you do this via your desktop computer?</li>
<li>(ID- 4113) How often do you do this via your laptop computer?</li>
</ul></li>
</ul></li>
</ul></li>
<li><p>(cat_id = 2) SCREENS & DEVICES (parent Category)</p>
<ul>
<li>(cat_id = 51)Usage/Shared usage (Sub category)
<ul>
<li>(ID- 1234) Thinking of shopping and advertising, which of the following have you ever done?
<ul>
<li>(ID- 4111) How often do you do this via your TV screen?</li>
<li>(ID- 4112) How often do you do this via your desktop computer?</li>
<li>(ID- 4113) How often do you do this via your laptop computer?</li>
</ul></li>
</ul></li>
</ul></li>
<li>(cat_id = 2) SCREENS & DEVICES (parent Category)
<ul>
<li>(cat_id = 52)TV (Sub category)
<ul>
<li>(ID- 1234) Thinking of shopping and advertising, which of the following have you ever done?
<ul>
<li>(ID- 4111) How often do you do this via your TV screen?</li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p>So in order to map this i created the following table. Please note I already have a Question table and a category table that link to this, that contains the IDs above.</p>
<pre><code>| id | object_id | parent_id | type |
|---- |----------- |----------- |------ |
| 1 | 1 | NULL | 1 |
| 2 | 41 | 1 | 1 |
| 3 | 1234 | 41 | 2 |
| 4 | 4111 | 1234 | 2 |
| 5 | 4112 | 1234 | 2 |
| 6 | 4113 | 1234 | 2 |
| 7 | 44 | 1 | 1 |
| 8 | 1234 | 44 | 2 |
| 9 | 4111 | 1234 | 2 |
| 10 | 4112 | 1234 | 2 |
| 11 | 4113 | 1234 | 2 |
| 12 | 2 | NULL | 1 |
| 13 | 51 | 2 | 1 |
| 14 | 1234 | 51 | 2 |
| 15 | 4111 | 1234 | 2 |
| 16 | 4112 | 1234 | 2 |
| 17 | 4113 | 1234 | 2 |
| 18 | 52 | 2 | 1 |
| 19 | 1234 | 52 | 2 |
| 20 | 4111 | 1234 | 2 |
| 21 | 4112 | 1234 | 2 |
| 22 | 4113 | 1234 | 2 |
</code></pre>
<p>As you can see above there is a lot of repetition. Other than the ID given for the table 4,5,6,9,10,11,15,16,17,20,21,22 is the same data. which makes me think this isn't the most efficient way if approaching this. I have a feeling I should be splitting this out by object ID and then having all parent but then I start to lose track and get lost. This is a small sample the above example is repeated a lot of times in the mind map as i can be access through multiple paths</p>
<p>Can anyone help? Is it possible or is what I have done sufficient.</p>
| 3 | 1,938 |
Unable to fetch search results via fetch - Github API
|
<p>I am trying to search users via a search String using Github API
I am using fetch with the url but unable to access the result json.</p>
<p>This is where I am fetching the data</p>
<pre><code>componentDidMount() {
console.log(this.props.searchString);
let furl = 'https://api.github.com/search/users?q='.concat(
this.props.searchString
);
console.log(furl);
fetch(furl)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
user: json
});
});
console.log(this.state.user);
console.log(this.state.user.total_count);
}
render() {
var { isLoaded, user } = this.state;
if (!isLoaded) {
return <div>Loading ....</div>;
} else {
return (
<Fragment>
<Switch>
<Route
exact
path="/"
render={() => (
<Fragment>
<div className="list-User">
<ul className="user-unordered-list">
{user.map(user => (
<li key={user.id}>
<div className="user-info">
<img src={user.avatar_url} />
<h1> {user.login}</h1>
<p>
<a href={user.html_url}>Github Profile</a>
</p>
</div>
</li>
))}
</ul>
</div>
</Fragment>
)}
/>
<Route
path="/search"
render={({ history }) => (
<Fragment>
<UserSearch searchString={this.state.query} />
</Fragment>
)}
/>
<Route
path="/user/m"
render={({ history }) => (
<div className="user-profile">
<User />
</div>
)}
/>
}
</Switch>
</Fragment>
);
}
</code></pre>
<p>The output from the console is as follows</p>
<pre><code>ddd
UserSearch.js:19 https://api.github.com/search/users?q=ddd
UserSearch.js:29 []length: 0__proto__: Array(0)
react-dom.development.js:57 Uncaught Error: Objects are not valid as a React child (found: object with keys {login, id, node_id, avatar_url, gravatar_id, url, html_url, followers_url, following_url, gists_url, starred_url, subscriptions_url, organizations_url, repos_url, events_url, received_events_url, type, site_admin, score}). If you meant to render a collection of children, use an array instead.
in div (at UserSearch.js:86)
in UserSearch (at App.js:201)
in Route (at App.js:151)
in Switch (at App.js:150)
in App (at src/index.js:9)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:8)
at invariant (react-dom.development.js:57)
at throwOnInvalidObjectType (react-dom.development.js:13607)
at createChild (react-dom.development.js:13834)
at reconcileChildrenArray (react-dom.development.js:14080)
at reconcileChildFibers (react-dom.development.js:14430)
at reconcileChildren (react-dom.development.js:14817)
at updateFragment (react-dom.development.js:14983)
at beginWork (react-dom.development.js:16009)
at performUnitOfWork (react-dom.development.js:19102)
at workLoop (react-dom.development.js:19143)
at HTMLUnknownElement.callCallback (react-dom.development.js:147)
at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
at invokeGuardedCallback (react-dom.development.js:250)
at replayUnitOfWork (react-dom.development.js:18350)
at renderRoot (react-dom.development.js:19261)
at performWorkOnRoot (react-dom.development.js:20165)
at performWork (react-dom.development.js:20075)
at performSyncWork (react-dom.development.js:20049)
at requestWork (react-dom.development.js:19904)
at scheduleWork (react-dom.development.js:19711)
at Object.enqueueSetState (react-dom.development.js:12936)
at UserSearch.push../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:356)
at UserSearch.js:23
invariant @ react-dom.development.js:57
throwOnInvalidObjectType @ react-dom.development.js:13607
createChild @ react-dom.development.js:13834
reconcileChildrenArray @ react-dom.development.js:14080
reconcileChildFibers @ react-dom.development.js:14430
reconcileChildren @ react-dom.development.js:14817
updateFragment @ react-dom.development.js:14983
beginWork @ react-dom.development.js:16009
performUnitOfWork @ react-dom.development.js:19102
workLoop @ react-dom.development.js:19143
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
replayUnitOfWork @ react-dom.development.js:18350
renderRoot @ react-dom.development.js:19261
performWorkOnRoot @ react-dom.development.js:20165
performWork @ react-dom.development.js:20075
performSyncWork @ react-dom.development.js:20049
requestWork @ react-dom.development.js:19904
scheduleWork @ react-dom.development.js:19711
enqueueSetState @ react-dom.development.js:12936
push../node_modules/react/cjs/react.development.js.Component.setState @ react.development.js:356
(anonymous) @ UserSearch.js:23
Promise.then (async)
componentDidMount @ UserSearch.js:21
commitLifeCycles @ react-dom.development.js:16998
commitAllLifeCycles @ react-dom.development.js:18512
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
commitRoot @ react-dom.development.js:18717
completeRoot @ react-dom.development.js:20247
performWorkOnRoot @ react-dom.development.js:20170
performWork @ react-dom.development.js:20075
performSyncWork @ react-dom.development.js:20049
interactiveUpdates$1 @ react-dom.development.js:20337
interactiveUpdates @ react-dom.development.js:2267
dispatchInteractiveEvent @ react-dom.development.js:5083
index.js:1446 The above error occurred in one of your React components:
in div (at UserSearch.js:86)
in UserSearch (at App.js:201)
in Route (at App.js:151)
in Switch (at App.js:150)
in App (at src/index.js:9)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:8)
Consider adding an error boundary to your tree to customize error handling behavior.
function.console.(anonymous function) @ index.js:1446
logCapturedError @ react-dom.development.js:16764
logError @ react-dom.development.js:16800
update.callback @ react-dom.development.js:17814
callCallback @ react-dom.development.js:11743
commitUpdateEffects @ react-dom.development.js:11783
commitUpdateQueue @ react-dom.development.js:11773
commitLifeCycles @ react-dom.development.js:17055
commitAllLifeCycles @ react-dom.development.js:18512
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
commitRoot @ react-dom.development.js:18717
completeRoot @ react-dom.development.js:20247
performWorkOnRoot @ react-dom.development.js:20170
performWork @ react-dom.development.js:20075
performSyncWork @ react-dom.development.js:20049
requestWork @ react-dom.development.js:19904
scheduleWork @ react-dom.development.js:19711
enqueueSetState @ react-dom.development.js:12936
push../node_modules/react/cjs/react.development.js.Component.setState @ react.development.js:356
(anonymous) @ UserSearch.js:23
Promise.then (async)
componentDidMount @ UserSearch.js:21
commitLifeCycles @ react-dom.development.js:16998
commitAllLifeCycles @ react-dom.development.js:18512
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
commitRoot @ react-dom.development.js:18717
completeRoot @ react-dom.development.js:20247
performWorkOnRoot @ react-dom.development.js:20170
performWork @ react-dom.development.js:20075
performSyncWork @ react-dom.development.js:20049
interactiveUpdates$1 @ react-dom.development.js:20337
interactiveUpdates @ react-dom.development.js:2267
dispatchInteractiveEvent @ react-dom.development.js:5083
react-dom.development.js:57 Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {login, id, node_id, avatar_url, gravatar_id, url, html_url, followers_url, following_url, gists_url, starred_url, subscriptions_url, organizations_url, repos_url, events_url, received_events_url, type, site_admin, score}). If you meant to render a collection of children, use an array instead.
in div (at UserSearch.js:86)
in UserSearch (at App.js:201)
in Route (at App.js:151)
in Switch (at App.js:150)
in App (at src/index.js:9)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:8)
at invariant (react-dom.development.js:57)
at throwOnInvalidObjectType (react-dom.development.js:13607)
at createChild (react-dom.development.js:13834)
at reconcileChildrenArray (react-dom.development.js:14080)
at reconcileChildFibers (react-dom.development.js:14430)
at reconcileChildren (react-dom.development.js:14817)
at updateFragment (react-dom.development.js:14983)
at beginWork (react-dom.development.js:16009)
at performUnitOfWork (react-dom.development.js:19102)
at workLoop (react-dom.development.js:19143)
at renderRoot (react-dom.development.js:19228)
at performWorkOnRoot (react-dom.development.js:20165)
at performWork (react-dom.development.js:20075)
at performSyncWork (react-dom.development.js:20049)
at requestWork (react-dom.development.js:19904)
at scheduleWork (react-dom.development.js:19711)
at Object.enqueueSetState (react-dom.development.js:12936)
at UserSearch.push../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:356)
at UserSearch.js:23
invariant @ react-dom.development.js:57
throwOnInvalidObjectType @ react-dom.development.js:13607
createChild @ react-dom.development.js:13834
reconcileChildrenArray @ react-dom.development.js:14080
reconcileChildFibers @ react-dom.development.js:14430
reconcileChildren @ react-dom.development.js:14817
updateFragment @ react-dom.development.js:14983
beginWork @ react-dom.development.js:16009
performUnitOfWork @ react-dom.development.js:19102
workLoop @ react-dom.development.js:19143
renderRoot @ react-dom.development.js:19228
performWorkOnRoot @ react-dom.development.js:20165
performWork @ react-dom.development.js:20075
performSyncWork @ react-dom.development.js:20049
requestWork @ react-dom.development.js:19904
scheduleWork @ react-dom.development.js:19711
enqueueSetState @ react-dom.development.js:12936
push../node_modules/react/cjs/react.development.js.Component.setState @ react.development.js:356
(anonymous) @ UserSearch.js:23
Promise.then (async)
componentDidMount @ UserSearch.js:21
commitLifeCycles @ react-dom.development.js:16998
commitAllLifeCycles @ react-dom.development.js:18512
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
commitRoot @ react-dom.development.js:18717
completeRoot @ react-dom.development.js:20247
performWorkOnRoot @ react-dom.development.js:20170
performWork @ react-dom.development.js:20075
performSyncWork @ react-dom.development.js:20049
interactiveUpdates$1 @ react-dom.development.js:20337
interactiveUpdates @ react-dom.development.js:2267
dispatchInteractiveEvent @ react-dom.development.js:5083
</code></pre>
<p>The json file at <a href="https://api.github.com/search/users?q=ddd" rel="nofollow noreferrer">https://api.github.com/search/users?q=ddd</a></p>
<pre><code>{
"total_count": 3056,
"incomplete_results": false,
"items": [
{
"login": "ddd",
"id": 400620,
"node_id": "MDQ6VXNlcjQwMDYyMA==",
"avatar_url": "https://avatars0.githubusercontent.com/u/400620?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ddd",
"html_url": "https://github.com/ddd",
"followers_url": "https://api.github.com/users/ddd/followers",
"following_url": "https://api.github.com/users/ddd/following{/other_user}",
"gists_url": "https://api.github.com/users/ddd/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ddd/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ddd/subscriptions",
"organizations_url": "https://api.github.com/users/ddd/orgs",
"repos_url": "https://api.github.com/users/ddd/repos",
"events_url": "https://api.github.com/users/ddd/events{/privacy}",
"received_events_url": "https://api.github.com/users/ddd/received_events",
"type": "User",
"site_admin": false,
"score": 104.69152
},
{
"login": "dddaisuke",
"id": 96539,
"node_id": "MDQ6VXNlcjk2NTM5",
"avatar_url": "https://avatars2.githubusercontent.com/u/96539?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dddaisuke",
"html_url": "https://github.com/dddaisuke",
"followers_url": "https://api.github.com/users/dddaisuke/followers",
"following_url": "https://api.github.com/users/dddaisuke/following{/other_user}",
"gists_url": "https://api.github.com/users/dddaisuke/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dddaisuke/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dddaisuke/subscriptions",
"organizations_url": "https://api.github.com/users/dddaisuke/orgs",
"repos_url": "https://api.github.com/users/dddaisuke/repos",
"events_url": "https://api.github.com/users/dddaisuke/events{/privacy}",
"received_events_url": "https://api.github.com/users/dddaisuke/received_events",
"type": "User",
"site_admin": false,
"score": 74.155464
},
</code></pre>
<p>What am i doing wrong here,please tell ?</p>
| 3 | 5,825 |
ListView items does not fit in Grid cells
|
<p>Help me please. In Xamarin.Forms I have a main ListView containing cards (Frame with Grid). Each Grid has Labels and a ListVew with phones. The ListVew with phones takes up three rows and three columns. I need all the elements of the phone ListView inside the Grid to always be visible (usually their number is up to three, but maybe more) and that the height of the Grid cells will increase if necessary to accommodate all the elements of the phone ViewList. Is this possible to do? Now Grid cells increase in text height in labels but not in PhoneListView height.</p>
<pre><code>[MyListView MainView = new MyListView
{
SeparatorVisibility = SeparatorVisibility.None,
HasUnevenRows = true,
ItemTemplate = new DataTemplate(() =>
{
Grid MyGrid = new Grid
{
RowDefinitions =
{
new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) },
new RowDefinition { Height = new GridLength(0.02, GridUnitType.Absolute) },
new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
new RowDefinition { Height = new GridLength(0.02, GridUnitType.Absolute) },
new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
new RowDefinition { Height = new GridLength(0.02, GridUnitType.Absolute) },
new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }
},
ColumnDefinitions =
{
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }
}
};
...
ListView phonesList = new ListView
{
VerticalScrollBarVisibility = ScrollBarVisibility.Never,
BackgroundColor = Color.Transparent,
SeparatorVisibility = SeparatorVisibility.None,
HasUnevenRows = true,
VerticalOptions = LayoutOptions.FillAndExpand,
ItemTemplate = new DataTemplate(() =>
{
Image phoneButton = new Image { Source = "phone_green.png", HeightRequest = 40, VerticalOptions = LayoutOptions.Center };
Label phoneTextLabel = new Label { HeightRequest = 40, VerticalOptions = LayoutOptions.Center, VerticalTextAlignment = TextAlignment.Center };
phoneTextLabel.SetBinding(Label.TextProperty, "phone");
return new ViewCell { View = new StackLayout {
Orientation = StackOrientation.Horizontal,
Children = { phoneButton, phoneTextLabel } } };
})
};
phonesList.SetBinding(ListView.ItemsSourceProperty, "phones", BindingMode.Default, new PhoneSepConverter());
...
DetailGrid.Children.Add(phonesList, 4, 2);
...
Grid.SetColumnSpan(phonesList, 3);
Grid.SetRowSpan(phonesList, 3);
...
Frame ListItem = new Frame { Content = MyGrid };
return new ViewCell
{
View = ListItem
};
})
};][1]
</code></pre>
| 3 | 1,831 |
Display glitches with html emails sent from Java
|
<p>I am using the below code to send html emails, but somehow the output is coming different on different mailboxes. On gmail its coming fine, on yahoo,rediff,hotmail and ms outlook the whole layout gets break. </p>
<p>How can all display be same irrespective of mail clients.</p>
<pre><code>StringBuffer sb = new StringBuffer();
sb.append("<!DOCTYPE HTML>");
sb.append("<html lang='en' style='height: 100%;'><head>");
sb.append("<meta http-equiv='X-UA-Compatible' content='chrome=1' />");
sb.append("<title>UnRegisteredUser Invite</title>");
sb.append("<style type='text/css'>");
sb.append("html {height: 100%; }");
sb.append("body {margin: 0;padding: 0;height: 100%;}");
sb.append("</style>");
sb.append("</head><body style='margin: 0;padding: 0;height: 100%;'>");
sb.append("<div class='content' style='position: relative;width: 500px;height: 224px;z-index:1;margin-top: 10px;margin-left: 10px;border: .08em solid rgba(147, 184, 189,0.8);-webkit-box-shadow: 0pt 2px 2px rgba(105, 108, 109, 0.7), 0px 0px 2px 2px rgba(208, 223, 226, 0.4) inset;-moz-box-shadow: 0pt 2px 2px rgba(105, 108, 109, 0.7), 0px 0px 2px 2px rgba(208, 223, 226, 0.4) inset;box-shadow: 0pt 2px 2px rgba(105, 108, 109, 0.7), 0px 0px 2px 2px rgba(208, 223, 226, 0.4) inset;-webkit-box-shadow: 2px;-moz-border-radius: .1em;border-radius: .1em;'>");
sb.append("<div class='email' style='clear: both;width: 500px;height: 122px;margin-left: 0%;margin-right: 0%;'>");
sb.append("<div class='emailIMG' style='float: left;width: 125px;height: 122px;margin-left: 0%;margin-right: 0%;'>");
sb.append("<img src='" +photoPath+ "' alt='' style='width: 100px;height: 100px;margin-left: 10px;margin-top: 10px;'/>");
sb.append("</div>");
sb.append("<div class='emailContent' style='float: right;width: 375px;height: 122px;margin-left: 0%;margin-right: 0%;'>");
sb.append("<div class='emailContent_placeholder' style='float: left;width: 375px;height: 22px;margin-left: 0px;margin-top: 10px;'>");
sb.append("<label style='color: black;text-align: left;float: left;margin-top: 4px;font-size:.9em;font-family: Courier ;font-weight:bold;color: #4E4E4E;'>"+ inviter +" invites you for a video call on " +Constants.PRODUCT_TITLE+".</label>");
sb.append("</div>");
sb.append("<div class='emailContent_videocall' style='float: left;width: 375px;height: 30px;margin-left: 0px;margin-right: 0%;margin-top: 10px;'>");
sb.append("<a href='"+videoCallPath+"'><img src='"+path+"img/vid_call.png' alt='' style='float: left;width: 100px;height: 30px;margin-left: 0px;margin-right: 0%;'/>");
sb.append("<label style='color: black;text-align: left;float: left;margin-top: 4px;font-size:.9em;font-family: Courier ;font-weight:bold;color: #4E4E4E;'> Give "+ inviter +" now a call. </label>");
sb.append("</div>");
sb.append("</div> ");
sb.append("</div>");
sb.append("<div class='marketing' style='clear: both;width: 500px;height: 102px;margin-left: 0%;margin-bottom: 10px;'>");
sb.append("<span style='color: black;text-align: left;float: left;margin-top: 4px;margin-left: 10px;font-size: 1em;font-family: Courier ;font-weight:bold;color: #4E4E4E;'>");
sb.append("<p>You can register a free account <span><u><a href='"+url+"'>here</a></u></span>.</p>");
sb.append("<p>You can use video chat for free. No installation or registeration is required.</p>");
sb.append("</span>");
sb.append("</div>");
sb.append("</div>");
sb.append("</body></html>");
String htmlBody = sb.toString();
</code></pre>
| 3 | 1,535 |
App is crashing while running AVD in Android Studio. I am running on virtual device pixel 5x with API 27
|
<p>When I try to create and instance of FusedLocationApi it doesn't get recognized some How. it is in red. It is not importing any classes. seems to me that there might be some problem in Gradle Build App. Please Check it out.</p>
<p>This is My MapActivity.java File</p>
<pre><code>package com.matt.mapapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
private LocationRequest locationRequest;
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] permissions,
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
private synchronized void buildGoogleApiClient(){
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
@Override
public void onLocationChanged(Location location) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
LocationRequest.FusedLocationApi.requestlocationUpdates(client, locationRequest, this);
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
</code></pre>
<p>This is my build gradle (Module app) File. There seemed to be some problem in compiling as there is no such command as compile</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.matt.mapapp"
minSdkVersion 22
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
implementation 'com.google.android.gms:play-services-maps:11.0.4'
implementation 'com.google.android.gms:play-services-location:11.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation'com.android.support.test.espresso:espresso-core:2.2.2'
}
</code></pre>
<p>please Check it out and tell me the reason behind. I was following a video tutorial on how to create a map based app and suddenly when I reached at a point to use Fused Location Api I got stuck. The Build Gradle code in the tutorial was different than mine so I thing that this can be the reason for the FusedLocationApi to not work properly.</p>
| 3 | 1,750 |
Comparing old and new prices in a bootstrap thumbnail?
|
<p>As can be seen from the code below I am dynamically generating thumbnails using the template in <code>var sProductTemplate</code>. The thhumbnails are populated via ajax request which is getting the information from a json file.</p>
<p>My task is to compare the current price in the thumbnail vs the updated price in the json(if such) and display a green arrow in the thumbnail if the new price is higher than the old. If the new price is lower then the old one then I must display a red arrow.</p>
<p><strong>My problem</strong> is that I cannot really get to this point, since I cannot figure out how to save the old price and then compare it to the new price for each thumbnail.</p>
<p>Since each thumbnail has a unique id the i've written this code to get the price from the dom by the thumbnail's id's : </p>
<pre><code>var sPriceInDom = Number($("#product-id-"+sProductId+" .product-price").text());
</code></pre>
<p>But, of course, this gives me the last price and I cannot really compare it to the old price, since it is replaced by the new price.</p>
<p>If I place this code right after the ajax request, then it gives me just zeroes, since the thumbnail is dynamically generated and it has to be populated first.</p>
<p>Does anyone have an idea how can I keep the old price and compare it to the lastly updated one, so I can calculate the difference?</p>
<p>Here is all the neccesary code : </p>
<pre><code>var sProductTemplate = '<div class="col-sm-6 col-md-3"> \
<div class="thumbnail"> \
<div id="product-id-{{product-id}}" class="product"> \
<img class="imgProduct" src="{{product-icon}}" alt="idiot forgot icon"> \
<div class="caption"> \
<h3>{{product-name}}</h3> \
<div class="product-price">{{product-price}}</div> \
<i {{arrow-updown}}></i> \
</div> \
</div> \
</div>';
getProducts();
function getProducts() {
$.ajax({
"url":'get-products.php',
"method":"get",
"dataType":"text",
"cache":false
}).done( function( jData ){
var jProducts=JSON.parse(jData);
jProducts.forEach( function( jProduct ){
var sProductId = jProduct.id;
var sProductName = jProduct.name;
var sProductBrand = jProduct.brand;
var sProductPrice = jProduct.price;
lastPrice = sProductPrice;
var sPriceInDom = Number($("#product-id-"+sProductId+" .product-price").text());
console.log(sPriceInDom + " DOM");
var arrowUP ='class="fa fa-arrow-up" aria-hidden="true"';
var arrowDOWN ='class="fa fa-arrow-down" aria-hidden="true"';
var sTempProduct = sProductTemplate;
sTempProduct = sTempProduct.replace("{{product-id}}", sProductId);
sTempProduct = sTempProduct.replace("{{product-icon}}", "http://image.flaticon.com/teams/1-freepik.jpg");
sTempProduct = sTempProduct.replace("{{product-name}}", sProductBrand);
sTempProduct = sTempProduct.replace("{{product-price}}", sProductPrice);
sTempProduct = sTempProduct.replace("{{arrow-updown}}",arrowUP);
$("#lblDisplayProducts").append(sTempProduct);
})
});
}
</code></pre>
| 3 | 1,588 |
conways game of life from automate boring stuff book
|
<p>i need to create a python conways game of life. i have this code given below from book "how to automate boring stuff with python" i had run this code but the output doesn't seem that the code is correct. i intended to get a result of the conway program to be in grid. can you please review the code and briefly decode it for me.</p>
<pre><code> # Conway's Game of Life
import random, time, copy
WIDTH = 60
HEIGHT = 20
# Create a list of list for the cells:
nextCells = []
for x in range(WIDTH):
column = [] # Create a new column.
for y in range(HEIGHT):
if random.randint(0, 1) == 0:
column.append('#') # Add a living cell.
else:
column.append(' ') # Add a dead cell.
nextCells.append(column) # nextCells is a list of column lists.
while True: # Main program loop.
print('\n\n\n\n\n') # Separate each step with newlines.
currentCells = copy.deepcopy(nextCells)
# Print currentCells on the screen:
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end='') # Print the # or space.
print() # Print a newline at the end of the row.
# Calculate the next step's cells based on current step's cells:
for x in range(WIDTH):
for y in range(HEIGHT):
# Get neighboring coordinates:
# `% WIDTH` ensures leftCoord is always between 0 and WIDTH - 1
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
# Count number of living neighbors:
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1 # Top-left neighbor is alive.
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1 # Top neighbor is alive.
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1 # Top-right neighbor is alive.
if currentCells[leftCoord][y] == '#':
numNeighbors += 1 # Left neighbor is alive.
if currentCells[rightCoord][y] == '#':
numNeighbors += 1 # Right neighbor is alive.
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1 # Bottom-left neighbor is alive.
if currentCells[x][belowCoord] == '#':
numNeighbors += 1 # Bottom neighbor is alive.
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors += 1 # Bottom-right neighbor is alive.
# Set cell based on Conway's Game of Life rules:
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
# Living cells with 2 or 3 neighbors stay alive:
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
# Dead cells with 3 neighbors become alive:
nextCells[x][y] = '#'
else:
# Everything else dies or stays dead:
nextCells[x][y] = ' '
time.sleep(1) # Add a 1-second pause to reduce flickering.
</code></pre>
| 3 | 1,587 |
unable to compile googletest in eclipse
|
<p>I am trying to compile googletest (git clone <a href="https://github.com/google/googletest.git" rel="nofollow noreferrer">https://github.com/google/googletest.git</a> -b release-1.11.0) but keep getting 1000+ linker errors.</p>
<p>I am running windows 10, eclipse CDT (latest), mingw (latest) gcc. I created an eclipse c++ project (executable, empty project).</p>
<p>added include paths to:</p>
<ul>
<li>googletest</li>
<li>googletest/includes</li>
<li>googlemock</li>
<li>googlemock/includes</li>
</ul>
<p>added source location to:</p>
<ul>
<li>googletest/src</li>
<li>googlemock/src</li>
</ul>
<p>All is compiled without problems, but linking fails with 1000+ errors. Eg.</p>
<pre><code>C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
googletest\gtest.o: in function `testing::IsNotSubstring(char const*, char const*, wchar_t const*, wchar_t const*)':
C:\dev\unode\eclipse\unit_tests\Debug/../../googletest/googletest/src/gtest.cc:1821: multiple definition of `testing::IsNotSubstring(char const*, char const*, wchar_t const*, wchar_t const*)';
googletest\gtest-all.o:C:/dev/unode/eclipse/googletest/googletest/src/gtest.cc:1821: first defined here
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
googletest\gtest.o: in function `testing::IsSubstring(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
C:\dev\unode\eclipse\unit_tests\Debug/../../googletest/googletest/src/gtest.cc:1827: multiple definition of `testing::IsSubstring(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)';
googletest\gtest-all.o:C:/dev/unode/eclipse/googletest/googletest/src/gtest.cc:1827: first defined here
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
googletest\gtest.o: in function `testing::IsNotSubstring(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
</code></pre>
<p>I am reading googletests readme.md to figure out what I am doing wrong but getting nowhere. Some help would be greatly appreciated</p>
| 3 | 1,089 |
Data exists, but the map function returns no value React Native
|
<p>I guess I'm not realizing something. I have the structure where I list the friends of the logged in user. Data appears to exist on console.log, but the map function does not work. Also, when I press the component in tab transitions, useEffect only works once. It doesn't work after that. Can you help me? Thanks.</p>
<p>App.js code</p>
<pre><code>import { StatusBar } from 'expo-status-bar';
import React, { useState, useMemo } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import SignIn from './SignIn';
import SignUp from './SignUp';
import Conversation from './Conversation';
import Contacts from './Contacts';
import Settings from './Settings';
import Chats from './Chats';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import {Ionicons} from '@expo/vector-icons'
import { UserProvider } from './UserContext';
import { LogBox } from "react-native"
const Stack = createNativeStackNavigator();
const Tabs = createBottomTabNavigator();
const TabsNavigator = () => (
<Tabs.Navigator screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
return <Ionicons name={route.name === "Chats" ? "chatbubble-ellipses-outline" : route.name === "Contacts" ? "people-outline" : "settings-outline"} color={color} size={size} />
}})}>
<Tabs.Screen name="Chats" component={Chats} />
<Tabs.Screen name="Contacts" component={Contacts} />
<Tabs.Screen name="Settings" component={Settings} />
</Tabs.Navigator>
);
export default function App() {
LogBox.ignoreAllLogs(true);
// const [lastUser, setLastUser] = useState('none');
// const value = useMemo(
// () => ({ lastUser, setLastUser }),
// [lastUser]
// );
return (
<UserProvider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen options={{headerShown : false }} name="SignIn" component={SignIn} />
<Stack.Screen
name="SignUp"
component={SignUp}
options={{ headerTitle:'Login', headerBackVisible : true, headerBackTitleVisible :true}}
/>
<Stack.Screen name="Home" component={TabsNavigator} options={{headerShown : false, headerBackTitleVisible : false}}/>
<Stack.Screen name="Contacts" component={Contacts} options={{ headerTitle:'ChatApp'}}/>
<Stack.Screen name="Conversation" component={Conversation} options={{ headerTitle:'ChatApp'}}/>
</Stack.Navigator>
</NavigationContainer>
</UserProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
</code></pre>
<p>SignIn.js code</p>
<pre><code>import { useNavigation } from '@react-navigation/core'
import React, { useEffect, useState, createContext, useContext } from 'react'
import { KeyboardAvoidingView, StyleSheet, Text, TextInput, TouchableOpacity, View, Image } from 'react-native'
import { borderColor } from 'react-native/Libraries/Components/View/ReactNativeStyleAttributes'
import { auth, firebase } from './firebase'
import { userContext } from './UserContext'
import AsyncStorage from '@react-native-async-storage/async-storage';
const SignIn = () => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const navigation = useNavigation()
const value = useContext(userContext);
const handleLogin = async() => {
await auth
.signInWithEmailAndPassword(email, password)
.then(userCredentials => {
const user = userCredentials.user;
console.log('Logged in with:', user.email);
getUser(user.email);
navigation.replace("Home");
})
.catch(error => alert(error.message))
}
const getUser = async (email2) => {
await firebase.database().ref().child('users').orderByChild('email').equalTo(email2).once('value').then((data) => {
data.forEach((node) => {
storeUser(node.val().username); // one data
}
)
}
)
}
const storeUser = async(data) => {
try{
await AsyncStorage.setItem('sertacKul', data);
}catch(err){
console.log(err);
}
}
return(
<KeyboardAvoidingView
style={styles.container}
behavior="padding"
>
<View style={styles.inputContainer}>
<Image style={styles.logo} source={require('./img/logo.png')}>
</Image>
<TextInput
placeholder="Email"
value={email}
onChangeText={text => setEmail(text)}
style={styles.input}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={text => setPassword(text)}
style={styles.input}
secureTextEntry
/>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity
onPress={handleLogin}
style={styles.button}
>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
//onPress={handleSignUp}
onPress={() => navigation.navigate('SignUp')}
style={[styles.button, styles.buttonOutline]}
>
<Text style={styles.buttonOutlineText}>Register</Text>
</TouchableOpacity>
<TouchableOpacity
//onPress={handleSignUp}
onPress={() => value.setData('ebebbebebe')}
style={[styles.button, styles.buttonOutline]}
>
<Text style={styles.buttonOutlineText}>{value.lastUser}</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
)
}
export default SignIn;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor : 'white'
},
logo :{
resizeMode :'contain',
width: '100%',
marginBottom : 40
},
inputContainer: {
width: '80%'
},
input: {
backgroundColor: '#eeeeee',
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 10,
marginTop: 5,
},
buttonContainer: {
width: '60%',
justifyContent: 'center',
alignItems: 'center',
marginTop: 40,
},
button: {
backgroundColor: '#06d6cc',
width: '100%',
padding: 15,
borderRadius: 10,
alignItems: 'center',
},
buttonOutline: {
backgroundColor: 'white',
marginTop: 5,
borderColor: '#06d6cc',
borderWidth: 2,
},
buttonText: {
color: 'white',
fontWeight: '700',
fontSize: 16,
},
buttonOutlineText: {
color: '#06d6cc',
fontWeight: '700',
fontSize: 16,
},
})
</code></pre>
<p>Contact.js code</p>
<pre><code>import React, { useState, useEffect, useContext } from "react";
import {
StyleSheet,
View,
TextInput,Text
} from "react-native";
import { auth, firebase } from "./firebase";
import { List, Avatar, Divider, FAB } from "react-native-paper";
import uuid from "react-native-uuid";
import moment from "moment";
import { userContext } from "./UserContext";
import AsyncStorage from '@react-native-async-storage/async-storage';
const Contacts = () => {
const [username, setUsername] = useState("");
const value = useContext(userContext);
const [contactList, setContactList] = useState([{}]);
const [lastUser, setLastUser] = useState('');
useEffect(() => {
setContactList([])
updateLastUserName();
getContacts();
}, [])
useEffect(() => {
console.log(lastUser);
console.log(contactList);
}, [lastUser, contactList]);
async function updateLastUserName(){
const user = await getUserName();
setLastUser(user);
}
async function getUserName(){
const user = await AsyncStorage.getItem('sertacKul');
return user;
}
const addFriend = () => {
console.log(value.lastUser)
firebase
.database()
.ref("/users/")
.once("value")
.then((data) => {
let id = uuid.v4();
firebase
.database()
.ref("/friendrelations/" + id)
.set({
id: id,
user1: username,
user2: lastUser,
relationtype: "normal",
createdDate: moment().format("DD/MM/YYYY HH:mm:ss"),
})
.then(() => alert("Friend added."));
});
};
async function getContacts(){
await firebase.database().ref().child('friendrelations').orderByChild('user2').equalTo(lastUser)
.once('value').then(data => {
data.forEach((node) => { setContactList(lastContacts => [...lastContacts, node.val().user1])})
})
}
return (
<View>
<TextInput
placeholder="Yeni Arkadaş"
value={username}
style={styles.input}
onChangeText={(text) => setUsername(text)}
/>
<FAB
onPress={() => addFriend()}
icon="plus"
style={{ position: "absolute", right: 16 }}
/>
{/* is not working */}
{contactList.map((item)=>{
(<List.Item onPress={() => navigation.navigate('Conversation')} title={item}
left={() => <Avatar.Image source={require('./img/profile1.png')} size={53}/>}
/>
)
})}
<Divider inset/>
</View>
);
};
export default Contacts;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "white",
},
logo: {
resizeMode: "contain",
width: "100%",
marginBottom: 40,
},
inputContainer: {
width: "80%",
},
input: {
backgroundColor: "#eeeeee",
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 10,
marginTop: 5,
},
buttonContainer: {
width: "60%",
justifyContent: "center",
alignItems: "center",
marginTop: 40,
},
button: {
backgroundColor: "#06d6cc",
width: "100%",
padding: 15,
borderRadius: 10,
alignItems: "center",
},
buttonOutline: {
backgroundColor: "white",
marginTop: 5,
borderColor: "#06d6cc",
borderWidth: 2,
},
buttonText: {
color: "white",
fontWeight: "700",
fontSize: 16,
},
buttonOutlineText: {
color: "#06d6cc",
fontWeight: "700",
fontSize: 16,
},
});
</code></pre>
| 3 | 4,942 |
How can I redirect users to different pages after inserting into the database using Sweet Alert in PHP?
|
<p>I am finding it difficult to use the sweet alert after a successful login and also add the sweet alert after a user successfully inserts his/her data into the database. I am finding it difficult to use the sweet alert after a successful login and also add the sweet alert after a user successfully inserts his/her data into the database.x</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><?php
include ("dbcon.php");
session_start();
if(isset($_POST['login'])){
//get the user data
$username = mysqli_real_escape_string($conn , $_POST['username']);
$email = mysqli_real_escape_string($conn , $_POST['email']);
$pwd = mysqli_real_escape_string($conn , $_POST['pdf]);
if(empty($username) || empty($email) || empty($pwd)){
header("Location:../../login.php?loginempty");
exit();
}else{
$select = "SELECT * FROM users WHERE email ='$email' ";
$result = mysqli_query($conn , $select);
$result_check = mysqli_num_rows($result);
if($result_check < 1){
header("Location:../../login.php?invaliduid");
exit();
}else{
if($row=mysqli_fetch_assoc($result)){
$cpwd = $row['pwd'];
//de-hashed the password
// $hashedpwd = password_verify($pwd, $row['pdf]);
if($pwd != $cpwd){
header("Location: ../../login.php?invalidpwd");
exit();
}elseif($pwd == $cpwd){
$_SESSION['uid'] =$row['username'];
$username = $_SESSION['uid'];
echo "
Swal.fire({
title: 'Welcome to bottles beach',
text: 'You successfully submitted the form,
icon: 'success',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Great, show me the site!'
}).then((result) => {
if (result.confirmed) {
location = '../../dashboard.php'
}
})
";
// header("Location:../../dashboard.php?loginsuc");
// exit();
}
}
}
}
}
?>
<?php
session_start();
include ("dbcon.php");
if(isset($_POST["reg-btn"])) {
$username = mysqli_real_escape_string($conn , $_POST['username']);
$email = mysqli_real_escape_string($conn , $_POST['email']);
$phone = mysqli_real_escape_string($conn , $_POST['phone']);
$pwd = mysqli_real_escape_string($conn , $_POST['pwd']);
$cpwd = mysqli_real_escape_string($conn , $_POST['cpwd']);
// $verify_token = md5(random());
// VALIDATION
if(strlen(trim($pwd)) < 5) {
// Password Length
header("Location:../../register.php?passwordshort");
exit();
}
if($pwd != $cpwd ) {
// If Password = Confirm Password
header("Location:../../register.php?comfirmpass");
exit();
}
// Check for Empty Inputs
if (empty($username)|| empty($email)|| empty($phone)|| empty($pwd)|| empty($cpwd) ) {
header ("Location:../../register.php?signupempty");
exit();
}else {
//VALIDATE EMAIL
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
header ("Location:../../register.php?invalidemail");
exit();
}else {
$select = "SELECT * FROM users WHERE username = '$username' AND pwd ='$pwd'";
$result = mysqli_query($conn , $select);
$result_check = mysqli_num_rows($result);
if($result_check > 0) {
echo "ooooops!!! user already exists";
}else {
$insert = "INSERT INTO users (username, email, phone, pwd, cpwd) VALUES ('$username', '$email', '$phone', '$pwd', '$cpwd')";
$result = mysqli_query($conn , $insert);
if(!$result) {
echo "ooooops!!! an error was encountered while inserting data to the database";
}else {
echo "
Swal.fire({
title: 'Welcome to bottles beach',
text: 'You successfully submitted the form,
icon: 'success',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Great, show me the site!'
}).then((result) => {
if (result.confirmed) {
location = '../../login.php'
}
})
";
// header("location: ../../login.php");
// exit();
}
}
}
}
}else {
header ("Location:../../register.php?signupempty");
exit();
}
?></code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
$page_title = "Login Form";
include ('assets/includes/header.php');
include ('assets/includes/navbar.php');
?>
<div class="py-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card shadow">
<div class="card-header">
<h5>Login Form</h5>
</div>
<div class="card-body">
<form action="assets/action/login_action.php" method="POST" autocomplete="no">
<div class="form-group mb-3">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="pwd">Password</label>
<input type="text" name="pwd" id="pwd" class="form-control" autocomplete="off">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="login">Login Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
include ('assets/includes/footer.php');
?>
<?php
$page_title = "Registration Form";
include ('assets/includes/header.php');
include ('assets/includes/navbar.php');
// include ('assets/action/dbcon.php');
?>
<div class="py-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card shadow">
<div class="card-header">
<h5>Registration Form With Email Verification</h5>
</div>
<div class="card-body">
<form action="assets/action/code.php" method="POST">
<div class="form-group mb-3">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="phone">Phone Number</label>
<input type="text" name="phone" id="phone" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="pwd">Password</label>
<input type="text" name="pwd" id="pwd" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="cpwd">Confirm Password</label>
<input type="text" name="cpwd" id="cpwd" class="form-control" autocomplete="off">
</div>
<div class="form-group">
<button type="submit" name="reg-btn" class="btn btn-primary">Register Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
include ('assets/includes/footer.php');
?></code></pre>
</div>
</div>
</p>
<p>difficult adding sweet alert redirection after a user successfully inserts his / her details</p>
| 3 | 6,567 |
netdiagnostics Java agent startup error with Adobe Experience Manager
|
<p>We are using Adobe Experience Manager, and I need to set up monitoring for it via javaagent (we have the special tool for java application monitoring called netdiagnostics).
Usually, for enabling monitoring I only need to pass parameters of netdiagnostics to the application via javaagent option.
But after passed javaagent option to the Adobe Experience Manager, it doesn't start and I see the errors in the logs:</p>
<pre><code>su[16168]: 14.01.2020 08:31:05.615 *INFO * [Apache Sling Terminator] Java VM is shutting down
su[16168]: 14.01.2020 08:31:05.615 *INFO * [Apache Sling Terminator] Stopping Apache Sling
su[16168]: MAIN process: shutdown hook
su[16168]: MAIN process: exiting
su[16168]: Exception in thread "UnregisteringFilterThread for ServiceUnavailableFilter with tags [systemalive]" java.lang.NoClassDefFoundError: com/cavisson/ndutils/ThreadCallOutHandler
su[16168]: at org.apache.felix.hc.core.impl.filter.ServiceUnavailableFilter$UnregisteringFilterThread.run(ServiceUnavailableFilter.java)
su[16168]: Caused by: java.lang.ClassNotFoundException: com.cavisson.ndutils.ThreadCallOutHandler not found by org.apache.felix.healthcheck.core [579]
su[16168]: at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1597)
su[16168]: at org.apache.felix.framework.BundleWiringImpl.access$300(BundleWiringImpl.java:79)
su[16168]: at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1982)
su[16168]: at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
su[16168]: ... 1 more
su[16168]: 14.01.2020 08:31:33.418 *INFO * [Sling Notifier] Apache Sling has been stopped
</code></pre>
<p>Also, when I try to check systemready I get the next error:</p>
<pre><code>curl http://127.0.0.1:4502/systemready
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 500 Server Error</title>
</head>
<body><h2>HTTP ERROR 500</h2>
<p>Problem accessing /systemready. Reason:
<pre> Server Error</pre></p><h3>Caused by:</h3><pre>java.lang.NoClassDefFoundError: com/cavisson/ndutils/NDHttpCapture
at javax.servlet.http.HttpServlet.service(HttpServlet.java:671)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.felix.http.base.internal.handler.ServletHandler.handle(ServletHandler.java:123)
at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:86)
at com.adobe.granite.license.impl.LicenseCheckFilter.doFilter(LicenseCheckFilter.java:308)
at org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:142)
at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:81)
at org.apache.sling.i18n.impl.I18NFilter.doFilter(I18NFilter.java:131)
at org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:142)
at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:81)
at org.apache.felix.http.base.internal.dispatch.Dispatcher$1.doFilter(Dispatcher.java:146)
at org.apache.felix.http.base.internal.whiteboard.WhiteboardManager$2.doFilter(WhiteboardManager.java:1002)
at org.apache.sling.security.impl.ReferrerFilter.doFilter(ReferrerFilter.java:326)
at org.apache.felix.http.base.internal.handler.PreprocessorHandler.handle(PreprocessorHandler.java:136)
at org.apache.felix.http.base.internal.whiteboard.WhiteboardManager$2.doFilter(WhiteboardManager.java:1008)
at org.apache.felix.http.sslfilter.internal.SslFilter.doFilter(SslFilter.java:97)
at org.apache.felix.http.base.internal.handler.PreprocessorHandler.handle(PreprocessorHandler.java:136)
at org.apache.felix.http.base.internal.whiteboard.WhiteboardManager$2.doFilter(WhiteboardManager.java:1008)
at org.apache.felix.http.base.internal.whiteboard.WhiteboardManager.invokePreprocessors(WhiteboardManager.java:1012)
at org.apache.felix.http.base.internal.dispatch.Dispatcher.dispatch(Dispatcher.java:91)
at org.apache.felix.http.base.internal.dispatch.DispatcherServlet.service(DispatcherServlet.java:49)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:873)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:542)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1701)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1345)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1668)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1247)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:220)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:502)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:370)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:267)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:117)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:333)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:310)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:168)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:126)
at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:366)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683)
at java.lang.Thread.run(Thread.java:748)
</pre>
</body>
</html>
</code></pre>
<p>I founded a similar issue, but with another agent:
<a href="https://discuss.elastic.co/t/apm-java-agent-startup-error-with-adobe-experience-manager/153451" rel="nofollow noreferrer">https://discuss.elastic.co/t/apm-java-agent-startup-error-with-adobe-experience-manager/153451</a></p>
<p>As mentioned in that issue I trying to pass sling.bootdelegation parameter via the command line ("-Dsling.bootdelegation.com.cavisson=com.cavisson.* ") but without luck.</p>
<p>Also, AEM successfully started without a javaagent option ...</p>
| 3 | 2,662 |
TensorFlow batch tensors with different shapes
|
<p>I am studying Neural Network and I have encountered what is probably a silly problem which I can't figure out. For my first ever network, I have to create a flower image classifier in Keras and TensorFlow using the <a href="https://www.tensorflow.org/datasets/catalog/oxford_flowers102" rel="nofollow noreferrer">oxford_flowers102</a> and the MobileNet pre-trained model from TensorFlow Hub.</p>
<p>The issue seems to be that the images are not re-sized to (224,224,3), but they keep their original shapes which are different from one and other. However, according to my class material, my re-sizing code is correct so I don't understand what is going on and what I am doing wrong.</p>
<p>Thank you very much for all your help.</p>
<pre><code># LOADING
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)
training_set, testing_set, validation_set = dataset['train'], dataset['test'],dataset['validation']
# PROCESSING AND BATCHES
def normalize(img, lbl):
img = tf.cast(img, tf.float32)
img = tf.image.resize(img, size=(224,224))
img /= 255
return img, lbl
batch_size = 64
training_batches = training_set.cache().shuffle(train_examples//4).batch(batch_size).map(normalize).prefetch(1)
validation_batches = validation_set.cache().batch(batch_size).map(normalize).prefetch(1)
testing_batches = testing_set.cache().batch(batch_size).map(normalize).prefetch(1)
# BUILDING THE NETWORK
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
mobile_net = hub.KerasLayer(URL, input_shape=(224, 224,3))
mobile_net.trainable = False
skynet = tf.keras.Sequential([
mobile_net,
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_classes, activation= 'softmax')
])
# TRAINING THE NETWORK
skynet.compile(optimizer='adam', loss= 'sparse_categorical_crossentropy', metrics=['accuracy'])
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
Epochss = 25
history = skynet.fit(training_batches,
epochs= Epochss,
validation_data=validation_set,
callbacks=[early_stopping])
ERROR:
InvalidArgumentError: Cannot batch tensors with different shapes in component 0. First element had shape [590,501,3] and element 1 had shape [500,752,3].
[[node IteratorGetNext (defined at /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:1751) ]] [Op:__inference_distributed_function_18246]
Function call stack:
distributed_function
</code></pre>
| 3 | 1,039 |
How to I make my php include stay at the bottom?
|
<p>So I've been editing my website and recently tried to upload the basics (index, css and some other pages) but when I have looked at one of the pages, the actual article overlaps the bottom div and I don't know how its done that.</p>
<p>Here is the css for the bottom:</p>
<pre><code>div#bottom {
background-color: #2C292B;
width: 100%;
height: 120px;
color: #888888;
padding-top: 40px;
padding-bottom: 40px;
}
div#copyright {
background-color: #1F1D1E;
width: 100%;
height: 45px;
font-weight: bold;
}
</code></pre>
<p>And here is the code for the index: </p>
<pre><code><script type="text/javascript">
if (location.pathname.substr(0, 3) !== "/m/" && screen.width <= 720) {
location.href = "/m" + location.pathname;
}
</script>
<a name="top"></a>
<!doctype html>
<html>
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml" lang="en-gb">
<head>
<title>michae|dylanEdwards - artistic blog</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link href = "_includes/style.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="stylesheet" type="text/css" href="_includes/style.css" />
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="_includes/slider/style.css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:image" content="http://www.michaeldylanedwards.co.uk/admin/uploads/op-image.png"/>
<meta property="og:description" content="michae|dylanEdwards is a contemporary British Art and Design Student at Liverpool John Moores University. In which creates works in which provide a sociological question in regards to how society sees itself. Also by means of design."/>
<meta name="description" content="michae|dylanEdwards is a contemporary British Art and Design Student at Liverpool John Moores University. In which creates works in which provide a sociological question in regards to how society sees itself. Also by means of design.">
<meta name="keywords" content="art blog mickword michaeldylanedwards michae|dylanEdwards michael dylan edwards liverpool john moores university sociological history"/>
<script>var SITE_URL = 'http://wowslider.com/';</script>
<script type="text/javascript" src="_includes/slider/jquery.js"></script>
<script type="text/javascript" src="_includes/slider/a.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-25854704-1']);
_gaq.push(['_setDomainName', '.wowslider.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_setAllowHash', false]);
if(document.cookie.match("(^|;\\s)__utma") && !/utmcsr=\(direct\)/.test(unescape(document.cookie))) {
_gaq.push(
['_setReferrerOverride', ''],
['_setCampNameKey', 'aaan'],
['_setCampMediumKey', 'aaam'],
['_setCampSourceKey', 'aaas'],
['_setCampTermKey', 'aaat'],
['_setCampContentKey', 'aaac'],
['_setCampCIdKey', 'aaaci']
)
}
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<center>
<?php include("_includes/header.html"); ?>
<div id="frontad">
<div id="wowslider-container1">
<div class="ws_images">
<ul>
<li>
<a href="link">
<img src="_includes/slider/adverts/1.png" alt="" title="News Title Number #1" id="wows1_0"/>
</a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
</li>
<li>
<a href="link">
<img src="_includes/slider/adverts/2.png" alt="" title="News Title Number #2" id="wows1_1" />
</a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
</li>
<li>
<a href="link">
<img src="_includes/slider/adverts/3.png" alt="" title="News Title Number #3" id="wows1_2"/>
</a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
</li>
<li>
<a href="link">
<img src="_includes/slider/adverts/4.png" alt="" title="News Title Number #4" id="wows1_3"/>
</a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
</li>
</ul>
</div>
</div>
<script type="text/javascript" src="_includes/slider/wowslider.js"></script>
<script type="text/javascript" src="_includes/slider/script.js"></script>
</div>
<div id="themespacer"></div>
<div id="frontnews">
<div id="newsleft">
<?PHP
$category = "6";
$template = "New_homepage";
$number = "3";
include("admin/show_news.php");
?>
</div>
<div id="newsright">
Google Adsense Here
</div>
</div>
<?php include("_includes/bottom.html"); ?>
</center>
</body>
</html>
</code></pre>
<p>And here is the webpage itself:</p>
<p><a href="http://www.michaeldylanedwards.co.uk/archives.php?id=1397654579" rel="nofollow">http://www.michaeldylanedwards.co.uk/archives.php?id=1397654579</a></p>
<p>When I want it to look like this:</p>
<p><a href="http://www.michaeldylanedwards.co.uk/" rel="nofollow">http://www.michaeldylanedwards.co.uk/</a></p>
<p>Any help would be amazing!</p>
<p>Edit: Here is the bottom.html too!</p>
<pre><code><div id="themespacer"></div>
<div id="bottom">
<div id="bottomcontent">
<div id="bottomleft">
<div id="bottomheader1">
SITE LINKS.
</div>
<img src="_img/spacer.png" width="0" height="25"/>
<a href="index.php">Homepage</a>
<br>
<img src="_img/spacer.png" width="0" height="15"/>
<a href="blog.php">Blog</a>
<br>
<img src="_img/spacer.png" width="0" height="15"/>
<a href="blog.php?id=1436143282">About Us</a>
<br>
<img src="_img/spacer.png" width="0" height="15"/>
<a href="blog.php?id=1436145183">Contact</a>
<br>
<img src="_img/spacer.png" width="0" height="15"/>
<a href="blog.php?id=1436140662">Privacy Policy</a>
</div>
<div id="bottomcenter">
<div id="bottomheader1">
EXTERNAL LINKS.
</div>
<img src="_img/spacer.png" width="0" height="25"/>
<a href="http://www.facebook.com/mickeeART" target="_blank">Facebook</a>
<br>
<img src="_img/spacer.png" width="0" height="15"/>
<a href="http://www.twitter.com/mickeeART" target="_blank">Twitter</a>
<br>
<img src="_img/spacer.png" width="0" height="15"/>
<a href="http://michaeldylanedwards.tumblr.com" target="_blank">Tumblr</a>
<br>
<img src="_img/spacer.png" width="0" height="15"/>
<a href="http://www.instagram.com/mickeehh" target="_blank">Instagram</a>
<br>
<img src="_img/spacer.png" width="0" height="15" />
<a href="http://www.ljmu.ac.uk" target="_blank">Liverpool John Moores University</a>
</div>
<div id="bottomright">
<div id="bottomheader2">
Sign up for the newsletter!
</div>
<br>
Coming Soon...
</div>
</div>
</div>
<div id="copyright">
<div id="copyrightcontent">
<div id="copyrightleft">
COPYRIGHT © 2015 MICHAELDYLANEDWARDS.CO.UK
</div>
<div id="copyrightright">
<a href="#top">
TOP OF PAGE
</a>
</div>
</div>
</div>
</code></pre>
| 3 | 5,613 |
MongoDB View vs Function to abstract query and variable/parameter passed
|
<p>I hate to risk asking a duplicate question, but perhaps this is different from <a href="https://stackoverflow.com/questions/52786830/passing-variables-to-a-mongodb-view">Passing Variables to a MongoDB View</a> which didn't have any clear solution.</p>
<p>Below is a query to find the country for IP Address 16778237. (Outside the scope of this query, there is a formula that turns an IPV4 address into a number.)</p>
<p>I was wondering if we could abstract away this query out of NodeJS code, and make a view, so the view could be called from NodeJS. But the fields ipFrom and ipTo are indexed to get the query to run fast against millions of documents in the collection, so we can't return all the rows to NodeJS and filter there.</p>
<p>In MSSQL maybe this would have to be a stored procedure, instead of a view. Just trying to learn what is possible in MongoDB. I know there are functions, which are written in JavaScript. Is that where I need to look?</p>
<pre><code>db['ip2Locations'].aggregate(
{
$match:
{
$and: [
{
"ipFrom": {
$lte: 16778237
}
},
{
"ipTo": {
$gte: 16778237
}
},
{
"active": true
}
],
$comment: "where 16778237 between startIPRange and stopIPRange and the row is 'Active',sort by createdDateTime, limit to the top 1 row, and return the country"
}
},
{
$sort:
{
'createdDateTime': - 1
}
},
{
$project:
{
'countryCode': 1
}
},
{
$limit: 1
}
)
</code></pre>
<p>Part 2 - after more research and experimenting, I found this is possible and runs with success, but then see trying to make a view below this query.</p>
<pre><code>var ipaddr = 16778237
db['ip2Locations'].aggregate(
{
$match:
{
$and: [
{
"ipFrom": {
$lte: ipaddr
}
},
{
"ipTo": {
$gte: ipaddr
}
},
{
"active": true
}
],
$comment: "where 16778237 between startIPRange and stopIPRange and the row is 'Active',sort by createdDateTime, limit to the top 1 row, and return the country"
}
},
{
$sort:
{
'createdDateTime': - 1
}
},
{
$project:
{
'countryCode': 1
}
},
{
$limit: 1
}
)
</code></pre>
<p>If I try to create a view with a "var" in it, like this;</p>
<p>db.createView("ip2Locations_vw-lookupcountryfromip","ip2Locations",[
var ipaddr = 16778237
db['ip2Locations'].aggregate(</p>
<p>I get error:</p>
<pre><code>[Error] SyntaxError: expected expression, got keyword 'var'
</code></pre>
<p>In the link I provided above, I think the guy was trying to figure how the $$user-variables work (no example here: <a href="https://docs.mongodb.com/manual/reference/aggregation-variables/" rel="nofollow noreferrer">https://docs.mongodb.com/manual/reference/aggregation-variables/</a>). That page refers to $let, but never shows how the two work together. I found one example here: <a href="https://www.tutorialspoint.com/mongodb-query-to-set-user-defined-variable-into-query" rel="nofollow noreferrer">https://www.tutorialspoint.com/mongodb-query-to-set-user-defined-variable-into-query</a> on variables, but not $$variables. I'm</p>
<p>db.createView("ip2Locations_vw-lookupcountryfromip","ip2Locations",[
db['ip2Locations'].aggregate(
...etc...
"ipFrom": {
$lte: $$ipaddr
}</p>
<p>I tried ipaddr, $ipaddr, and $$ipaddr, and they all give a variation of this error:</p>
<pre><code>[Error] ReferenceError: $ipaddr is not defined
</code></pre>
<p>In a perfect world, one would be able to do something like:</p>
<pre><code> get['ip2Locations_vw-lookupcountryfromip'].find({$let: {'ipaddr': 16778237})
</code></pre>
<p>or similar.</p>
<p>I'm getting that it's possible with Javascript stored in MongoDB (<a href="https://stackoverflow.com/questions/48136206/how-to-use-variables-in-mongodb-query">How to use variables in MongoDB query?</a>), but I'll have to re-read that; seems like some blogs were warning against it.</p>
<p>I have yet to find a working example using $$user-variables, still looking.</p>
| 3 | 2,184 |
JQueryUI datepicker is not setting/posting the value of the textbox after a date is selected
|
<p>The textbox starts with a value of 1/1/0001, which I am assuming is the default starting date for a new datetime. The issue is that after a date is selected from the datepicker menu, the value on the HTML element is never changed and 1/1/0001 gets posted to the controller after the form is submitted. The text within the textbox is changed, but when using the browser dev tools the value is still 1/1/0001.</p>
<p><strong>HTML</strong></p>
<pre><code><div class="row col-12 formdatepicker">
<input asp-for="StartDate" type="text" class="form-control" id="startdatepicker" />
<span style="margin-left: 8px; margin-right: 8px; padding-top: 5px;">to</span>
<input asp-for="EndDate" type="text" class="form-control" id="enddatepicker" />
</div>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>$(document).ready(function () {
$("#startdatepicker").datepicker({
onSelect: function () {
alert($('#startdatepicker').val());
}
});
$("#enddatepicker").datepicker();
var data = $('form').serialize();
var dataType = 'application/x-www-form-urlencoded; charset=utf-8';
$(function () {
$('#submit').on('click', function (evt) {
console.log('Submitting form...');
console.log(data);
evt.preventDefault();
//Ajax form post
$.ajax({
type: 'POST',
data: data,
contentType: dataType,
url: '@Url.Action("Daily","Reports")',
success: function (data) {
if (data.success) {
alert("Data Success");
} else {
console.log(data);
//Toggle the error modal and display error messages
$('#errorsModal').modal('toggle');
//Add <br> tags when there is a linebreak in the string. This will add the line breaks into the HTML.
$('#errorsModal .modal-body p').html(data.message.replace(/(?:\r\n|\r|\n)/g, '<br>'));
}
}
});
});
});
});
</code></pre>
<p>The <code>.datepicker()</code> initializations are working correctly because the datepicker menu's are appearing when the textbox is clicked. The onSelect alert never appears though when the value is changed. </p>
| 3 | 1,123 |
My activity keeps force closing because of this error
|
<p>My activity keeps force closing because of this class exception</p>
<pre><code> 07-02 01:24:59.244: ERROR/AndroidRuntime(660):
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fttech.collection/com.fttech.collection.book_list}:
java.lang.IllegalArgumentException: column '_id' does not exist
</code></pre>
<p>thsi is my class</p>
<pre><code> public class bookDbHelper{
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "books";
private static final int DATABASE_VERSION = 1;
public static final String KEY_BOOKTITLE = "title";
public static final String KEY_AUTHOR = "author";
public static final String KEY_ISBN = "isbn";
public static final String KEY_RATING = "rating";
public static final String KEY_ROWID = "_ID";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
" create table " + DATABASE_TABLE + " ("
+ KEY_ROWID + " integer primary key autoincrement, "
+ KEY_BOOKTITLE + " text not null, "
+ KEY_AUTHOR + " text not null, "
+ KEY_ISBN + " text not null, "
+ KEY_RATING + " text not null);";
private final Context mCtx;
public bookDbHelper(Context ctx){
this.mCtx = ctx;
}
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
public bookDbHelper open()throws SQLException{
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
mDbHelper.close();
}
public long addBook(String book_name, String author, String isbn, String rating){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_BOOKTITLE, book_name);
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_ISBN, isbn);
initialValues.put(KEY_RATING, rating);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean DeleteBook(long rowId){
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllBooks(){
return mDb.query(DATABASE_TABLE, new String []{KEY_BOOKTITLE, KEY_AUTHOR, KEY_ISBN, KEY_RATING, KEY_ROWID}, null, null, null, null, null);
}
public Cursor fetchBook(long rowId)throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_BOOKTITLE, KEY_AUTHOR, KEY_RATING, KEY_ISBN, KEY_ROWID}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateBooks(long rowId, String book_name, String author, String rating, String isbn){
ContentValues args = new ContentValues();
args.put(KEY_BOOKTITLE, book_name);
args.put(KEY_AUTHOR, author);
args.put(KEY_ISBN, isbn);
args.put(KEY_RATING, rating);
return
mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) >0;
}
}
</code></pre>
<p>Here is my second class that pulls data from the <code>SQLbase</code></p>
<pre><code>public class book_list extends ListActivity{
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVTY_EDIT = 1;
private bookDbHelper mDbHelper;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.book_list);
mDbHelper = new bookDbHelper(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor booksCursor = mDbHelper.fetchAllBooks();
startManagingCursor(booksCursor);
String [] from = new String[]{bookDbHelper.KEY_BOOKTITLE};
int[] to = new int[]{R.id.text1};
SimpleCursorAdapter books =
new SimpleCursorAdapter(this, R.layout.book_row, booksCursor, from, to);
setListAdapter(books);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, book_edit.class);
i.putExtra(bookDbHelper.KEY_ROWID, id);
startActivityForResult(i, ACTIVTY_EDIT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
}
public class book_list extends ListActivity{
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVTY_EDIT = 1;
private bookDbHelper mDbHelper;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.book_list);
mDbHelper = new bookDbHelper(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor booksCursor = mDbHelper.fetchAllBooks();
startManagingCursor(booksCursor);
String [] from = new String[]{bookDbHelper.KEY_BOOKTITLE};
int[] to = new int[]{R.id.text1};
SimpleCursorAdapter books =
new SimpleCursorAdapter(this, R.layout.book_row, booksCursor, from, to);
setListAdapter(books);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, book_edit.class);
i.putExtra(bookDbHelper.KEY_ROWID, id);
startActivityForResult(i, ACTIVTY_EDIT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
}
</code></pre>
| 3 | 2,754 |
Convert array of types to union of object type
|
<p>Let's say I have these types:</p>
<pre class="lang-js prettyprint-override"><code>type StepA = // ...
type StepB = // ...
type StepC = // ...
type Steps = [StepA, StepB, StepC]
</code></pre>
<p>I want to have an utility type <code>SomeUtilityType<T></code> so that:</p>
<pre class="lang-js prettyprint-override"><code>type StepsCombinations = SomeUtilityType<Steps>
// type StepsCombinations =
// | { step: 0; value: StepA }
// | { step: 1; value: StepB }
// | { step: 2; value: StepC };
</code></pre>
<p>How should I define <code>SomeUtilityType<T></code>?</p>
<p><strong>Edit</strong></p>
<p>If <code>Steps</code> is defined as an object</p>
<pre class="lang-js prettyprint-override"><code>type Steps = {0: StepA, 1: StepB, 2: StepC}
</code></pre>
<p>this utility using <a href="https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types" rel="nofollow noreferrer">Distributive Conditional Types</a> would do the trick (see <a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAysFgIJQLxQERwY9AoUks8YAQqhlmAMJ4HSVXmbEl77j3EDO5A2pYgA0RBCWEMAurnaFKXAPIAjAFYQAxsHIBvAAwAuEUmEBGA5TFQATGeJUAvtLqwA9gFsIAVWABLADbfQABUOAB5cKCgANSgIAA94ADsAEx4tKF5vZLiDBIBXV0UIACcJA1yEgGsE5wB3BKg7QXCoQJj4iGSeCogQZwAzKPJu3oHI3AA+cla4xJSocqrahOaAfig0rmIDQIBuKAA3AENfXIgDSN5AiT2HCJyIfeKdxw5DLio3RUzDn2cEnjQMDcnh8-iCoTkSlUGnGQA" rel="nofollow noreferrer">playground</a>):</p>
<pre class="lang-js prettyprint-override"><code>type SomeUtilityType<
V extends { [index: number]: unknown },
T extends keyof V = keyof V
> = T extends unknown
? { step: T; value: V[T]; }
: never;
</code></pre>
<p>But I would much prefer avoid defining an object with superfluous keys <code>0, 1 , 2...</code>.</p>
<p>I think I could use the above type definition of <code>SomeUtilityType</code> if there were some way to get an union of all indexes in the array, like <code>Indexes<Steps> // --> 0 | 1 | 2</code></p>
<p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAysFgIJQLxQERwY9AoUks8YAQqhlmAMJ4HSVXmbEl77j3EDO5A2pYgA0RBCWEMAurnaFKXAPIAjAFYQAxsHIBvAAwAuEUmEBGA5TFQATGeJUAvtLqwA9gFsIAVWABLADbfQABUOAB5cKCgANSgIAA94ADsAEx4tKF5vZLiDBIBXV0UIACcJA1yEgGsE5wB3BKg7QXCoQJj4iGSeCogQZwAzKPJu3oHI3AA+cla4xJSocqrahOaAfig0rmIDQIBuKAA3AENfXIgDSN5AiT2HCJyIfeKdxw5DLio3RUzDn2cEnjQMDcnh8-iCoTkSlUGnGQA" rel="nofollow noreferrer">Playground Link</a></p>
| 3 | 1,131 |
C# WPF App silently crashes if I use "open with"
|
<p>I am making a text editor in C# WPF. After publishing the project to a folder, I can double-click the .exe, it runs fine, and I can load files using my Open (CTRL+O) function perfectly fine.</p>
<p>I want to use <strong>Open with > Choose another app > More apps > Look for another app on this PC</strong>
(I'm not worrying about file associations yet - during development this is fine)</p>
<p>Here's the problem - no matter what I do to my code, I can't get my app to do anything useful when I use this method to open it. What happens is it brings up a randomly sized white window and looks like it's busy - after 2 seconds it closes itself. The name of the window is "%PathOfTheFileIOpened% - KuroNote", which seems to be automatic.</p>
<p><em>App.xaml</em></p>
<pre><code><Application x:Class="KuroNote.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:KuroNote"
Startup="Application_Startup"
ShutdownMode="OnMainWindowClose">
<Application.Resources>
</Application.Resources>
</Application>
</code></pre>
<p><em>App.xaml.cs</em></p>
<pre><code>namespace KuroNote
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
MessageBox.Show("test");
foreach (string s in e.Args)
{
MessageBox.Show(s);
}
}
}
}
</code></pre>
<p>As you can see, I removed all the useful code to try and get it to do SOMETHING - I'm not even opening the main window, I just want it to output its command line arguments. When I use the "Look for another app on this PC" method, I don't even get the "test" message box, like you see is written above.</p>
<p>As you can see from <a href="https://i.stack.imgur.com/Ailkx.png" rel="nofollow noreferrer">this screenshot of the project properties,</a> the startup object is also set to be the app.</p>
<hr />
<p>I thought it might be permissions-related, but the executable and the file to be opened are never in protected administrator-only areas.</p>
<p>I've done tests before while debugging, retrieving command line arguments set in project properties > debug tab > "application arguments:", and those are returned just fine. Something seems to be different about opening using the "Look for another app on this PC" method, it's like it's doing more than just launching the app with a command line argument with the filepath.</p>
<p>Am I missing some kind of flag in App.xaml that enables "Open with" functionality?</p>
<hr />
<p>It's a purely offline application, not a web app, and the files I get after publishing are just "KuroNote.deps.json", "KuroNote.dll", "KuroNote.exe", "KuroNote.pdb" and "KuroNote.runtimeconfig.json", no ".application" files that it sounds like "ClickOnce" uses. If I search for "ClickOnce" inside visual studio, it says I can install it, but it doesn't sound like it's already installed. Unless there's some hidden "use ClickOnce" setting that I need to disable?</p>
| 3 | 1,249 |
Upload files in vb.net
|
<p>I have a code in vb.net (as shown below) in which it ask to upload a file after the selection of yes button. On checking No button, it doesn't ask us to upload a file as shown below in the images. </p>
<p>************************************************VB Code****************************************************** </p>
<pre><code> Protected Sub rblOrgChart_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rblOrgChart.SelectedIndexChanged
ruOrgChart.Visible = False
hlOrgChart.Visible = False
' btnOrgChart.Visible = rblOrgChart.SelectedValue And bolHasWritePermission
hlOrgChart.Visible = rblOrgChart.SelectedValue
If CBool(rblOrgChart.SelectedValue) Then
ruOrgChart.Visible = True
Dim dtFile As DataTable
dtFile = dalClientProfile.GetFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART)
If dtFile.Rows.Count > 0 Then
Dim dr As DataRow = dtFile.Rows(0)
hlOrgChart.NavigateUrl = ruOrgChart.TargetFolder & "/" & dr.Item("FileName")
hlOrgChart.Text = dr.Item("FileName")
hlOrgChart.Visible = True
End If
Else
' If Me.lblOrgChartMissing2.Visible Then Me.lblOrgChartMissing2.Visible = False
End If
End Sub
</code></pre>
<p>The code inside the method <code>btnOrgChart_Click</code> is:</p>
<pre><code>Protected Sub btnOrgChart_Click(sender As Object, e As System.EventArgs) Handles btnOrgChart.Click
Try
'If ruOrgChart.InvalidFiles.Count > 0 Then
' lblOrgChartNotPDF.Visible = True
'Else
' lblOrgChartNotPDF.Visible = False
'End If
'------------------------------------------------------------------
' Q07. HAS WRITTEN ORG. CHART [IAPData..tblReadinessProfile_Question ID=9 ]
'------------------------------------------------------------------
If (rblOrgChart.SelectedValue = 1 And ruOrgChart.UploadedFiles.Count > 0) Then
hlOrgChart.Visible = True
'' ''======' BEGIN NEW CODE --- to upload file to virtual directory
Dim sufile As Telerik.Web.UI.UploadedFile = Nothing
For Each sufile In Me.ruOrgChart.UploadedFiles
' for now upload files on webserver
'If AppSettings.Item("Environment") <> "Prod" Then
remoteName = Request.PhysicalApplicationPath
'Else
'remoteName = AppSettings.Item("UploadRootPath").ToString.Trim()
'End If
Dim strPhysicalFilePath As String = remoteName & AppSettings.Item("FileUploadRootPath").ToString & "\" & dtLicensee.Rows(0).Item("UniqueIdentifier").ToString & "\" & dtOrg.Rows(0).Item("OrgCode").ToString & "\"
CreateFileUploaderLink(remoteName)
If Not Directory.Exists(strPhysicalFilePath) Then
Directory.CreateDirectory(strPhysicalFilePath)
End If
hlOrgChart.NavigateUrl = AppSettings.Item("FileUploadRootPath").ToString & "/" & dtLicensee.Rows(0).Item("UniqueIdentifier").ToString & "/" & dtOrg.Rows(0).Item("OrgCode").ToString & "/" & ruOrgChart.UploadedFiles(0).GetName()
dalClientProfile.SaveFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART, ruOrgChart.UploadedFiles(0).GetName(), strPhysicalFilePath, True)
hlOrgChart.Text = ruOrgChart.UploadedFiles(0).GetName()
Dim NewFileName As String
NewFileName = sufile.GetName()
'If File.Exists(strPhysicalFilePath & NewFileName) Then
' Dim script As String = "alert('" + Me.GetLocalResourceObject("err.fileuploaded.text") + "');"
' ScriptManager.RegisterStartupScript(ruOrgChart, ruOrgChart.GetType(), "clientscript", script, True)
' Exit Sub
'End If
sufile.SaveAs(strPhysicalFilePath & NewFileName, True)
' Cancel the connection
RemoveFileUploaderLink(remoteName)
Next
End If
Catch ex As Exception
Dim oErr As New ErrorLog(ex, "Error in btnOrgChart_Click")
Response.Redirect("~/Error/ErrorPage.aspx?type=Err&ui=" & Request.QueryString("ui"), True)
Exit Sub
End Try
End Sub
</code></pre>
<p><br></p>
<p>**********************************************Images*******************************************************</p>
<p><a href="https://i.stack.imgur.com/zEREd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zEREd.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/bsGre.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bsGre.png" alt="enter image description here"></a></p>
<p>As shown above in the images, on selection of yes it ask us to upload a file.
By default, it always remains No as the value of HasOrgChart is always 0.</p>
<pre><code> rblOrgChart.SelectedValue = IIf(CBool(dtOrg.Rows(0).Item("HasOrgChart")), 1, 0)
</code></pre>
<p><br> </p>
<p>******************************************************HTML*************************************************
<br><br>
The .aspx code belonging to the above <code>images</code> and to the above <code>vb codes</code> are:</p>
<pre><code><div class="grid-c2">
<div>
<asp:UpdatePanel runat="server" ID="Updatepanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="rblOrgChart" EventName="SelectedIndexChanged"/>
</Triggers>
<ContentTemplate>
<asp:RadioButtonList ID="rblOrgChart" runat="server" AutoPostBack="True">
<asp:ListItem ID="rblOrgChartY" runat="server" Value="1" Text="Yes (Please upload the organizational chart as a PDF file)"></asp:ListItem>
<asp:ListItem ID="rblOrgChartN" runat="server" Value="0" Text="No" ></asp:ListItem>
</asp:RadioButtonList>
<div>
<br />
<telerik:RadAsyncUpload ID="ruOrgChart" runat="server" AutoPostBack="true"
HideFileInput="True"
AllowedFileExtensions=".pdf"
OnClientValidationFailed="validationFailed"
onclientfileuploaded="ruOrgChart_Fileuploaded"
MaxFileInputsCount="1"
InitialFileInputsCount="1"
MaxFileSize="5000000"
/>
<div class="fileLink">
<asp:HyperLink runat="server" ID="hlOrgChart" Target="_blank" Visible="false"
Text=""></asp:HyperLink>
</div>
</div>
<br />
<div style="display:none">
<asp:linkButton ID="btnOrgChart" CssClass="btnUpload" runat="server" Text="" />
</div>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</code></pre>
<p>I am wondering what changes do I need to make in the vb.net and .aspx codes so that instead of Yes and No radio button, there is only select button which ask us directly to upload a file with no yes/no options. </p>
| 3 | 3,446 |
Why does strip.white work when trimws does not?
|
<p>I am reading in a .csv that NA observations are recorded as "- ". </p>
<pre><code>returns <-read.csv("~/R/ADFG_Obtained_AKReturns.csv", stringsAsFactors = FALSE)
str(returns)
'data.frame': 4222 obs. of 15 variables:
$ Year : int 1975 1976 1977 1977 1977 1977 1977 1978 1978 1978 ...
$ Region : chr "Kodiak & AK Peninsula" "Kodiak & AK Peninsula" "Kodiak & AK Peninsula" "Prince William Sound" ...
$ Hatchery : chr "Kitoi Bay" "Kitoi Bay" "Kitoi Bay" "AF Koernig"
...
$ Project : chr "Kitoi Bay" "Kitoi Bay" "Kitoi Bay" "Port San
Juan" ...
$ Species : chr "Pink" "Pink" "Pink" "Pink" ...
$ Seine : chr " - " " - " " - " " 2,000 " ...
$ Gillnet : chr " - " " - " " - " " - " ...
$ Troll : chr " - " " - " " - " " - " ...
$ Other.Commercial: chr " - " " - " " - " " - " ...
$ Sport : chr " - " " - " " - " " - " ...
$ PersUse : chr " - " " - " " - " " - " ...
$ Subsis : chr " - " " - " " - " " - " ...
$ Brood : chr " 5,800 " " 8,000 " " - " " 21,300 " ...
$ CR.catch : chr " - " " - " " - " " 15,545 " ...
$ Other : chr " - " " - " " 18,500 " " - " ...
</code></pre>
<p>When I read in the .csv then attempt to trimws, the white spaces are not removed (the df does not change at all. This was first attempted by the suggestion of my colleagues' reformatting process). Note that in the below code I used "both", but I've attempted "right" with the same results. </p>
<pre><code>returns <-read.csv("~/R/ADFG_Obtained_AKReturns.csv", stringsAsFactors = FALSE)
returns <- trimws(returns, which = c("both"))
str(returns)
'data.frame': 4222 obs. of 15 variables:
$ Year : int 1975 1976 1977 1977 1977 1977 1977 1978 1978
1978 ...
$ Region : chr "Kodiak & AK Peninsula" "Kodiak & AK
Peninsula" "Kodiak & AK Peninsula" "Prince William Sound" ...
$ Hatchery : chr "Kitoi Bay" "Kitoi Bay" "Kitoi Bay" "AF
Koernig" ...
$ Project : chr "Kitoi Bay" "Kitoi Bay" "Kitoi Bay" "Port San
Juan" ...
$ Species : chr "Pink" "Pink" "Pink" "Pink" ...
$ Seine : chr " - " " - " " - " " 2,000 " ...
$ Gillnet : chr " - " " - " " - " " - " ...
$ Troll : chr " - " " - " " - " " - " ...
$ Other.Commercial: chr " - " " - " " - " " - " ...
$ Sport : chr " - " " - " " - " " - " ...
$ PersUse : chr " - " " - " " - " " - " ...
$ Subsis : chr " - " " - " " - " " - " ...
$ Brood : chr " 5,800 " " 8,000 " " - " " 21,300 " ...
$ CR.catch : chr " - " " - " " - " " 15,545 " ...
$ Other : chr " - " " - " " 18,500 " " - " ...
</code></pre>
<p>If I use strip.white within the read.csv call, the white spaces are removed. I'm assuming this has something to do with how read.csv works, but looking through the appropriate <a href="http://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html" rel="nofollow noreferrer">R documentation</a> I still don't understand why this is occurring. </p>
<pre><code>returns <-read.csv("~/R/ADFG_Obtained_AKReturns.csv", stringsAsFactors = FALSE, strip.white = TRUE)
str(returns)
'data.frame': 4222 obs. of 15 variables:
$ Year : int 1975 1976 1977 1977 1977 1977 1977 1978 1978
1978 ...
$ Region : chr "Kodiak & AK Peninsula" "Kodiak & AK
Peninsula" "Kodiak & AK Peninsula" "Prince William Sound" ...
$ Hatchery : chr "Kitoi Bay" "Kitoi Bay" "Kitoi Bay" "AF
Koernig" ...
$ Project : chr "Kitoi Bay" "Kitoi Bay" "Kitoi Bay" "Port San
Juan" ...
$ Species : chr "Pink" "Pink" "Pink" "Pink" ...
$ Seine : chr "-" "-" "-" " 2,000 " ...
$ Gillnet : chr "-" "-" "-" "-" ...
$ Troll : chr "-" "-" "-" "-" ...
$ Other.Commercial: chr "-" "-" "-" "-" ...
$ Sport : chr "-" "-" "-" "-" ...
$ PersUse : chr "-" "-" "-" "-" ...
$ Subsis : chr "-" "-" "-" "-" ...
$ Brood : chr " 5,800 " " 8,000 " "-" " 21,300 " ...
$ CR.catch : chr "-" "-" "-" " 15,545 " ...
$ Other : chr "-" "-" " 18,500 " "-" ...
</code></pre>
<p>So adding the strip.white call does exactly what I would like for the blank ("-") cells, I just don't understand why; and why does trimws not work in this case? </p>
<p>Also, are there still whitespaces remaining on the observations that are numbers? </p>
<pre><code>$ Seine : chr "-" "-" "-" " 2,000 " ...
</code></pre>
<p>For my next step, I will be changing the type from character to numeric with the following code, but would appreciate any suggestions on how to do this for all columns Seine:Other (cols 6:15 in my df). </p>
<pre><code>returns$Seine <- as.numeric(gsub(",","",returns$Seine))
$ Seine : num NA NA NA 2000 NA NA NA NA NA NA ...
</code></pre>
<p>(FYI, this is the first question I have asked.) </p>
| 3 | 2,301 |
boost::spirit and strict_real_policies fails to parse a too long integer
|
<p>I've to deal with really long integers in text format -- so long that they won't fit into an 32bit int.
I need to parse such text into a </p>
<pre><code>boost::variant<int, double>.
</code></pre>
<p>So if there is a long integer to big for an integer it needs to go into a double. See the example below. It does not parse the name value pair </p>
<pre><code>MUESR1 = 411100000000000.
</code></pre>
<p>How can this be fixed?</p>
<pre><code>#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <iterator>
namespace qi = boost::spirit::qi;
namespace spirit = boost::spirit;
namespace ascii = boost::spirit::ascii;
typedef boost::variant<int, double> VALUE;
typedef std::pair<std::string, VALUE> PAIR;
typedef std::map<std::string, VALUE> PAIRS;
template<typename Iterator>
struct parameters:qi::grammar<Iterator, PAIRS(), ascii::space_type>
{
qi::rule<Iterator, std::string(), ascii::space_type> m_sName;
qi::rule<Iterator, VALUE(), ascii::space_type> m_sValue;
qi::rule<Iterator, PAIR(), ascii::space_type> m_sNameValue;
qi::rule<Iterator, PAIRS(), ascii::space_type> m_sRoot;
qi::real_parser<double, qi::strict_real_policies<double> > m_sReal;
parameters(void)
:parameters::base_type(m_sRoot)
{ m_sName %= qi::lexeme[qi::char_("a-zA-Z_") >> *qi::char_("a-zA-z_0-9")];
m_sValue %= m_sReal | spirit::int_;
m_sNameValue %= m_sName >> qi::lit('=') >> m_sValue >> -qi::lit('\n');
m_sRoot %= m_sNameValue >> *m_sNameValue;
}
};
int main(int, char**)
{
static const char s_ap[] = "\
MUEPH1 = 7.014158 MUEPHW= -0.3 MUEPWP = 0.23 MUEPHL= -0.72 MUEPLP = 3.4 MUEPHS = 2.976E-07 MUEPSP = 5 VTMP= -1.8463 WVTH0= -1.01558 MUESR0 = 0.01256478438899837 MUESR1 = 411100000000000\n\
MUEPHW2 = 0 MUEPWP2 = 1\n";
parameters<const char*> sGrammar;
const char *pIter = s_ap;
const char *const pEnd = s_ap + sizeof s_ap - 1;
PAIRS sValues;
if (phrase_parse(pIter, pEnd, sGrammar, boost::spirit::ascii::space, sValues) && pIter == pEnd)
{ std::cerr << "parsing successful!" << std::endl;
for (const auto &r : sValues)
std::cout << r.first << "=" << std::scientific << r.second << std::endl;
}
else
{ std::cerr << "parsing failed!" << std::endl;
std::cerr << pIter << std::endl;
}
}
</code></pre>
| 3 | 1,200 |
How to clear Select Box old Data & Fill with new Data on Selection Javascript?
|
<p>I have 2 drop downs, this thing here is when user select BMW i want to fill data 1,2,3,4,5 & when he selects Volvo i want to display 5,6,7,8,9. Data is getting populated in second drop down but i can see old data as well & as many times i click the list is getting increased. I want to show only specific data on selection & data should also not get repeated. below is my approach.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("mySelect").value;
if(x=='BMW'){
var select = document.getElementById("participant");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
if(x=='Volvo'){
var select = document.getElementById("participant");
var options = ["6", "7", "8", "9", "10"];
console.log(options)
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
}
</script>
</head>
<body>
<select id="mySelect" onchange="myFunction()">
<option value="" disabled selected>Select Type</option>
<option value="BMW">BMW</option>
<option value="Volvo">Volvo</option>
</select>
<br><br>
<select id="participant">
<option>select</option>
</select>
</body>
</html>
</code></pre>
| 3 | 1,083 |
Post form always returning null
|
<p>I have an application in asp .net mvc 4 as follows:</p>
<p><strong>1.ProductsController.cs</strong></p>
<pre><code>namespace MvcApplication2.Controllers
{
public class ProductsController : Controller
{
//
// GET: /Products/
[HttpGet]
public ActionResult Products()
{
List<Product> prList = new List<Product>();
Product p1 = new Product();
p1.ProductName = "J & J";
p1.Price = 40;
p1.Ratings = 5;
prList.Add(p1);
Product p2 = new Product();
p2.ProductName = "Himalaya";
p2.Price = 20;
p2.Ratings = 2;
prList.Add(p2);
return View(prList);
}
[HttpPost]
public ActionResult Products(FormCollection prList,List<MvcApplication2.Models.Product> fg)
{
return View(prList);
}
}
}
</code></pre>
<p><strong>2. ProductList.cs</strong></p>
<pre><code>namespace MvcApplication2.Models
{
public class Product
{
public string ProductName { get; set; }
public int Price { get; set; }
public int Ratings { get; set; }
}
}
</code></pre>
<p><strong>3. Products.cshtml</strong></p>
<pre><code>@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Products</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery-3.2.1.min.js"></script>
</head>
@model IEnumerable<MvcApplication2.Models.Product>
@using (@Html.BeginForm("Products", "Products", FormMethod.Post))
{
<body>
<div style="width:100%;height:100%;position: relative ">
<div style="width:100%;top:0px;height:40px;position:relative;background-color:purple">
<input type="submit" value="Sort price" style="float : right;width:30px;" id="SearchId" />
@Html.TextBox("Search Box", null, new { @style = "float:right;width:80px "});
<input type="submit" value="submit" />
</div>
<div id="tableDiv">
<table id="tableId">
<tr>
<th>Name</th>
<th>Price in Rs.</th>
<th>Ratings</th>
</tr>
@foreach (var drawing in Model)
{
<tr>
<td>@drawing.ProductName</td>
<td>@drawing.Price</td>
<td>@drawing.Ratings</td>
</tr>
}
</table>
</div>
</div>
</body>
}
</html>
</code></pre>
<p>Whenever I navigate to <em><a href="http://localhost:5858/Products/Products" rel="nofollow noreferrer">http://localhost:5858/Products/Products</a></em> and click and on submit , the contol comes to <code>[HttpPost]</code> in Products methods, but the model is always empty .</p>
<p>What is it that I am missing here?I am expecting the same model to be returned when the page was loaded , why is it that the model is becoming empty?</p>
| 3 | 1,653 |
Unable to create Generic CustomAttributeData properly when using programatically generated Enum
|
<p>I am trying to source a PropertyGrid with a dynamically generated object.</p>
<p>For combo selections on this property grid, I have built a TypeConverter (where T is an enum, defining the list of options):</p>
<pre><code> public class TypedConverter<T> : StringConverter where T : struct, IConvertible
{
...
public override System.ComponentModel.TypeConverter.StandardValuesCollection
GetStandardValues(ITypeDescriptorContext context)
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
string[] values = Enum.GetValues(typeof(T)).OfType<object>().Select(o => o.ToString()).ToArray();
return new StandardValuesCollection(values);
}
}
</code></pre>
<p>I can then add a custom attribute to the property, referencing this TypeConverter, as below (typedConverterGenericType is the the type of TypedConverter with an enum generic argument)</p>
<pre><code>CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(typeof(TypeConverterAttribute).GetConstructor(new Type[] { typeof(Type) }), new Type[] { typedConverterGenericType });
propertyBuilder.SetCustomAttribute(attributeBuilder);
</code></pre>
<p>This works <strong>great</strong>, as long as the Enum in question is hardcoded: <code>AddTypeConverterAttribute(propertyBuilder, typeof(TypedConverter<Fred>));</code>. In the debugger, the attribute on the property gives me <code>{[System.ComponentModel.TypeConverterAttribute( ...</code>.</p>
<p>However, when I use a dynamically built enum (that I have determined is generated properly in reflection) does not work:</p>
<pre><code> Type enumType = enumBuilder.CreateType();//This generates a proper enum, as I have determined in reflection
Type converterType = typeof(TypedConverter<>);
Type typedConverterType = converterType.MakeGenericType(enumType);
AddTypeConverterAttribute(propertyBuilder, typedConverterType);
</code></pre>
<p>In the debugger, the attribute on the property now gives me <code>{System.Reflection.CustomAttributeData}</code>, and drilling into this, I have an error on the ConstructorArguments <code>... Mscorlib_CollectionDebugView<System.Reflection.CustomAttributeData>(type.GetProperties()[1].CustomAttributes).Items[4].ConstructorArguments' threw an exception of type 'System.IO.FileNotFoundException'</code> </p>
<p>What am I doing wrong? How can I get the TypeConverter attribute set properly?</p>
<p><strong>EDIT</strong>: In case someone wants to see how I add the attribute</p>
<pre><code>private void AddTypeConverterAttribute(PropertyBuilder propertyBuilder, Type typedConverterGenericType)
{
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(typeof(TypeConverterAttribute).GetConstructor(new Type[] { typeof(Type) }), new Type[] { typedConverterGenericType });
propertyBuilder.SetCustomAttribute(attributeBuilder);
}
</code></pre>
<p><strong>EDIT2</strong></p>
<p>Testing confirms it is an issue with the dynamically built enum - if I create the generic type with <code>Type typedConverterType = converterType.MakeGenericType(typeof(Fred));</code> it works fine.</p>
<p><strong>EDIT 3</strong></p>
<p>My test project is available <a href="http://purehumbug.com/files/PropertiesExample.zip" rel="nofollow">here</a>. It is reading some JSON from Resouces, and trying to generate a class whose type is described by that JSON. </p>
<p>I am creating an instance of that class (<code>Activator.CreateInstance</code>) that will source a PropertyGrid. To get combo selection on that PropertyGrid, I am creating a Type, with a property attributed with TypedConverter, where T is an enum that describes the values in the combo selection. </p>
<p>This works great for hardcoded enums, but not for programatically generated ones</p>
| 3 | 1,193 |
Python multithreading - writing to file is 10x slower
|
<p>I've been trying to convert a large file with many lines (27 billion) to JSON. Google Compute recommends that I take advantage of multithreading to improve write times. I've converted my code from this:</p>
<pre><code>import json
import progressbar
f = open('output.txt', 'r')
r = open('json.txt', 'w')
import math
num_permutations = (math.factorial(124)/math.factorial((124-5)))
main_bar = progressbar.ProgressBar(maxval=num_permutations, \
widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage(), progressbar.AdaptiveETA()])
main_bar.start()
m = 0
for lines in f:
x = lines[:-1].split(' ')
x = json.dumps(x)
x += '\n'
r.write(x)
m += 1
main_bar.update(m)
</code></pre>
<p>to this:</p>
<pre><code>import json
import progressbar
from Queue import Queue
import threading
q = Queue(maxsize=5)
def worker():
while True:
task = q.get()
r.write(task)
q.task_done()
for i in range(4):
t = threading.Thread(target=worker)
t.daemon = True
t.start()
f = open('output.txt', 'r')
r = open('teams.txt', 'w')
import math
num_permutations = (math.factorial(124)/math.factorial((124-5)))
main_bar = progressbar.ProgressBar(maxval=num_permutations, \
widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage(), progressbar.AdaptiveETA()])
main_bar.start()
m = 0
for lines in f:
x = lines[:-1].split(' ')
x = json.dumps(x)
x += '\n'
q.put(x)
m += 1
main_bar.update(m)
</code></pre>
<p>I've copied the Queue coding pretty much straight from the module manual.</p>
<p>Before, the whole script would take 2 days. Now it is saying 20 days! I'm not quite sure why, could anyone explain this to me?</p>
<p><strong>EDIT:</strong> This could be considered a Python Global Interpreter Lock (GIL) problem, however, I don't think it is so - it is not computationally intensive and is an IO bottleneck problem, from the threading docs:</p>
<blockquote>
<p>If you want your application to make better use of the computational
resources of multi-core machines, you are advised to use
multiprocessing. However, threading is still an appropriate model if
you want to run multiple I/O-bound tasks simultaneously.</p>
</blockquote>
<p>My understanding of this is limited, but I believe this to be the latter, ie. an IO bound task. This was my original thought when I wanted to go for multi-threading in the first place: That the computation was being blocked by IO calls that could be put to a separate thread to allow the computation functions to continue.</p>
<p><strong>FURTHER EDIT:</strong> Perhaps the fact is that I've got an IO block from the INPUT, and that is what is slowing it down. Any ideas on how I could effectively send the 'for' loop to a separate thread? Thanks!</p>
| 3 | 1,024 |
timestamp issue
|
<p>I have some scripts and in the database table I have set the dato to int(25) and timestamp </p>
<p>I have a create topic script and then I create a topic it insert the date and time in the timestamp tabel (dato).</p>
<p>But somehow my comment script will not insert the time :S and its the same stuff I use :S.</p>
<p>Here is my script</p>
<pre><code> if(isset($_POST['opret_kommentar']))
{
$indhold = $_POST['indhold'];
$godkendt = "ja";
$mysql = connect();
$stmt = $mysql->prepare("INSERT INTO forum_kommentare (fk_forum_traad, brugernavn, indhold, dato, godkendt) VALUES (?,?,?,?,?)") or die($mysql->error);
$stmt->bind_param('issis', $traadID, $_SESSION['username'], $indhold, $dato, $godkendt) or die($mysql->error);
$stmt->execute();
$stmt->close();
$svar = mysqli_insert_id($mysql);
header("location: forum.traad.php?traadID=$traadID&kategoriID=$kategoriID&#$svar");
}
</code></pre>
<p>Here is my create topic script so you can see its the same stuff I use :S</p>
<pre><code> if(isset($_POST['send'])) {
$kategoriID = $_GET['kategoriID'];
$overskrift = $_POST['overskrift'];
$indhold = $_POST['indhold'];
$godkendt = "ja";
$mysql = connect();
$stmt = $mysql->prepare("INSERT INTO forum_traad (overskrift, indhold, fk_forum_kategori, brugernavn, dato, godkendt) VALUES (?,?,?,?,?,?)") or die($mysql->error);
$stmt->bind_param('ssisis', $overskrift, $indhold, $kategoriID, $_SESSION['username'], $dato, $godkendt) or die($mysql->error);
$stmt->execute();
$stmt->close();
$traadID = mysqli_insert_id($mysql);
header("location: forum.traad.php?traadID=$traadID&kategoriID=$kategoriID");
}#Lukker isset send
</code></pre>
<p>Here is my SQL</p>
<blockquote>
<p>CREATE TABLE IF NOT EXISTS <code>forum_kommentare</code> ( <code>id</code> int(11) NOT
NULL AUTO_INCREMENT, <code>fk_forum_traad</code> int(11) NOT NULL,<br>
<code>brugernavn</code> text NOT NULL, <code>indhold</code> mediumtext NOT NULL, <code>dato</code>
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP, <code>godkendt</code> varchar(4) NOT NULL DEFAULT 'ja',<br>
PRIMARY KEY (<code>id</code>) ) ENGINE=MyISAM DEFAULT CHARSET=latin1
AUTO_INCREMENT=4 ;</p>
<p>--</p>
<h2>-- Data dump for tabellen <code>forum_kommentare</code></h2>
<hr>
<p>--</p>
<h2>-- Struktur-dump for tabellen <code>forum_traad</code></h2>
<p>CREATE TABLE IF NOT EXISTS <code>forum_traad</code> ( <code>id</code> int(11) NOT NULL
AUTO_INCREMENT, <code>overskrift</code> text NOT NULL, <code>indhold</code> mediumtext
NOT NULL, <code>fk_forum_kategori</code> int(11) NOT NULL, <code>brugernavn</code> text
NOT NULL, <code>dato</code> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP, <code>godkendt</code> varchar(4) NOT NULL DEFAULT
'ja', PRIMARY KEY (<code>id</code>) ) ENGINE=MyISAM DEFAULT CHARSET=latin1
AUTO_INCREMENT=3 ;</p>
<p>--
-- Data dump for tabellen <code>forum_traad</code></p>
</blockquote>
<p>Hope someone can help me :/</p>
| 3 | 1,317 |
MS Access Join sub query
|
<p>I have data in Table2 which I need to use as the key to retrieve information in Table1. Table2 contains information about the part number including its plant of manufacture and production process. I need to pass to Table2 the warehouse (plant) and the part number and have it pass back to me, the production plant id and the process id. I've attempted with the SQL below but its throws a syntax error that simply says "Syntax error in JOIN operation". I'd rather not have to split into separate sql statements :/</p>
<pre><code>SELECT
T1.MFRFMR03 AS Seq,
T1.MFRFMR04 AS [Desc],
T1.MFRFMR0S AS M2M,
T1.MFRFMR0Q AS Std_Labor,
T1.MFRFMR0M AS Std_Setup,
T1.MFRFMR0R AS Std_Units
FROM
T1 LEFT JOIN
(
SELECT
T2.MAJRTEPLT,
T2.MAJRTEID
FROM
T2
WHERE
(
((T2.PLT)=[Enter Plant Number])
AND
((T2.ITMID)=ucase$([Enter Part Number]))
)
) ON ((T1.MFRFMR01)=(T2.MAJRTEPLT)) AND ((T1.MFRFMR02)=(T2.MAJRTEID))
WHERE
(
((T1.MFRFMR0Q)<>0)
AND
((T1.MFRFMR0I)<>'S')
AND
((T1.MFRFMR0G)=0)
OR
((T1.MFRFMR0G)=99999)
AND
(
((T1.MFRFMR01)=(T2.MAJRTEPLT))
AND
((T1.MFRFMR02)=(T2.MAJRTEID))
EXISTS IN
)
)
ORDER BY
T1.MFRFMR03;
</code></pre>
| 3 | 1,055 |
jquery duplicating dynamically created content
|
<p>im building a phone app using html5, jquery and php and database. I have a messaging system im trying to develope and have an issue with jquery dynamically creating buttons. I have code that creates a message subject div and message content div using details from the database called using ajax and json, I have then created a delete message button that should get the messageid that will allow the user to delete message from the database once read. The present issue is in dynamic creation of the delete button jquery is duplicating the button, so i need to get jquery to just create the button with the id of the message only, then use a jquery ajax function to delete the message. Following is my code and you can view the live process here <a href="http://newberylodge.co.uk/webapp/message.html" rel="nofollow">http://newberylodge.co.uk/webapp/message.html</a></p>
<p><strong>page code</strong></p>
<pre><code><link href="styles/pages.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {//READY FUNC
$.getJSON("http://newberylodge.co.uk/webapp/includes/messageRetrieve.php",function(data) {//JSON
$.each(data, function(key, val) {//iterate each data
var id = val.id;
var messageId = val.messageId;
var messageSubject = val.messageSubject;
var messageContent = val.messageDetail;
$('#serverData').append('<div id="' + id + '" class="messageAlert">' + messageSubject + '</div>');
$('#serverData').append('<div id="' + messageId + '" class="messageContent">' + messageContent + '</div>');
$('.messageContent').append('<input id="' + messageId + '" type="button" class="deleteButton" value="Delete Message" />');
});//iterate each data
});//JSON
});//READY FUNC
</script>
</head>
<body class="body">
<div class="top">
<div class="logoSmall"></div>
<a href="menu.html"><div class="menuIcon"></div></a>
</div>
<div class="pageBan3"></div>
<div id="whiteBox" class="whiteBox">
<div id="serverData"></div>
</div>
<div class="l-a"></div>
<div class="tagLine1">Little minds with big ideas</div>
<script>
$(document).ready(function() {
$("#serverData").on("click", ".messageAlert", function() {
$(this).next(".messageContent").toggle();
});
$("#serverData").on("click", ".messageContent", function() {
$(this).before().toggle();
});
})
</script>
</body>
</html>
</code></pre>
<p><strong>json code for dynamic creation</strong></p>
<pre><code><script type="text/javascript">
$(document).ready(function() {//READY FUNC
$.getJSON("http://newberylodge.co.uk/webapp/includes/messageRetrieve.php",function(data) {//JSON
$.each(data, function(key, val) {//iterate each data
var id = val.id;
var messageId = val.messageId;
var messageSubject = val.messageSubject;
var messageContent = val.messageDetail;
$('#serverData').append('<div id="' + id + '" class="messageAlert">' + messageSubject + '</div>');
$('#serverData').append('<div id="' + messageId + '" class="messageContent">' + messageContent + '</div>');
$('.messageContent').append('<input id="' + messageId + '" type="button" class="deleteButton" value="Delete Message" />');
});//iterate each data
});//JSON
});//READY FUNC
</script>
</code></pre>
<p>Any help would be greatfully appreciated</p>
| 3 | 1,665 |
jQuery Ajax load table not whole page
|
<h1>FIXED</h1>
<p>My problem is resolved. My issue was not the jQuery command as much as i was using the same template as when first loading the page and the table included in that jsp page. </p>
<h2>Solution</h2>
<p>MY solution:
Create a new template to be called on new page load name ControlTable.
Create a new jsp file with only the table. Have it loaded with both templates.
when jquery is triggered call only the new template via the controller -> template -> jstl core </p>
<p><strong>Background</strong></p>
<ol>
<li>I have a form that I fill in to create a website user login information. </li>
<li>When i enter the text into 'plantNo' and select producer from my Drop Down list. i want it to load a table into after querying the servlet to get the data. </li>
<li>It is getting the data ( i can see via console) and retrieving the list. </li>
</ol>
<p><strong>Problem</strong></p>
<p>The problem is the reloading of the table. It is reloading the whole webpage into the table. What am i doing wrong? I am new to jQuery and AJAX.</p>
<p><strong>jQuery function</strong></p>
<pre><code>function getProdInfoData(variableIn){
var plantnumber=document.myform.plantNo.value.trim();
alert(plantnumber);
$.post('Admin?page=createUser', {"plant_no": plantnumber },function(data){
$('#pi').html(data).hide().slideDown('slow');
});
}
</code></pre>
<p><strong>Create_User.jsp</strong></p>
<pre><code><script type="text/javascript" src="/javascript/ajax_functions.js"></script>
<script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/javascript/create_web_user.js"></script>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<style type="text/css">
label{display: inline-block; width:120px; font-weight: bold;}
input{width:250px; height: 25px; font-size: 18px; margin-right:25px;}
select{width:250px; height: 25px; font-size: 18px; margin-right:25px;}
#pi tr:nth-child(odd){
background: #dae5f4;
}
#pi tr:nth-child(even){
background: #ccccc;
}
<h2> Create Website User Login</h2>
<!-- &nbsp is a non break line space needed to offset for the asterisk in the required fields-->
<div id="reserve_form"><form name="myform" method="post" action="/Admin?page=create_user_confirm" onsubmit="return validateform(this.form)" >
<div id="User_name"><p><label class="form"><sup style="color:red; font-style:bold, italic;">*</sup> User Name: </label><input type="text" class="textbox" id="uname" name="user_name" />
<label class="form"><sup style="color:red; font-style:bold, italic;;">*</sup> First Name: </label><input type="text" class="textbox" id="fname" name="first_name" /></p></div>
<div id="User_pword"><p><label class="form"><sup style="color:red; font-style:bold, italic;">*</sup> Password: </label><input type="text" class="textbox" id="pword" name="user_pword" />
<label class="form"><sup style="color:red; font-style:bold, italic;">*</sup> Last Name: </label><input type="text" class="textbox" id="lname" name="last_name" /></p></div>
<div id="Plant_no"><p><label class="form"><sup style="color:red; font-style:bold, italic;">*</sup> Plant or Prod #: </label><input type="text" class="textbox" id="plantNo" name="plant_no" />
<label class="form">&nbsp; Farm Name: </label><input type="text" class="textbox" id="farnname" name="farm_name" /></p></div>
<div id="Acct_type"><p><label class="form"><sup style="color:red; font-style:bold, italic;">*</sup> Account Type: </label>
<select name="acct_type" id="acct_type_select" onchange = "ShowHideDiv2(this.value)" style="height: 25px;">
<option value=""> </option>
<option value=5>Producer</option>
<option value=15>Field Man</option>
<option value=2>Admin</option>
</select>
<label class="form">&nbsp; Email Address: </label><input type="text" class="textbox" id="emailaddress" name="email_address" /></p></div>
<div id="cntrl"><p><label class="form"><sup style="color:red; font-style:bold, italic;">*</sup> Control #: </label><input type="text" class="textbox" id="cntrlno" name="cntrl_no" />
</div>
<table id="pi" style="display: block" >
<tr id="header">
<td>Control Number</td>
<td>Producer ID</td>
<td>Producer Name</td>
<td>Producer Name 2</td>
<td>Producer Name 3</td>
<td>Plant</td>
<td>Coop</td>
<td>Federal Order</td>
</tr>
<c:forEach items="${prod_ctl_sel}" var="pt" varStatus="i">
<c:set var="background_color" value="#fff"/>
<c:set var="border_color" value="black"/>
<c:set var="v" value=""/>
<tr class="producer_data" id="<c:out value="${i.count}_row"/>" >
<td style="text-align:center;"><c:out value="${pt.prodCtlNum}"/></div></td>
<td><c:out value="${pt.prodIdNum}"/></td>
<td><c:out value="${pt.prodName1}"/></td>
<td><c:out value="${pt.prodName2}"/></td>
<td><c:out value="${pt.prodName3}"/></td>
<td><c:out value="${pt.prodPlant}"/></td>
<td><c:out value="${pt.prodCoop}"/></td>
<td><c:out value="${pt.prodOrder}"/></td>
</tr>
</c:forEach>
</code></pre>
<p></p>
<p>finally <strong>servlet/controller</strong></p>
<pre><code>public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//_LOTS_OF_CODE_IN_BETWEEN
if(request.getParameter("page")!=null && !request.getParameter("page").equals("")){
if(request.getParameter("page").equalsIgnoreCase("createUser")){
/* NEW CODE to create user */
String updateID = info.getUserid();
String prod_number_in = request.getParameter("plant_no");
AdminFunctions af = new AdminFunctions();
ArrayList prod_control_select = new ArrayList();
System.out.println("prond_num_in"+ prod_number_in);
if(prod_number_in != null || prod_number_in != ""){
prod_control_select = af.getProdCtlNum(prod_number_in);
request.setAttribute("prod_ctl_sel",prod_control_select);
}
</code></pre>
<p>Since a picture is worth a 1k words here is a screen grab. </p>
<p><a href="http://i.stack.imgur.com/pEDSw.png" rel="nofollow">Screen Grab of the webpage after (removed some database info)</a></p>
| 3 | 3,336 |
Radzen nested Datagrid not showing
|
<p>I'm new to Radzen and I've been trying to make a nice yet simplified nested master detail datagrid following <a href="https://blazor.radzen.com/master-detail-hierarchy-demand" rel="nofollow noreferrer">this example</a>. I have managed to make two seperate datagrids appear properly but when I try to nest them nothing appears (renders? ). Any help is much appreciated.</p>
<p><a href="https://i.stack.imgur.com/XyBhO.png" rel="nofollow noreferrer">Image of rendered page</a></p>
<p>SkillCategoryOverviewPage.cs:</p>
<pre><code>using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Radzen;
using Radzen.Blazor;
using SkillMatrix.APIModels;
using SkillMatrix.Client.Services.Interfaces;
namespace SkillMatrix.Client.Features.SkillCategoryView
{
public partial class SkillCategoryOverviewPage
{
#region private properties
private RadzenDataGrid<SkillCategoryResponse> OuterGrid;
private RadzenDataGrid<SkillResponse> InnerGrid;
#endregion
#region protected properties
protected List<SkillCategoryResponse> SkillCategories { get; set; }
protected List<SkillResponse> Skills;
[Inject]
protected ISkillCategoryDataService SkillCategoryDataService { get; set; }
[Inject]
protected ISkillDataService SkillDataService { get; set; }
#endregion
#region protected methods
protected override async Task OnInitializedAsync()
{
// Get all SkillCategories
SkillCategories = (List<SkillCategoryResponse>) await SkillCategoryDataService.GetSkillCategoriesAsync();
Skills = (List<SkillResponse>) await SkillDataService.GetSkillsAsync();
// Add Skills to their correct skillCategory
foreach (var skillCategory in SkillCategories)
{
// todo: fix this
foreach (var skill in Skills)
{
if(skill.SkillCategoryId == skillCategory.Id)
{
var tmp= new SkillResponse{Id=skill.SkillCategoryId,Name=skill.Name,Description=skill.Description};
skillCategory.Skills.Add(tmp);
}
}
}
}
void OuterRowRender(RowRenderEventArgs<SkillCategoryResponse> args)
{
args.Expandable = true;
}
void InnerRowRender(RowRenderEventArgs<SkillResponse> args)
{
args.Expandable = true;
}
#endregion
}
}
</code></pre>
<p>SkillCategoryOverviewPage.razor:</p>
<pre><code>@page "/skillcategoryoverview"
@using SkillMatrix.APIModels
@using SkillMatrix.Shared.Entities
<h1 class="page-title">Skill Categories</h1>
@if (SkillCategories == null)
{
<p><em>Loading ...</em></p>
}
else
{
@*Working Code*@
<RadzenDataGrid @ref="OuterGrid" Data="SkillCategories" TItem="SkillCategoryResponse" AllowPaging="true" PageSize="10" RowRender="OuterRowRender" ExpandMode="DataGridExpandMode.Single">
<Columns>
<template Context="skillCategory">
<RadzenDataGridColumn TItem="@SkillCategoryResponse" Property="@nameof(SkillCategoryResponse.Id)" Title="Id" Width="auto" />
<RadzenDataGridColumn TItem="@SkillCategoryResponse" Property="@nameof(SkillCategoryResponse.Name)" Title="Name" Width="auto" />
<RadzenDataGridColumn TItem="@SkillCategoryResponse" Property="@nameof(SkillCategoryResponse.Description)" Title="Description" Width="auto" />
</template>
</Columns>
</RadzenDataGrid>
<RadzenDataGrid @ref="InnerGrid" Data="Skills" TItem="SkillResponse" AllowPaging="true" PageSize="10" RowRender="InnerRowRender" ExpandMode="DataGridExpandMode.Single">
<Columns>
<template Context="skill">
<RadzenDataGridColumn TItem="@SkillResponse" Property="@nameof(SkillResponse.Id)" Title="Skill ID" Width="auto" />
<RadzenDataGridColumn TItem="@SkillResponse" Property="@nameof(SkillResponse.Name)" Title="Skill Name" Width="auto" />
<RadzenDataGridColumn TItem="@SkillResponse" Property="@nameof(SkillResponse.Description)" Title="Skill Description" Width="auto" />
</template>
</Columns>
</RadzenDataGrid>
@*Non Working code*@
<RadzenDataGrid @ref="OuterGrid" Data="SkillCategories" TItem="SkillCategoryResponse" AllowPaging="true" PageSize="10" RowRender="OuterRowRender" ExpandMode="DataGridExpandMode.Single">
<template Context="skillCategory">
<RadzenDataGrid @ref="InnerGrid" Data=".Skills" TItem="SkillResponse" AllowPaging="true" PageSize="10" RowRender="InnerRowRender" ExpandMode="DataGridExpandMode.Single">
<Columns>
<RadzenDataGridColumn TItem="@SkillResponse" Property="@nameof(SkillResponse.Id)" Title="Skill ID" Width="auto">
</RadzenDataGridColumn>
</Columns>
</RadzenDataGrid>
</Template>
</RadzenDataGrid>
}
</code></pre>
<p>Edit: Figured out a solution. As mentioned, the radzen syntax in the example is very specific and albeit hidden it does require an extra template before or after the outter datagrid for it to work. This example works:</p>
<pre><code>@page "/skillcategoryoverview"
@using SkillMatrix.APIModels
<h1 class="page-title">Skill Categories</h1>
@if (SkillCategories == null)
{
<p><em>Loading ...</em></p>
}
else
{
<RadzenDataGrid @ref="@SkillCategoryGrid" AllowFiltering="true" AllowPaging="true" PageSize="4" AllowSorting="true"
ExpandMode="DataGridExpandMode.Single" Data="@SkillCategories" TItem="SkillCategoryResponse">
<Columns>
<RadzenDataGridColumn TItem="@SkillCategoryResponse" Property="@nameof(SkillCategoryResponse.Id)" Title="Skill Category Id" Width="auto">
</RadzenDataGridColumn>
<RadzenDataGridColumn TItem="@SkillCategoryResponse" Property="@nameof(SkillCategoryResponse.Name)" Title="Name" Width="auto">
</RadzenDataGridColumn>
<RadzenDataGridColumn TItem="@SkillCategoryResponse" Property="@nameof(SkillCategoryResponse.Description)" Title="Description" Width="auto">
</RadzenDataGridColumn>
<RadzenDataGridColumn TItem="@SkillCategoryResponse" Width="100px">
<Template Context="selected">
<RadzenButton Icon="info" ButtonStyle="ButtonStyle.Info" Click=@(() => NavigateToDetailPage(selected))>
</RadzenButton>
<RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Light" Click=@(() => NavigateToEditPage(selected))>
</RadzenButton>
</Template>
</RadzenDataGridColumn>
</Columns>
<Template Context="skill">
<RadzenDataGrid AllowFiltering="false" AllowPaging="true" PageSize="10" AllowSorting="false"
Data="skill.Skills" TItem="SkillResponse">
<Columns>
<RadzenDataGridColumn TItem="@SkillResponse" Property="skill.Id" Title="Skill Id" Width="auto">
</RadzenDataGridColumn>
<RadzenDataGridColumn TItem="@SkillResponse" Property="skill.Name" Title="Name" Width="auto">
</RadzenDataGridColumn>
<RadzenDataGridColumn TItem="@SkillResponse" Property="skill.Description" Title="Description" Width="auto">
</RadzenDataGridColumn>
</Columns>
</RadzenDataGrid>
</Template>
</RadzenDataGrid>
}
</code></pre>
| 3 | 4,294 |
Android Signed Apk crashed in below 5.0 Versions
|
<p>I create a signed APK and upload that, it crashes in all below version of marshmallow. The signed APK works on Android above version 5.0, but not on <5.0. The AppCompat Library is linked with the project in Android.</p>
<p>And when I normally run the same project in android 5.0 it work perfectly but signed apk not run in 5.0.</p>
<p>And it was also not generating the crash report.</p>
<p>In the AndroidManifest.xml I have declared:</p>
<pre><code>android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.ahgp"
minSdkVersion 21
targetSdkVersion 26
versionCode 1
versionName "1.0"
// Enabling multidex support.
multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets { main { java.srcDirs = ['src/main/java', 'src/main/assets/fonts'] } }
</code></pre>
<p>}</p>
<pre><code>allprojects {
repositories {
maven {
url "https://github.com/QuickBlox/quickblox-android-sdk-releases/raw/master/"
}
}
}
repositories {
mavenCentral()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile('com.paypal.sdk:paypal-android-sdk:2.15.3') {
exclude group: 'io.card'
}
compile files('libs/twitter4j-core-4.0.3.jar')
// compile 'com.jakewharton:butterknife-compiler:8.6.0'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.jakewharton:butterknife:8.6.0'
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:design:26.0.2'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'org.glassfish.main:javax.annotation:4.0-b33'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.android.support:recyclerview-v7:26.0.2'
compile 'com.android.support:support-v4:26.0.2'
compile 'com.facebook.android:facebook-android-sdk:(4,5)'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'com.journeyapps:zxing-android-embedded:3.5.0'
testCompile 'junit:junit:4.12'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
/* compile 'com.google.android.gms:play-services:10+'
compile 'com.google.android.gms:play-services-location:10+'
compile 'com.google.android.gms:play-services-maps:10+'
compile 'com.google.android.gms:play-services-places:10+'*/
compile 'com.quickblox:quickblox-android-sdk-videochat-webrtc:3.3.1'
compile 'com.google.android.gms:play-services:11.0.4'
compile 'com.google.firebase:firebase-messaging:11.0.4'
compile 'com.google.firebase:firebase-core:11.0.4'
implementation 'com.android.support:multidex:1.0.3'
//noinspection GradleCompatible
/* compile 'com.google.firebase:firebase-messaging:9.8.0'
compile 'com.google.firebase:firebase-core:9.8.0'*/
// glide
compile 'com.github.bumptech.glide:glide:3.7.0'
// acra crash report
compile 'ch.acra:acra:4.6.2'
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
| 3 | 1,448 |
Error 404: The links on my website don't work, only index (using Codeigniter & .htaccess)
|
<p>I am hosting my website <a href="http://tstspanama.com/" rel="nofollow noreferrer">http://tstspanama.com/</a> on a Apache server. It was created with the PHP framework Codeigniter. I can only see the home page but nothing else, the links don't work.</p>
<p>If I want to go to <code>http://tstspanama.com/servicios</code>, I get:</p>
<blockquote>
<p>Not Found</p>
<p>The requested URL <code>/servicios</code> was not found on this server</p>
</blockquote>
<p>Does anyone have an idea of how ti fix this? I attach all important code.</p>
<p><strong>On application config (/var/www/tsts/application/config/config.php)</strong></p>
<pre><code>$config['base_url'] = isset($_SERVER['REQUEST_URI']) && $_SERVER['HTTP_HOST'] != 'localhost' ? 'http://'.$_SERVER['HTTP_HOST'].'/' : 'http://www.tstspanama.com/';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
</code></pre>
<p><strong>On my .htaccess</strong></p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /tsts/
RewriteCond $1 !^(index\.php|assets|images|css|js|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
ErrorDocument 404 /index.php
</IfModule>
<ifModule mod_php5.c>
php_value default_charset utf-8
</ifModule>
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
</code></pre>
<p><strong>On /etc/apache2/sites-available/www.tstspanama.com</strong></p>
<pre><code><VirtualHost *:80>
ServerName www.tstspanama.com
ServerAlias tstspanama.com
DocumentRoot /var/www/tsts
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/tsts>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
ErrorLog /var/log/apache2/error.log
# Possible values include: debug, info, notice, warn, error,
# crit, alert, emerg.
LogLevel error
CustomLog /var/log/apache2/access.log combined
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</VirtualHost>
</code></pre>
| 3 | 1,259 |
Sorting attachments into different folders
|
<p>I updated a (working) macro which I received from my friend (this macro sorts attachments into different folders) The update relates to select - case block in SaveAttachment Procedure. I'd like to save attachments into 2 different paths - PATH and PATH2 depending on the folder. For TargetFolderItemsAA and TargetFolderItemsAB there will be PATH2 and for the rest - PATH. Does anybody know, what's wrong with the code (an error occurs)? Thanks for your help in advance.</p>
<pre><code>Option Explicit
'###############################################################################
'### Module level Declarations
'expose the items in the target folder to events
'MASTS
Dim WithEvents TargetFolderItemsG As Items
Dim WithEvents TargetFolderItemsK As Items
Dim WithEvents TargetFolderItemsL As Items
Dim WithEvents TargetFolderItemsM As Items
Dim WithEvents TargetFolderItemsN As Items
Dim WithEvents TargetFolderItemsO As Items
Dim WithEvents TargetFolderItemsP As Items
Dim WithEvents TargetFolderItemsQ As Items
Dim WithEvents TargetFolderItemsR As Items
Dim WithEvents TargetFolderItemsT As Items
Dim WithEvents TargetFolderItemsU As Items
Dim WithEvents TargetFolderItemsV As Items
Dim WithEvents TargetFolderItemsW As Items
'ENERGY SALE
Dim WithEvents TargetFolderItemsAA As Items
Dim WithEvents TargetFolderItemsAB As Items
Const FILE_PATH As String = "Z:\Wind_datas\"
Const FILE_PATH2 As String = "Z:\Projects\"
'###############################################################################
'### this is the Application_Startup event code in the ThisOutlookSession module
Private Sub Application_Startup()
'some startup code to set our "event-sensitive" items collection
Dim ns As Outlook.NameSpace
'
Set ns = Application.GetNamespace("MAPI")
'MASTS
Set TargetFolderItemsG = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Grajewo").Items
Set TargetFolderItemsK = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Czyzew").Items
Set TargetFolderItemsL = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Annopol").Items
Set TargetFolderItemsM = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Wloszczowa").Items
Set TargetFolderItemsN = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Grajewo_100m").Items
Set TargetFolderItemsO = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Bialogard").Items
Set TargetFolderItemsP = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Krasnik").Items
Set TargetFolderItemsQ = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Suraz").Items
Set TargetFolderItemsR = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Bejsce").Items
Set TargetFolderItemsT = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Malogoszcz").Items
Set TargetFolderItemsU = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Odolanow").Items
Set TargetFolderItemsV = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Frampol").Items
Set TargetFolderItemsW = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("maszty").Folders("datas_Zaklikow").Items
'ENERGY SALE
Set TargetFolderItemsAA = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("Sprzedaz energii Bialogard").Folders("Alpiq - grafiki dla Energa").Items
Set TargetFolderItemsAB = ns.Folders.Item("Zimbra - TB").Folders.Item("Inbox").Folders("Sprzedaz energii Bialogard").Folders("WH prognoza n-1").Items
End Sub
'MASTS & ENERGY SALE
Sub SaveAttachment(ByVal Prefix As String, ByVal Item As Object)
'when a new item is added to our "watched folder" we can process it
Dim olAtt As Attachment
Dim i As Integer
Select Case Item
Case TargetFolderItemsAA, TargetFolderItemsAB
If Item.Attachments.Count > 0 Then
For i = 1 To Item.Attachments.Count
Set olAtt = Item.Attachments(i)
'save the attachment
olAtt.SaveAsFile FILE_PATH2 & Prefix & "\daily_files\" & olAtt.FileName
Next
End If
Case Else
If Item.Attachments.Count > 0 Then
For i = 1 To Item.Attachments.Count
Set olAtt = Item.Attachments(i)
'save the attachment
olAtt.SaveAsFile FILE_PATH & Prefix & "\daily_files\" & olAtt.FileName
Next
End If
End Select
Set olAtt = Nothing
End Sub
'###############################################################################
'### this is the ItemAdd event code
'MASTS
Sub TargetFolderItemsG_ItemAdd(ByVal Item As Object)
SaveAttachment "Grajewo", Item
End Sub
Sub TargetFolderItemsK_ItemAdd(ByVal Item As Object)
SaveAttachment "Czyzew", Item
End Sub
Sub TargetFolderItemsL_ItemAdd(ByVal Item As Object)
SaveAttachment "Annopol", Item
End Sub
Sub TargetFolderItemsM_ItemAdd(ByVal Item As Object)
SaveAttachment "Wloszczowa", Item
End Sub
Sub TargetFolderItemsN_ItemAdd(ByVal Item As Object)
SaveAttachment "grajewo_100m", Item
End Sub
Sub TargetFolderItemsO_ItemAdd(ByVal Item As Object)
SaveAttachment "Bialogard", Item
End Sub
Sub TargetFolderItemsP_ItemAdd(ByVal Item As Object)
SaveAttachment "Krasnik", Item
End Sub
Sub TargetFolderItemsQ_ItemAdd(ByVal Item As Object)
SaveAttachment "Suraz", Item
End Sub
Sub TargetFolderItemsR_ItemAdd(ByVal Item As Object)
SaveAttachment "Bejsce", Item
End Sub
Sub TargetFolderItemsT_ItemAdd(ByVal Item As Object)
SaveAttachment "Malogoszcz", Item
End Sub
Sub TargetFolderItemsU_ItemAdd(ByVal Item As Object)
SaveAttachment "Odolanow", Item
End Sub
Sub TargetFolderItemsV_ItemAdd(ByVal Item As Object)
SaveAttachment "Frampol", Item
End Sub
Sub TargetFolderItemsW_ItemAdd(ByVal Item As Object)
SaveAttachment "Zaklikow", Item
End Sub
'ENERGY SALE
Sub TargetFolderItemsAA_ItemAdd(ByVal Item As Object)
SaveAttachment "01_PKD_do_Energa", Item
End Sub
Sub TargetFolderItemsAB_ItemAdd(ByVal Item As Object)
SaveAttachment "03_Prognozy_WH_n-1", Item
End Sub
'###############################################################################
'### this is the Application_Quit event code in the ThisOutlookSession module
Private Sub Application_Quit()
Dim ns As Outlook.NameSpace
Set TargetFolderItemsG = Nothing
Set TargetFolderItemsK = Nothing
Set TargetFolderItemsL = Nothing
Set TargetFolderItemsM = Nothing
Set TargetFolderItemsN = Nothing
Set TargetFolderItemsO = Nothing
Set TargetFolderItemsP = Nothing
Set TargetFolderItemsQ = Nothing
Set TargetFolderItemsR = Nothing
Set TargetFolderItemsT = Nothing
Set TargetFolderItemsU = Nothing
Set TargetFolderItemsV = Nothing
Set TargetFolderItemsW = Nothing
Set TargetFolderItemsAA = Nothing
Set TargetFolderItemsAB = Nothing
Set ns = Nothing
End Sub
</code></pre>
| 3 | 2,612 |
Resource allocation algorithm for an airlock on a moon base
|
<p>I'm trying to find an algorithm or problem name on a resource allocation problem that goes something like this.</p>
<p>A moon base has an airlock that only one person can use at a time, either to enter or exit, and takes 20 seconds to pass through. Airlock transitions cannot be aborted early or reversed. Astronauts have a limited amount of air when they are outside the base (say 10 minutes). Their job on the moon is to operate a number of drills that are different distances from the moon base, and keep them running with 100% manned uptime.</p>
<p>I hope to answer questions like these:
How many drill sites can be supported with no astronauts running out of air? How do you determine the schedule for the airlock (who gets to enter/exit and in what order)?</p>
<p>There are 2 components:<br>
- First figuring out the number of astronauts required to man each drill site with 100% up time.<br>
- Figuring out the number of drills that can be operated using one airlock</p>
<pre><code>Per Drill:
MaxWorkTime[i] = AirTime - 2*TravelTime[i]
ActualWorkTime[i] < MaxWorkTime[i]
WorkersPerDrill[i] = AirTime/ActualWorkTime[i]
for each drill
try to schedule airlock time
</code></pre>
<p>WorkTime can be reduced to schedule workers more optimally on the airlock as it approaches 100% utilization (I think).</p>
<p>Below is a simple diagram to try to clarify the problem more. The airlock time is consumed by astronauts using it and is indicated by the bars. I want to increase usage to its maximum while not sending too many astronauts outside. The astronauts work cycle is shown for one drill. The astronaut uses airlock time to exit, walks to the worksite, works, walks back to base, and uses airlock to enter.</p>
<pre><code> |---time-->
Airlock: |--x---| |--x---| |--x---| |--x---|
Astronaut1 |-lock-|--to--|---------drill1--------|-from-|-lock-|
Astronaut2 |-lock-|--to--|-------drill1--------|-from-|-lock-|
^
drill1 always manned
</code></pre>
<h2>Update (Example with numbers)</h2>
<pre><code>AirTime = 10min
WalkSpeed = 1 m/s
drill[0] = 180m // 6min to/from travel
drill[1] = 150m // 5min
drill[2] = 120m // 4min
drill[3] = 240m // 8min
TravelTime[0] = 6min
...
MaxWorkTime[0] = AirTime - TravelTime[0] = 4min
...
// WorkersPerDrill = AirTime/MaxWorkTime
WorkersPerDrill[0] >= 2.5 // These numbers are over 1 airtime (10m)
WorkersPerDrill[1] >= 2
WorkersPerDrill[2] >= 1.67
WorkersPerDrill[3] >= 5
TotalWorkersPerAirtime = sum(WorkersPerDrill) = 11.17
AirlockTime = 20s
AirlockPerWorker = 40s
TotalAirlockUsage = TotalWorkersPerAirtime*AirlockPerWorker = 7.4 min of airlock time
74% usage of airlock if no one uses it at the same time
</code></pre>
<p>This is the first part of the problem. Once there is a conflict where drill[1] worker and drill[3] worker come back at the same time there is a chance one runs out of air. That is the problem I'm trying to solve. Thanks for putting up with this long winded question!</p>
| 3 | 1,173 |
Nginx Setup on Ubuntu
|
<p>I'm trying to setup nginx with passenger to work on Ubuntu with RVM.
I should get my apps home page when i go to localhost, instead I recieve the default nginx home page. </p>
<pre><code>user antarr;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
passenger_root /home/antarr/.rvm/gems/ruby-1.9.2-p180@myapplication/gems/passenger-3.0.7;
passenger_ruby /home/antarr/.rvm/wrappers/ruby-1.9.2-p180@myapplication/ruby;
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# HTTP SERVER
server {
listen 80;
server_name localhost;
root /rails_apps/Blog/public; # <--- be sure to point to 'public'!
passenger_enabled on;
}
}
</code></pre>
| 3 | 1,192 |
What do these networkx errors mean which I am getting after setting a filter on my pandas dataframe?
|
<p>I have a source, target and weight dataframe called <code>Gr_Team</code> which looks like this (sample) -</p>
<pre><code>Passer Receiver count
116643 102747 27
102826 169102 10
116643 102826 7
167449 102826 8
102747 167449 4
</code></pre>
<p>Each Passer and Receiver have their unique x,y co-ordinates which I have in a dictionary <code>loc</code> - <code>{'102739': [32.733999999999995, 26.534], '102747': [81.25847826086964, 27.686739130434784], '102826': [68.09609195402302, 77.52206896551728]}</code>
I plotted this using networkx:</p>
<pre><code>G=nx.from_pandas_edgelist(Gr_Team, 'Passer', 'Receiver', create_using=nx.DiGraph())
nx.draw(G, loc, with_labels=False, node_color='red',
node_size=Gr_Team['count']*100,
width=Gr_Team['count'],
edge_color = Gr_Team["count"],
edge_cmap = cmap,
arrowstyle='->',
arrowsize=10,
vmin=vmin,
vmax=vmax,
font_size=10,
font_weight="bold",
connectionstyle='arc3, rad=0.1')
</code></pre>
<p>That worked without any issues and here's what I got:
<a href="https://i.stack.imgur.com/jawQJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jawQJ.png" alt="enter image description here"></a></p>
<p>However, as soon as I try to filter out all the rows with count value below a constant, let's say 3, using this <code>Gr_Team = Gr_Team[Gr_Team["count"]>3]</code>, I get a key error and here's the entire error and traceback which I can't make anything out of: </p>
<pre><code>Warning (from warnings module):
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\drawing\nx_pylab.py", line 676
if cb.iterable(node_size): # many node sizes
MatplotlibDeprecationWarning:
The iterable function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use np.iterable instead.
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PassMapOptaF24Networkx.py", line 148, in <module>
font_weight="bold")#,
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\drawing\nx_pylab.py", line 128, in draw
draw_networkx(G, pos=pos, ax=ax, **kwds)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\drawing\nx_pylab.py", line 280, in draw_networkx
edge_collection = draw_networkx_edges(G, pos, arrows=arrows, **kwds)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\drawing\nx_pylab.py", line 684, in draw_networkx_edges
arrow_color = edge_cmap(color_normal(edge_color[i]))
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\series.py", line 868, in __getitem__
result = self.index.get_value(self, key)
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\indexes\base.py", line 4375, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas\_libs\index.pyx", line 81, in pandas._libs.index.IndexEngine.get_value
File "pandas\_libs\index.pyx", line 89, in pandas._libs.index.IndexEngine.get_value
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 987, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 993, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 1
</code></pre>
<p>I realized that doing only <code>nx.draw(G, loc, with_labels=False, node_color='red')</code> still worked but as soon as I try to pass <code>node_size</code> or <code>edge_color</code>, it hits the above error. From my understanding, the error is only when I'm using the dataframe <code>Gr_Team</code> in the keyword arguments. </p>
<p>I can't figure out why that's happening and why filtering breaks the code. Any help would be appreciated.</p>
<p><strong>EDIT 1</strong>: <a href="https://gist.github.com/AbhishekSharma99/446116421e8e97fe2dcacb8a0f96a38c" rel="nofollow noreferrer">Here</a>'s a gist of the entire code. I tried my best to keep it minimal. <a href="https://github.com/AbhishekSharma99/Opta-Data-Feed/blob/master/PSGCopy_NancyLyonAllEvents.csv" rel="nofollow noreferrer">Here</a>'s the link to the csv file that needs to be read in as df. The line which produces the error is in also in there; commented out.</p>
| 3 | 1,792 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.