title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Upload image in Webview crashes app
|
<p>Im trying to use webview to upload a image. My gallery gets displayed but when i click a image it crashes my app... then when i reopen my app it just gives me a white screen until i reupload my app on my phone again. Im confused and hit a roadblock on how to fix this.</p>
<pre><code> web = (WebView) findViewById(R.id.webView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://.com");
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient()
{
//The undocumented magic method override
//Eclipse will swear at you if you try to put @Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MainMenu.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainMenu.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MainMenu.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MainMenu.FILECHOOSER_RESULTCODE );
}
});
setContentView(web);
}
public class myWebClient extends WebViewClient
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
//flipscreen not loading again
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
// To handle "Back" key press event for WebView to go back to previous screen.
/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}*/
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
// public void onBackPressed()
// {
// if(mWebView.canGoBack())
// mWebView.goBack();
// else{
// Intent start = new Intent(MainMenu.this,MainMenu.class);
// startActivity(start);
// finish(); }}
}
</code></pre>
| 3 | 1,530 |
trouble with creating JTable to display data
|
<p>I am doing this payroll project for school.
The idea is for the user to input the employee's name, work hour, hourly rate, and select department from the ComboBox.
There will display 3 buttons, "Add More", "Display Result", and "exit".
"Add More" button will store the input into several arryalist and set the textfield to blank to allow more input.
"Display Result" will generate a JTable at the bottom JPanel to display the employee's name, department, and weekly salary.</p>
<p>I am running into the problem of nothing shows up after hitting the "Display Result" button. Maybe I have misunderstand the purpose of the button event, but I am really confused right now. Please help!</p>
<p>Here is a <a href="http://s443.photobucket.com/user/bigwhiteegg/media/grfha425564_zpselymr3yp.jpg.html][IMG]http://i443.photobucket.com/albums/qq159/bigwhiteegg/grfha425564_zpselymr3yp.jpg" rel="nofollow">photobucket</a> directURL PrtSc of the UI, hope it helps.</p>
<pre><code>import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class PayrollFrame extends JFrame
{
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame()
{
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new GridLayout(3,1));
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel);
add(buttonPanel);
add(outputPanel);
setVisible(true);
}
private void buildInputPanel()
{
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel()
{
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel()
{
outputPanel = new JPanel();
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][2]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Add More")
{
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
}
else if(e.getActionCommand()=="Display Result")
{
printData();
}
else if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString)
{
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if(tempHour<=40)
{
salary.add(Double.toString(tempHour * tempRate));
}
else
{
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
</code></pre>
| 3 | 2,579 |
How to create an iterative loop of multiple Python functions?
|
<p>I'm trying to write a Python code that is a numerical solver for 1-d heat conduction (using FVM) with a temperature dependent thermal conductivity. </p>
<p>The solver has three functions I need to iterate until convergence: </p>
<p>Conductivity function: takes an initial guess for temperature field and outputs nodal conductivities, dependent on past value of nodal temperatures.</p>
<p>Nodal coefficients: calculates nodal coefficients based on current nodal conductivities.</p>
<p>Nodal temperatures: uses a TDMA algorithm to calculate the nodal temperatures based on current coefficients. </p>
<p>Once the temperatures are calculated, the values are to be cycled through to the conductivity function to continue the loop until convergence. </p>
<p>I can make this work just fine when the conductivity is constant, but start getting issues when I try to implement this pseudocode. I get a maximum recursion depth exceeded error. My code is below:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import copy
# SOLUTION ALGORITHM
# Step 1: DATA
def data(n, hw, he, TinfW, TinfE):
n = 5
hw = 10**10
he = 10**-10
TinfW = 100
TinfE = 10**12
return n, hw, he, TinfW, TinfE
# Step 2: GRID
def grid(x1, x2, data):
x1 = 0
x2 = 0.5
xe = (x2-x1) / data(n, hw, he, TinfW, TinfE)[0]
return xe
# Step 3: GAMSOR
def gamsor(k, q, TDMA):
k0 = 100
beta = 20
T0 = 25
for i in range(data(n, hw, he, TinfW, TinfE)[0]):
k[i] = k0 + beta#*(TDMA(data, coeff)[i]-T0)
q[i] = 10**5
return k, q
#Step 4: COEFF
def coeff(Ae, Aw, Ap, data, gamsor, grid):
for i in range(data(n, hw, he, TinfW, TinfE)[0]):
Ae[i] = Aw[i] = gamsor(k,q, TDMA(data, coeff))[0][i] / grid(x1, x2, data)
Ap[i] = Ae[i] + Aw[i]
# Define "b" array - including source term and boundary conditions
b = np.zeros((data(n, hw, he, TinfW, TinfE)[0], 1))
b.fill(gamsor(k,q, TDMA(data, coeff))[1][i])
b[0] = (gamsor(k,q, TDMA(data, coeff))[1][i]*(grid(x1,x2,data)/2) +
data(n, hw, he, TinfW, TinfE)[1]*
data(n, hw, he, TinfW, TinfE)[3])
b[-1] = (gamsor(k,q, TDMA(data, coeff))[1][i]*(grid(x1,x2,data)/2)+
data(n, hw, he, TinfW, TinfE)[2]*
data(n, hw, he, TinfW, TinfE)[4])
# Change values in first and last coefficients to reflect specified BC's
Aw[0] = 0
Ap[0] = Ae[0] + Aw[0] + data(n, hw, he, TinfW, TinfE)[1]
Ae[-1] = 0
Ap[-1] = Ae[0] + Aw[0] + data(n, hw, he, TinfW, TinfE)[2]
return Ae, Aw, Ap, b
#Step 5: SOLVE
def TDMA(data, coeff):
# Initialize "T" array - the solution array
T = np.zeros(data(n, hw, he, TinfW, TinfE)[0]);
# Initialize recursion functions as arrays
P = np.zeros(data(n, hw, he, TinfW, TinfE)[0]);
Q = np.zeros(data(n, hw, he, TinfW, TinfE)[0]);
## Step 1: evaluate at node 1
P[0] = (coeff(Ae, Aw, Ap, data, gamsor, grid)[0][0] /
coeff(Ae, Aw, Ap, data, gamsor, grid)[2][0])
Q[0] = (coeff(Ae, Aw, Ap, data, gamsor, grid)[3][0] /
coeff(Ae, Aw, Ap, data, gamsor, grid)[2][0])
## Step 2: sweep from node 2 to node (n-1) (python
## cell 1->(n-2) ) evaluating P and Q
for i in range(1, data(n, hw, he, TinfW, TinfE)[0]-1):
P[i] = ((coeff(Ae, Aw, Ap, data, gamsor, grid)[0][i]) /
(coeff(Ae, Aw, Ap, data, gamsor, grid)[2][i] -
coeff(Ae, Aw, Ap, data, gamsor, grid)[1][i]*P[i-1]))
Q[i] = ((coeff(Ae, Aw, Ap, data, gamsor, grid)[3][i] +
coeff(Ae, Aw, Ap, data, gamsor, grid)[1][i]*Q[i-1]) /
(coeff(Ae, Aw, Ap, data, gamsor, grid)[2][i] -
coeff(Ae, Aw, Ap, data, gamsor, grid)[1][i]*P[i-1]))
## Step 3: calculate for node n
P[data(n, hw, he, TinfW, TinfE)[0]-1] = 0
Q[data(n, hw, he, TinfW, TinfE)[0]-1] = (
(coeff(Ae, Aw, Ap, data, gamsor, grid)[3][data(n, hw, he,
TinfW, TinfE)[0]-1] + coeff(Ae, Aw, Ap, data, gamsor, grid)
[1][data(n, hw, he, TinfW, TinfE)[0]-1]*Q[data(n, hw, he, TinfW,
TinfE)[0]-2]) / (coeff(Ae, Aw, Ap, data, gamsor, grid)[2][data(n,
hw, he, TinfW, TinfE)[0]-1] - coeff(Ae, Aw, Ap, data, gamsor,
grid)[1][data(n, hw, he, TinfW, TinfE)[0]-1]*P[data(n, hw, he,
TinfW, TinfE)[0]-2]))
T[data(n, hw, he, TinfW, TinfE)[0]-1] = (
Q[data(n, hw, he, TinfW, TinfE)[0]-1] )
## Step 4: back fill, giving the temperatures
for i in range(data(n, hw, he, TinfW, TinfE)[0] - 2, -1, -1):
T[i] = P[i]*T[i+1] + Q[i]
return T
def Temps(TDMA):
Temps = copy.copy(TDMA(data,coeff)); Temps.fill(100)
return Temps
if __name__ == '__main__':
# Initialize variables
n = 0
hw = 0
he = 0
TinfW = 0
TinfE = 0
k = np.zeros(data(n, hw, he, TinfW, TinfE)[0])
q = np.zeros(data(n, hw, he, TinfW, TinfE)[0])
k0 = 0
beta = 20
T0 = 0
x1 = 0
x2 = 0
Ae = np.zeros(data(n, hw, he, TinfW, TinfE)[0])
Aw = np.zeros(data(n, hw, he, TinfW, TinfE)[0])
Ap = np.zeros(data(n, hw, he, TinfW, TinfE)[0])
b = 0
data(n, hw, he, TinfW, TinfE)
grid(x1, x2, data)
Temps(TDMA)
for _ in range(1):
gamsor(k, q)
coeff(Ae, Aw, Ap, data, gamsor, grid)
TDMA(data, coeff)
#print Temps(TDMA)
print "Nodal Temperature Distribution (C):", TDMA(data, coeff)
</code></pre>
| 3 | 2,710 |
Appdomain not woking with .net 6?
|
<p>So I have been following the tutorial at <a href="https://docs.microsoft.com/en-us/previous-versions/dotnet/framework/code-access-security/how-to-run-partially-trusted-code-in-a-sandbox?redirectedfrom=MSDN" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/previous-versions/dotnet/framework/code-access-security/how-to-run-partially-trusted-code-in-a-sandbox?redirectedfrom=MSDN</a> to run untrusted code in a test environment with Appdomain, but I'm having trouble with AppDomainSetup constructor and the ApplicationBase property.
This is basically the code included in the tutorial :</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.Remoting;
//The Sandboxer class needs to derive from MarshalByRefObject so that we can create it in another
// AppDomain and refer to it from the default AppDomain.
class Sandboxer
{
const string pathToUntrusted = @"..\..\..\UntrustedCode\bin\Debug";
const string untrustedAssembly = "UntrustedCode";
const string untrustedClass = "UntrustedCode.UntrustedClass";
const string entryPoint = "IsFibonacci";
private static Object[] parameters = { 45 };
static void Main()
{
AppDomainSetup adSetup = new AppDomainSetup; **//Getting an error here that the constructor doesn't take 0 argumnets**
adSetup.ApplicationBase = Path.GetFullPath(pathToUntrusted);//Similar error here
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>();
AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly); //another error here,
ObjectHandle handle = Activator.CreateInstanceFrom(
newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName,
typeof(Sandboxer).FullName
);
Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();
newDomainInstance.ExecuteUntrustedCode(untrustedAssembly, untrustedClass, entryPoint, parameters);
}
public void ExecuteUntrustedCode(string assemblyName, string typeName, string entryPoint, Object[] parameters)
{
MethodInfo target = Assembly.Load(assemblyName).GetType(typeName).GetMethod(entryPoint);
try
{
bool retVal = (bool)target.Invoke(null, parameters);
}
catch (Exception ex)
{
new PermissionSet(PermissionState.Unrestricted).Assert();
Console.WriteLine("SecurityException caught:\n{0}", ex.ToString());
CodeAccessPermission.RevertAssert();
Console.ReadLine();
}
}
}
</code></pre>
<p>Am I missing a library or something here?
If this tutorial is outdated or something, could someone help me with an up-to-date one ?
Thanks in advance :) .</p>
| 3 | 1,212 |
How to join more than 2 collections in mongodb?
|
<p>I have got 3 collections: groups, users, and members.
Groups collection contains group specific details,
users collection contains user-specific details and members collection
contains the association of users with groups.</p>
<p>For example:</p>
<pre><code>Groups:
id | name
ObjectId("5ee5e346fae4a21e28a81d91") | Housemates
ObjectId("5ee5e346fae4a21e28a81d92") | Co-workers
Users:
id | name
ObjectId("5ee493b0989d0f271cdc41c1") | Joulie
ObjectId("5ee493b0989d0f271cdc41c3") | Newelle
ObjectId("5ee493b0989d0f271cdc41c5") | John
ObjectId("5ee493b0989d0f271cdc41c7") | Larry
Members:
group_id | user_id
ObjectId("5ee5e346fae4a21e28a81d91") | ObjectId("5ee493b0989d0f271cdc41c1")
ObjectId("5ee5e346fae4a21e28a81d91") | ObjectId("5ee493b0989d0f271cdc41c3")
ObjectId("5ee5e346fae4a21e28a81d92") | ObjectId("5ee493b0989d0f271cdc41c5")
ObjectId("5ee5e346fae4a21e28a81d92") | ObjectId("5ee493b0989d0f271cdc41c7")
</code></pre>
<p>I want to join these three collections and get user details for each group with the group name.</p>
<pre><code> Expected Output:
[
{ "group_name":"Housemates",
"user_info": [
{"name":"Joulie"},
{"name":"Newelle"}
]
},
{ "group_name":"Co-workers",
"user_info": [
{"name":"John"},
{"name":"Larry"}
]
}
]
</code></pre>
<p>I've written a query to get the output as above but it's not working:</p>
<pre><code>db.members.aggregate([
{
$lookup : {
from: 'users',
localField: "user_id",
foreignField: "_id",
as: "user_info"
}
},{
$lookup: {
from: 'groups',
localField: "group_id",
foreignField: "_id",
as: "group_info"
}
}
]);
</code></pre>
<p><a href="https://stackoverflow.com/questions/35813854/how-to-join-multiple-collections-with-lookup-in-mongodb">This</a> question looks similar and I have tried the solution from it as well, but it does not seem to work for me. I would really appreciate any help or guideline.
Thank you in advance!</p>
| 3 | 1,398 |
notify() and wait() not working in Java
|
<p>I have 2 threads which I want to synchronize with wait() and notify(). However when I notify the thread which waits never resumes. This are my pieces of code.
In Lib60870 i start both threads, and thread HandShake is synchronized with SerialReader.</p>
<pre><code>public Lib60870(){ //Here I start threads
try {
myConnection=new Connection(LOCALHOST,port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mySerialReader.start();
myHandshake.start();}
}
</code></pre>
<p><strong>Class SerialReader</strong></p>
<pre><code>public class SerialReader extends Thread {
private static boolean isPaused=true;
@Override
public void run() {
synchronized(this){
if(Lib60870.myConnection!=null){
while(true){
if(!isPaused){
byte inByte=Lib60870.myConnection.getByte();
if(inByte==0x68){
...
}
notify();
}
else if(inByte==0x10){
...
}
notify();
}
}
}
}
}
}
public void setPause(boolean pause){
isPaused=pause;
}
</code></pre>
<p><strong>Class Handshake</strong></p>
<pre><code>public class HandShake extends Thread {
public void run() {
synchronized(Lib60870.mySerialReader){
Lib60870.mySerialReader.setPause(false);
...
try {
Lib60870.mySerialReader.wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Lib60870.mySerialReader.setPause(true);
...
Lib60870.mySerialReader.setPause(false);
try {
Lib60870.mySerialReader.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</code></pre>
<p>}</p>
<p>Thanks in advance</p>
| 3 | 1,040 |
Why does my class not behave exactly like the overridden base class?
|
<p>My application has a <code>ComboBox</code> and had an application setting <code>myStrings</code> of the type <code>System.Collections.Specialized.StringCollection</code>. I bound the <code>ComboBox.ItemSource</code> to <code>Properties.Settings.Default.myStrings</code>. The ComboBox displayed the items of myStrings, as I planned.</p>
<p>Unfortunately the ComboBox did not update the items, when myStrings changed. So I tried to create a new class <code>CustomStringCollection</code> that overrides StringCollection and implements <code>INotifyPropertyChanged</code>.</p>
<p><strong>The setting is not properly saved. I did expect that <code>CustomStringCollection : StringCollection</code> does behave exactly like it's base class, including when it is saved. Why is it not the same?</strong></p>
<p>This is the settings file and you can see that myStrings-values are saved, but myCustomStringCollection-values are not:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
…
<userSettings>
<comboBoxDataBinding.Properties.Settings>
<setting name="myStrings" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Banana</string>
</ArrayOfString>
</value>
</setting>
<setting name="myCustomStringCollection" serializeAs="Xml">
<value />
</setting>
</comboBoxDataBinding.Properties.Settings>
</userSettings>
</configuration>
</code></pre>
<p>This is the class comboBoxDataBinding:</p>
<pre><code>using System.ComponentModel;
using System.Configuration;
using System.Reflection;
namespace comboBoxDataBinding {
[DefaultMember("Item")]
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
class CustomStringCollection : System.Collections.Specialized.StringCollection, INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string v) {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(v));
}
}
}
}
</code></pre>
<p>And this is how I saved those settings:</p>
<pre><code>Properties.Settings.Default.myStrings.Add("Banana");
Properties.Settings.Default.myCustomStringCollection.Add("Banana");
Properties.Settings.Default.Save();
</code></pre>
| 3 | 1,045 |
Can not target div with CSS
|
<p>I am having a CSS newb problem. We are still using the old YUI2 which I am using to create sub-tables within a table as in this:</p>
<p><a href="https://i.stack.imgur.com/BICOp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BICOp.png" alt="enter image description here"></a></p>
<p>When the sub table is shown YUI extands the height of the row and adds a white div as you can see. I would like to add some style to that div (behind the subtable).</p>
<p>I CAN assign an id to that div by overriding the class and modifying the table's functionality in order to get this:</p>
<p><a href="https://i.stack.imgur.com/2EWWe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2EWWe.png" alt="enter image description here"></a></p>
<p>I would really rather not go this route. I would prefer to just target the div with CSS but my inexpereince has trumped me. When I inspect the div google gives me this:</p>
<p><a href="https://i.stack.imgur.com/Ecth1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ecth1.png" alt="enter image description here"></a></p>
<p>How do I target the highlighted div? This seems like it should be easy as I can see right there what classes the div has but I just can't get it.</p>
<p><strong>EDIT</strong>
Not sure if this will help but my javascript uses the following function to create the subtable:</p>
<pre><code>DMAS.deviceconsole.datamonitor.DataMonitorOverviewTable.prototype.secondSubTable = function(state){
var json = {
"Fruit":[
{"name":"apples","type":"fruit", "color":"red"},
{"name":"broccoli","type":"veg","color":"red"},
{"name":"cherriess","type":"fruit","color":"red"}
]
};
var dsLocalJSON2 = new YAHOO.util.DataSource(json);
dsLocalJSON2.responseType = YAHOO.util.DataSource.TYPE_JSON;
dsLocalJSON2.responseSchema = {
resultsList : "Fruit",
fields : ["name","type","color"]
};
var fruitDT = new REDT(
state.expLinerEl,
[
{key:'name', label:'Name', sortable:true},
{key:'type', label:'Type', sortable:true},
{key:'color', label:'Color', sortable:true}
],
dsLocalJSON2,
{
className : "dataMonitorSubtable"
}
);
// Store the reference to this datatable object for any further use
// (specially destroying it, as above)
this.setExpansionState(state.record,NESTED_DT,fruitDT);
//Subscribe to the rowExpansionDestroyEvent so I can destroy the tracksDT table
// before its container (the album row) is gone and it ends a zombie
fruitDT.on(this,'rowExpansionDestroyEvent', function (state) {
state[NESTED_DT].destroy();
});
}
</code></pre>
<p>Here is a snippet from the YUI Library where it expands the row</p>
<pre><code> expandRow : function( recordId ){
var state = this.getExpansionState( recordId );
if( !state.expanded){
this.setExpansionState( recordId, 'expanded', true );
var expTrEl = state.expTrEl,
record = state.record,
trEl = this.getTrEl( record );
if (expTrEl) {
Dom.insertAfter(state.expTrEl,this.getTrEl(recordId));
Dom.setStyle(state.expTrEl,'display','');
} else {
expTrEl = document.createElement('tr');
var expTdEl = document.createElement( 'td' ),
expLinerEl = document.createElement( 'div' ),
template = this.get(TEMPLATE);
Dom.addClass(expTrEl, CLASS_EXPANSION);
expTdEl.colSpan = this.getFirstTrEl().childNodes.length;
Dom.addClass(expLinerEl, CLASS_LINER);
expTrEl.appendChild( expTdEl );
expTdEl.appendChild( expLinerEl);
this.setExpansionState( recordId, 'expTrEl', expTrEl);
this.setExpansionState( recordId, 'expLinerEl', expLinerEl);
// refresh the copy of the expansion state
state = this.getExpansionState(recordId);
if( Lang.isString( template ) ){
expLinerEl.innerHTML = Lang.substitute( template, record.getData() );
} else if( Lang.isFunction( template ) ) {
template.call(this, state );
} else {
return false;
}
}
//Insert new row
Dom.insertAfter( expTrEl, trEl );
Dom.replaceClass( trEl, CLASS_COLLAPSED, CLASS_EXPANDED );
/**
* Fires when a row is expanded
*
* @event rowExpandedEvent
* @param state {Object} see <a href="#method_getExpansionState">getExpansionState</a>
*/
this.fireEvent( "rowExpandedEvent", state);
return true;
}
},
</code></pre>
| 3 | 2,080 |
/usr/xpg4/bin/grep -q [^0-9] does not always work as expected
|
<p>I have a Unix ksh script that has been in daily use for years (kicked off at night by the crontab). Recently one function in the script is behaving erratically as never happened before. I tried various ways to find out why, but have no success.</p>
<p>The function validates an input string, which is supposed to be a string of 10 numeric characters. The function checks if the string length is 10, and whether it contains any non-numeric characters:</p>
<pre class="lang-sh prettyprint-override"><code>#! /bin/ksh
# The function:
is_valid_id () {
# Takes one argument, which is the ID being tested.
if [[ $(print ${#1}) -ne 10 ]] || print "$1" | /usr/xpg4/bin/grep -q [^0-9] ; then
return 1
else
return 0
fi
}
cat $input_file | while read line ; do
id=$(print $line | awk -F: '{print $5}')
# Calling the function:
is_valid_id $id
stat=$?
if [[ $stat -eq 1 ]] ; then
print "The ID $id is invalid. Request rejected.\n" >> $ERRLOG
continue
else
...
fi
done
</code></pre>
<p>The problem with the function is that, every night, out of scores or hundreds of requests, it finds the IDs in several requests as invalid. I visually inspected the input data and found that all the "invalid" IDs are actually strings of 10 numeric characters as should be. This error seems to be random, because it happens with only some of the requests. However, while the rejected requests persistently come back, it is consistently the same IDs that are picked out as invalid day after day.</p>
<p>I did the following:</p>
<ol>
<li>The Unix machine has been running for almost a year, therefore might need to be refreshed. The system admin to reboot the machine at my request. But the problem persists after the reboot.</li>
<li>I manually ran exactly the same two tests in the function, at command prompt, and the IDs that have been found invalid at night are all valid.</li>
<li>I know the same commands may behave differently invoked manually or in a script. To see how the function behaves in script, the above code excerpt is the small script I ran to reproduce the problem. And indeed, some (though not all) of the IDs found to be invalid at night are also found invalid by the small trouble-shooting script.</li>
<li>I then modified that troubleshooting script to run the two tests one at a time, and found it is the <code>/usr/xpg4/bin/grep -q [^0-9]</code> test that erroneously finds some of the ID as containing non-numeric character(s). Well, the IDs are all numeric characters, at least visually.</li>
<li>I checked if there is any problem with the xpg4 grep command file (<code>ls -l /usr/xpg4/bin/grep</code>), to see if it is put there recently. But its timestamp is year 2005 (this machine runs Solaris 10).</li>
<li>Knowing that the data comes from a central ERP system, to which data entry is performed from different locations using all kinds of various terminal machines running all kinds of possible operating systems that support various character sets and encodings. The ERP system simply allows them. But can characters from other encodings visually appear as numeric characters but the encoded values are not as the <code>/usr/xpg4/bin/grep</code> command expects to be on our Unix machine? I tried the <code>od</code> (octal dump) command but it does not help me much as I am not familiar with it. Maybe I need to know more about <code>od</code> for solving this problem.</li>
</ol>
<p>My temporary work-around is omitting the <code>/usr/xpg4/bin/grep -q [^0-9]</code> test. But the problem has not been solved. What can I try next?</p>
| 3 | 1,072 |
Angular 2 TD form cannot setValue or patchValue to span tag, button
|
<p>I have a simple angular template driven form with few inputs, span tags and button. I need to setValue to form from an object in my component.</p>
<p>I'm unable to setValue to span and button tags and I get the below error.</p>
<pre><code>core.js:1365 ERROR Error: Uncaught (in promise): Error: No value accessor for form control with path: 'userSettings -> id'
Error: No value accessor for form control with path: 'userSettings -> id'
at _throwError (forms.js:1901)
at setUpControl (forms.js:1771)
at resolvedPromise.then (forms.js:3851)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:3988)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
at zone.js:870
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3979)
at _throwError (forms.js:1901)
at setUpControl (forms.js:1771)
at resolvedPromise.then (forms.js:3851)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:3988)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
at zone.js:870
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3979)
at resolvePromise (zone.js:821)
at zone.js:873
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3979)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:594)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:499)
at invokeTask (zone.js:1536)
at HTMLAnchorElement.globalZoneAwareCallback (zone.js:1562)
</code></pre>
<p>My form html code</p>
<pre><code><form class="form-horizontal" role="form" (ngSubmit)="onSettingUpdateSubmit()" #settingsForm="ngForm" >
<fieldset ngModelGroup="userSettings">
<legend><strong>Account Settings</strong></legend>
<br>
<div class="form-group row">
<label class="col-md-3 col-form-label text-md-right">Id</label>
<div class="col-md-4">
<span class="fw-semi-bold" [ngModel]="id" id="id" name="id">{{ id }}</span>
</div>
</div>
<div class="form-group row">
<label for="firstName" class="col-md-3 col-form-label text-md-right">First Name</label>
<div class="col-md-4">
<input type="text"
id="firstName"
required
[ngModel]="firstName"
name="firstName"
class="form-control"
placeholder="Your first name">
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label text-md-right">Active</label>
<div class="col-md-4">
<button type="button"
id="active"
[value]="active"
[ngModel]="active"
name="active"
[ngClass]="active ? 'btn btn-success' : 'btn btn-danger'"
(click)="onActiveMode()">{{ active ? 'Yes' : 'No'}}</button>
</div>
</div>
</fieldset>
<div class="form-actions">
<div class="btn-block text-center">
<button type="submit"
class="btn btn-primary"
[disabled]=!settingsForm.valid>Update</button>
</div>
</div>
</code></pre>
<p></p>
<p>The settingsService in my component will return an object from my API as below object. </p>
<pre><code>{
"id":"12345",
"firstName":"Victor",
"active":true
}
</code></pre>
<p>My settings.compontent.ts</p>
<pre><code>export class SettingsComponent implements OnInit {
ngOnInit() {
this.settingsService.getUserSettings('12345')
.subscribe(
(response: UserSettings) => {
console.log(response);
// this.settingForm.setValue({
// userSettings: response
// });
this.settingForm.form.patchValue({
userSettings: response
});
},
(error) => console.log(error)
);
}
onSettingUpdateSubmit() {
console.log(this.settingForm.value.userSettings);
}
}
</code></pre>
<p>When I click the button Update in my form it returns all the complete object with values (preset in my component for testing purpose).</p>
| 3 | 2,206 |
Firebase Realtime database update
|
<p>Hello guys my firebase real-time database update function is updating all the data with new data, I'm attaching the image of the database before the update</p>
<p><img src="https://i.stack.imgur.com/iYQFG.png" alt="1" /></p>
<p>And after the update all the fields of A and B are changed into C, the source code is available below :</p>
<p>Frontend:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form onsubmit="return false">
<input type="hidden" id="hiddenId">
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Course Code</label>
<input type="text" class="form-control uname-box" id="popupCourseCode" aria-describedby="emailHelp" placeholder="Course Code">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Course Title</label>
<input type="text" class="form-control uname-box" id="popupCourseTitle" aria-describedby="emailHelp" placeholder="Course Title">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Subject</label>
<input type="text" class="form-control uname-box" id="popupSubject" aria-describedby="emailHelp" placeholder="Subject">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Credits</label>
<input type="number" class="form-control uname-box" id="popupCredits" aria-describedby="emailHelp" placeholder="Credits">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Grades</label>
<input type="text" class="form-control uname-box" id="popupGrades" aria-describedby="emailHelp" placeholder="Grades">
</div>
</div>
</form></code></pre>
</div>
</div>
</p>
<p>Function:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>function update() {
firebase.database().ref('academics').orderByKey().once('value', snap => {
snap.forEach((data) => {
var popupCourseCode = document.getElementById('popupCourseCode');
var popupCourseTitle = document.getElementById('popupCourseTitle');
var popupSubject = document.getElementById('popupSubject');
var popupCredits = document.getElementById('popupCredits');
var popupGrades = document.getElementById('popupGrades');
var updates = {
courseCode: popupCourseCode.value,
courseTitle: popupCourseTitle.value,
subject: popupSubject.value,
credits: popupCredits.value,
grade: popupGrades.value,
}
firebase.database().ref('academics/' + data.key).update(updates)
// alert('updated')
console.log(`Update FunctionKey!!!!!!!!!!!! >>>>>>>>> ${data.key}`)
})
// console.log(`Remove FunctionKey!!!!!!!!!!!! >>>>>>>>> ${data.key}`)
})
}</code></pre>
</div>
</div>
</p>
<p>Please provide me a solution. Thanks in anticipation</p>
| 3 | 2,039 |
Fastest way to find a file that contains a string
|
<p>I was looking for the fastest way to find a file, from a given directory, that contains a text string.</p>
<p>I've come across this question: <a href="https://stackoverflow.com/questions/37078978/the-fastest-way-to-find-a-string-inside-a-file">The fastest way to find a string inside a file</a></p>
<p>Most of the answers claimed that the fastest way to do this is using system grep. But no one added times so I've timed it.</p>
<p>I've timed those 2 functions:</p>
<pre><code>mysetup_sys = '''
from subprocess import Popen, PIPE, STDOUT
def find_file_containing_string(str, files_dir):
cmd = "grep {str} -rl {dir}".format(str=str, dir=files_dir)
proc = Popen(cmd, shell=True, stdin=None, stdout=PIPE, stderr=PIPE)
file, err = proc.communicate()
return file'''
</code></pre>
<p>and </p>
<pre><code>mysetup_py='''
from os import listdir
from os.path import isfile, getmtime, join
def find_file_containing_string(str, files_dir):
files_paths = filter(isfile, [join(files_dir, f) for f in listdir(files_dir)])
for file in sorted(files_paths, key=getmtime): #iterate files sorted by time
with open(file) as fl:
found = next((l for l in fl if str in l), None) #find first occurrence in file
if found:
return file
return None'''
</code></pre>
<p>And the test:</p>
<pre><code>mycode1='''find_file_containing_string(some_string_not_in_files, dir_path)'''
mycode2='''find_file_containing_string(some_string_exists_in_one_file, dir_path)'''
timeit.timeit(stmt=mycode1, number = 10000, setup=mysetup_py)
timeit.timeit(stmt=mycode1, number = 10000, setup=mysetup_sys)
timeit.timeit(stmt=mycode2, number = 10000, setup=mysetup_py)
timeit.timeit(stmt=mycode2, number = 10000, setup=mysetup_sys)
</code></pre>
<p>I've got these results:</p>
<p>String not found in files:</p>
<blockquote>
<p>Pythonic way (All files were searched): <strong>284.1225619316101</strong> </p>
<p>System grep using Popen: <strong>306.4192249774933</strong></p>
</blockquote>
<p>String found in files:</p>
<blockquote>
<p>Pythonic way (Search stopped at first match, file #61 out of #87 files): <strong>211.5037169456482</strong></p>
<p>Pythonic way (Search stopped at first match, file #44 out of #87
files): <strong>177.46654987335205</strong></p>
<p>System grep using Popen: <strong>317.99017000198364</strong></p>
</blockquote>
<p>The results shows that the pythonic way is ~7% faster on worst case (string not found, or found in last file) and ~33% faster on average case (string found on file #61 out of #87 files)</p>
<p>The results didn't make any sense, so I tried to add --max-count 1 to grep, which means grep will stop searching within the file at first match, but it'll continue to search the other files.</p>
<pre><code>cmd = "grep {str} -rlm1 {dir}".format(str=str, dir=files_dir)
</code></pre>
<blockquote>
<p>System grep using Popen, String found in files: <strong>314.34678983688354</strong></p>
<p>System grep using Popen, String not found: <strong>309.60394191741943</strong></p>
</blockquote>
<p>It seems weird that the pythonic way is that much faster, am I missing something?</p>
| 3 | 1,186 |
How to access PHP table element with same name
|
<p>I have this SQL query</p>
<pre><code> $query="SELECT * FROM FLIGHTTABLE INNER JOIN AirplaneTable ON FLIGHTTABLE.AIRPLANEID = AirplaneTable.AIRPLANEID
INNER JOIN AIRPORTTABLE from_airport ON FLIGHTTABLE.AIRPORTDEPARTURE = from_airport.AIRPORTID
INNER JOIN AIRPORTTABLE to_airport ON FLIGHTTABLE.AIRPORTARRIVAL = to_airport.AIRPORTID
INNER JOIN ROUTETABLE route ON FLIGHTTABLE.AIRPORTARRIVAL = route.TOAIRPORTID && FLIGHTTABLE.AIRPORTDEPARTURE = route.FROMAIRPORTID
WHERE $dateofdeparture_update $dateofarrival_update $airportofdeparture_update $airportofarrival_update $id_update$seats_update $status_update;";
$res = mysql_query($query, GetMyConnection() );
if (!mysql_num_rows($res))
{
if ($id)
{
$results = array('success' => false, 'error' => 'Este voo não foi encontrado');
} else {
$results = array('success' => false, 'error' => 'Nenhum voo foi encontrado');
}
}
else
{
while($row = mysql_fetch_array($res))
{
//echo $row;
$data[] = array(
'id' => $row['FLIGHTID'],
'status' => $row['FLIGHTSTATUS'],
'reason' => $row['REASON'],
'airplane' => array(
'id' => $row['AIRPLANEID'],
'name' => $row['NAME']
),
'departure' => $row['DATEOFDEPARTURE'],
'arrival' => $row['DATEOFARRIVAL'],
'fromairport' => $row['AIRPORTDEPARTURE'],
'fromairportname' => $row['NAMEOFAIRPORT'],
'toairport' => $row['AIRPORTARRIVAL'],
'toairportname' => $row['NAMEOFAIRPORT'],
'price' => $row['PRICE'],
'availableseats' => $row['AVAILABLESEATS'],
'price' => $row['PRICE'],
'photo' => $row['PHOTO'],
);
}
$results = array('success' => true, 'data' => $data);
</code></pre>
<p>although <code>'fromairportname'</code> and <code>'toairportname'</code> should have different values they have the same value because <code>$row['NAMEOFAIRPORT']</code>,come out with the same value. How do I get the <code>$row['NAMEOFAIRPORT']</code> of the second inner join so that they show the actual departure and arrival datas?</p>
<p>Thanks</p>
| 3 | 1,372 |
Unable to install pycontractions
|
<p>I am trying to install <strong>pycontractions</strong> either over Jupyter Lap or PyCharm but I get an error.</p>
<p>Also tried to install packages individually but it failed.</p>
<p>I am using an Anaconda3 environment with Python 3.8</p>
<pre><code> command: 'c:\users\grue\anaconda3\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\grue\\AppData\\Local\\Temp\\pip-install-frozt89x\\language-check_ec3c23f7676848a7a4726feaea8d1549\\setup.py'"'"'; __file__='"'"'C:\\Users\\grue\\AppData\\Local\\Temp\\pip-install-frozt89x\\language-check_ec3c23f7676848a7a4726feaea8d1549\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\grue\AppData\Local\Temp\pip-wheel-ybyl27go'
cwd: C:\Users\grue\AppData\Local\Temp\pip-install-frozt89x\language-check_ec3c23f7676848a7a4726feaea8d1549\
Complete output (35 lines):
Traceback (most recent call last):
(DELETED THE TRACEBACK)
----------------------------------------
> ERROR: Failed building wheel for language-check
ERROR: Command errored out with exit status 1:
command: 'c:\users\grue\anaconda3\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\grue\\AppData\\Local\\Temp\\pip-install-frozt89x\\pyemd_742d1a148b744173aaa0f5e9a6ad4e6f\\setup.py'"'"'; __file__='"'"'C:\\Users\\grue\\AppData\\Local\\Temp\\pip-install-frozt89x\\pyemd_742d1a148b744173aaa0f5e9a6ad4e6f\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\grue\AppData\Local\Temp\pip-wheel-ac89795q'
cwd: C:\Users\grue\AppData\Local\Temp\pip-install-frozt89x\pyemd_742d1a148b744173aaa0f5e9a6ad4e6f\
Complete output (11 lines):
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-3.8
creating build\lib.win-amd64-3.8\pyemd
copying pyemd\__about__.py -> build\lib.win-amd64-3.8\pyemd
copying pyemd\__init__.py -> build\lib.win-amd64-3.8\pyemd
running build_ext
building 'pyemd.emd' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
----------------------------------------
> ERROR: Failed building wheel for pyemd
ERROR: Command errored out with exit status 1:
command: 'c:\users\grue\anaconda3\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\grue\\AppData\\Local\\Temp\\pip-install-frozt89x\\pyemd_742d1a148b744173aaa0f5e9a6ad4e6f\\setup.py'"'"'; __file__='"'"'C:\\Users\\grue\\AppData\\Local\\Temp\\pip-install-frozt89x\\pyemd_742d1a148b744173aaa0f5e9a6ad4e6f\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\grue\AppData\Local\Temp\pip-record-a9qsz6i5\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\grue\anaconda3\Include\pyemd'
cwd: C:\Users\grue\AppData\Local\Temp\pip-install-frozt89x\pyemd_742d1a148b744173aaa0f5e9a6ad4e6f\
Complete output (11 lines):
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.8
creating build\lib.win-amd64-3.8\pyemd
copying pyemd\__about__.py -> build\lib.win-amd64-3.8\pyemd
copying pyemd\__init__.py -> build\lib.win-amd64-3.8\pyemd
running build_ext
building 'pyemd.emd' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\grue\anaconda3\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\grue\\AppData\\Local\\Temp\\pip-install-frozt89x\\pyemd_742d1a148b744173aaa0f5e9a6ad4e6f\\setup.py'"'"'; __file__='"'"'C:\\Users\\grue\\AppData\\Local\\Temp\\pip-install-frozt89x\\pyemd_742d1a148b744173aaa0f5e9a6ad4e6f\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\grue\AppData\Local\Temp\pip-record-a9qsz6i5\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\grue\anaconda3\Include\pyemd' Check the logs for full command output.
</code></pre>
| 3 | 2,574 |
Django serializer does not throw error for flawed validated data
|
<p>I am running a django application and I have a simple class-based django-rest <code>CreateView</code>. My problem is that data actually gets created even though I sent flawed data. I am not entirely sure if that's expected behaviour, but I think it shouldn't be.</p>
<p>View is simple:</p>
<pre><code>class ModelCreate(CreateAPIView):
"""Create instance"""
serializer_class = ModelCreateSerializer
queryset = ModelCreate.objects.all()
</code></pre>
<p>In my serializer I am overwriting the create method for some custom behaviour and I am adding two write-only fields that I need for my data creation:</p>
<pre><code> class ModelCreate(serializers.ModelSerializer):
"""Serialize objects."""
field_extra1 = serializers.CharField(write_only=True, required=True)
field_extra2 = serializers.CharField(write_only=True, required=True)
class Meta:
model = ModelCreate
fields = (
"field_extra1",
"field_extra2",
"field3",
"field4",
"field5",
"field6",
"field7",
...
)
def create(self, validated_data):
"""Create obj and relate to other model."""
field_extra1 = validated_data.pop("field_extra1")
field_extra2 = validated_data.pop("field_extra2")
obj = Model.objects.get(name=field_extra1)
relation = obj.objects.filter(name=field_extra2)[0]
validated_data["relation"] = relation
result = ModelCreate.objects.create(**validated_data)
return result
</code></pre>
<p>My model has many optional fields.</p>
<pre><code> field_fk = models.ForeignKey(
Model,
on_delete=models.CASCADE,
related_name="building_objects",
)
field_m2m = models.ManyToManyField(
Model,
default=None,
blank=True,
)
field3 = models.CharField(
max_length=120,
null=True,
blank=True,
)
field4 = models.FloatField(
null=True,
blank=True,
validators=[MinValueValidator(0.0)],
)
field5 = models.FloatField(
null=True,
blank=True,
validators=[MinValueValidator(0.0), MaxValueValidator(1.0)]
)
field6 = models.FloatField(
null=True,
blank=True,
validators=[MinValueValidator(0.0)],
)
field7 = models.FloatField(
null=True,
blank=True,
validators=[MinValueValidator(0.0)],
)
</code></pre>
<p>Now what happens is that if I send a random made up extra field in my JSON the data gets created and the validated data just ignores the field:</p>
<p>Let's say I send data like this:</p>
<pre><code>data = {
"field_extra1": "foo",
"field_extra2": "foo",
"field3": "bar",
"field3": "bar",
"bullshit-field": "bullshitvalue",
}
r = requests.request(
"post",
json=data,
url=url,
)
print(r.status_code)
</code></pre>
<p>It creates the data without complaints.</p>
<p>What I expected is that the the serializer should notice that there is a bullshitfield and throw an error. Because what happens when I have a typo, it just ignores the field alltogether. So I doubt that this is the desired behaviour.</p>
<p>If this is in fact the standard behaviour is there a way to change it?</p>
<p>Thanks in advance for hints and help! Very much appreciated.</p>
| 3 | 1,589 |
How to Know records updated with Update query?
|
<p>How to know whether any record in the table updated with the update query or not.</p>
<p>I am using the Mysql C API..i have tried storing the mysql result after firing the UPDATE query but result is always returning NULL for successful upation also. Any help would be great.</p>
<p>Thanks</p>
<pre><code> int main(void)
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
if ((conn = mysql_init(NULL)) == NULL)
{
fprintf(stderr, "Could not init DB\n");
return EXIT_FAILURE;
}
if (mysql_real_connect(conn, "localhost", "root", "password", "cpaas", 0, NULL, 0) == NULL)
{
fprintf(stderr, "DB Connection Error\n");
return EXIT_FAILURE;
}
if (mysql_query(conn, "update calldirection set callid='Hello' where callid='He'") != 0)
{
fprintf(stderr, "Query Failure\n");
return EXIT_FAILURE;
}
res = mysql_store_result(conn);
if(res == NULL){
printf("dssdg");
return 1;
}
if ((row = mysql_num_rows(res)) <= 0)
{
printf("FFFFFFF");
}
mysql_close(conn);
return EXIT_SUCCESS;
}
</code></pre>
| 3 | 1,863 |
Why my list is empty when I am parsing correct json response?
|
<p>I am trying to print the ids from a JSON response. But I am not able to understand why I am getting a blank list. I have verified the JSONpath (SECTIONS_IDS_JSONPATH) from the online website and it is giving me correct results.</p>
<pre><code>public static void main(String[] args) {
String SECTIONS_IDS_JSONPATH = "$.[*].instructionEvents[*].sectionId";
String sectionsData = "{\"sections\":[{\"id\":\"8da1cf5d-3150-4e11-b2af-338d1df20475\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"courseCredits\":[{\"minimum\":4,\"maximum\":null,\"measure\":\"hour\",\"increment\":null}],\"academicPeriodId\":\"8b7a8e9e-5417-42a3-9c90-8d47226b5987\",\"reservedSeatsMaximum\":0,\"maxEnrollment\":0,\"hours\":[],\"sites\":[\"All Campuses\"],\"instructors\":[],\"instructionEvents\":[{\"id\":\"9d0c49e2-1579-43c3-b25a-2f85f551e62d\",\"sectionId\":\"8da1cf5d-3150-4e11-b2af-338d1df20475\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"days\":[\"monday\",\"wednesday\",\"friday\"],\"startTm\":\"2019-01-01T09:45:00-05:00\",\"endTm\":\"2024-12-01T10:45:00-05:00\",\"localizations\":[],\"instructionalMethod\":\"Lecture\"}]},{\"id\":\"ad3f63ad-e642-4938-a9fd-318afd2d1ad0\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"courseCredits\":[{\"minimum\":4,\"maximum\":null,\"measure\":\"hour\",\"increment\":null}],\"academicPeriodId\":\"8b7a8e9e-5417-42a3-9c90-8d47226b5987\",\"reservedSeatsMaximum\":0,\"maxEnrollment\":20,\"hours\":[],\"sites\":[\"All Campuses\"],\"instructors\":[{\"id\":\"c26572de-f9c8-4623-ba6a-79997b33f1c6\",\"sectionId\":\"ad3f63ad-e642-4938-a9fd-318afd2d1ad0\",\"role\":\"primary\",\"persons\":[{\"id\":\"c1b50d79-5505-4a33-9316-b4b1f52c0ca3\",\"names\":[{\"firstName\":\"BanColoFac-1\",\"lastName\":\"CTester\",\"preferred\":true}]}]}],\"instructionEvents\":[{\"id\":\"af8fb500-29f5-4451-95d5-a11215298cd4\",\"sectionId\":\"ad3f63ad-e642-4938-a9fd-318afd2d1ad0\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"days\":[\"tuesday\",\"thursday\"],\"startTm\":\"2019-01-01T10:00:00-05:00\",\"endTm\":\"2024-12-01T10:50:00-05:00\",\"localizations\":[],\"instructionalMethod\":\"Lecture\"}]},{\"id\":\"a1422391-e2b9-4bc4-907b-371fcea01d70\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"courseCredits\":[{\"minimum\":4,\"maximum\":null,\"measure\":\"hour\",\"increment\":null}],\"academicPeriodId\":\"8b7a8e9e-5417-42a3-9c90-8d47226b5987\",\"reservedSeatsMaximum\":0,\"maxEnrollment\":20,\"hours\":[],\"sites\":[\"All Campuses\"],\"instructors\":[{\"id\":\"808daae1-3ec6-47ec-9af0-5392199bdf78\",\"sectionId\":\"a1422391-e2b9-4bc4-907b-371fcea01d70\",\"role\":\"primary\",\"persons\":[{\"id\":\"793cc9b3-57c7-4a2d-8984-07a1fb6834a9\",\"names\":[{\"firstName\":\"Andrew\",\"lastName\":\"Adams\",\"preferred\":true}]}]}],\"instructionEvents\":[{\"id\":\"730b4206-684d-4413-bf20-9bec5c1dc900\",\"sectionId\":\"a1422391-e2b9-4bc4-907b-371fcea01d70\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"days\":[\"tuesday\",\"thursday\"],\"startTm\":\"2019-01-01T10:00:00-05:00\",\"endTm\":\"2024-12-01T10:50:00-05:00\",\"localizations\":[],\"instructionalMethod\":\"Lecture\"},{\"id\":\"8bc059ab-a8f8-4469-8e79-bbc71f7fa3fd\",\"sectionId\":\"a1422391-e2b9-4bc4-907b-371fcea01d70\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"days\":[\"monday\",\"wednesday\",\"friday\"],\"startTm\":\"2019-05-26T09:00:00-04:00\",\"endTm\":\"2021-05-26T09:50:00-04:00\",\"localizations\":[],\"instructionalMethod\":\"Lecture\"}]}]}";
List<String> ids = JsonPath.parse(sectionsData).read(SECTIONS_IDS_JSONPATH);
System.out.println(ids);
}
</code></pre>
| 3 | 2,951 |
multiple image input training using dataset object
|
<p>How to use a dataset object as input in the <code>model.fit()</code> training loop, for a model with multiple inputs?
Trying to pass the dataset itself gives me the following error:</p>
<pre><code>Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'tensorflow.python.data.ops.dataset_ops.MapDataset'>"}), <class 'NoneType'>
</code></pre>
<p>My case here:</p>
<p>I have a multiple input model built with keras
The inputs are named <code>'First'</code>, <code>'Second'</code> and <code>'Third'</code></p>
<p>I have an image dataset in keras-style:</p>
<pre><code>main_directory/
...class_a/
......a_image_1.jpg
......a_image_2.jpg
...class_b/
......b_image_1.jpg
......b_image_2.jpg
</code></pre>
<p>I create the dataset object using <code>tf.keras.utils.image_dataset_from_directory</code>:</p>
<pre><code>train_dataset = image_dataset_from_directory(train_dir,
shuffle=False,
label_mode='categorical',
batch_size=hyperparameters["BATCH_SIZE"],
image_size=IMG_SIZE)
</code></pre>
<p>Now, each image is divided in 3 parts, each part serving as input to each of the inputs of the model. I take care of that using some map functions. This is not relevant tot he problem and I will not include it. I cannot use the cropping layers included in TF because of unrelated reasons.</p>
<p>I then try to start the training loop:</p>
<pre><code> history = model.fit([train_dataset1,
train_dataset2,
train_dataset3,
],
epochs=epochs,
callbacks=callbacks,
validation_data=validation_dataset
validation_steps=steps
)
</code></pre>
<p>And here is where I get the error.
I have tried some other approaches, like using a dict instead of a list.
The problem seems to be that when training a model with multiple inputs, the fit() loop expects data to come as a list for x-values and a list for y-values, but I haven't been able to split the dataset object into the required formats</p>
<p>I have read many topics on this, but all use datasets that are created using the <code>tf.data.Dataset.from_tensor_slices()</code> method, which is not applicable in my case</p>
<p>Additionally, there is no indication of how the validation dataset has to be structured (at least according to the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit" rel="nofollow noreferrer">model.fit() documentation</a>)</p>
<p>I have found some guidance saying that the validation dataset must have the same number of input/outputs as the training datasets (makes sense), but again, no indication on how to build or feed the validation dataset for a multiple input model</p>
| 3 | 1,179 |
How to save in database value with vue js?
|
<p>This calendar is made with vuejs.</p>
<p><a href="https://i.stack.imgur.com/UpMxZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UpMxZ.png" alt="calendar" /></a></p>
<p>But the problem I have, After selecting the date, it does not store any value in the database.</p>
<p>I want to store a vuejs component in a database. Is there some sort of serialization procedure/package that I can use to serialize vuejs components?</p>
<pre><code><div class="modal-body">
<form method="post">
@csrf
@method('PUT')
<input type="hidden" id="id">
<div class="row">
<div class="col-md-6 mb-3">
<label for="edit_start_date">تاریخ شروع به كار</label>
<date-picker type="date" id="edit_start_date" name="start_date"></date-picker>
</div>
<div class="col-md-6 mb-3">
<label for="edit_end_date">تاریخ خاتمه كار</label>
<date-picker type="date" id="edit_end_date" name="end_date"></date-picker>
</div>
</div>
</form>
</div>
</code></pre>
<p>script</p>
<pre><code>$(document).on('click', '#jobEdit', function(event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
type:'get',
url:'/job/'+id+'/edit',
success:function (data) {
console.log(data);
$('#id').val(data.job.id);
$('#edit_employment_type').val(data.job.employment_type);
$('#edit_job_type').val(data.job.job_type);
$('#edit_history').val(data.job.history);
$('#edit_post_title').val(data.job.post_title);
$('#edit_state_id').val(data.job.state_id);
$('#edit_city_id').val(data.job.city_id);
$('#edit_start_date').val(data.job.start_date);
$('#edit_end_date').val(data.job.end_date);
},
});
});
$(document).on('click', '#jobUpdate', function(event) {
event.preventDefault();
var id = $('#id').val();
var data = {
'employment_type' : $('#edit_employment_type').val(),
'job_type' : $('#edit_job_type').val(),
'history' : $('#edit_history').val(),
'post_title' : $('#edit_post_title').val(),
'state_id' : $('#edit_state_id').val(),
'city_id' : $('#edit_city_id').val(),
'start_date' : $('#edit_start_date').val(),
'end_date' : $('#edit_end_date').val(),
}
$.ajax({
type: 'PUT',
url: '/job/'+id,
data: data,
dataType: 'JSON',
success: function (response) {
console.log(response);
$('#jobModal').modal('hide');
showJobs();
},
});
});
</code></pre>
| 3 | 1,562 |
Navigation stack error while using EKF_localizatio_node with Turtlebot2
|
<p>I am using Turtlebot2 on Noetic, my navigation stack works fine when I use AMCL or fake localization as the localizer. However, due to the need of my research, I want to use EKF_localization_node as the localizer which means that my tf [map] -> [odom] is published by EKF_localizatio_node.</p>
<p>While using EKF_localizatio_node, my move_base has this error:</p>
<p>I have already tried to follow the solution provided on this website: <a href="https://answers.ros.org/question/3045.." rel="nofollow noreferrer">https://answers.ros.org/question/3045..</a>.</p>
<p>by writing a subscriber who subscribes to /tf and adds its stamp with
rospy.Duration.from_sec(0.5).</p>
<pre><code> def tf_callback(data):
if data.transforms[0].header.frame_id == 'map':
data.transforms[0].header.stamp = data.transforms[0].header.stamp + rospy.Duration.from_sec(0.5)
</code></pre>
<p>But this still doesn't work.</p>
<p>My ekf node is shown as follows:</p>
<pre><code><node pkg="robot_localization" type="ekf_localization_node" name="robot_localization_ekf_node_map clear_params="true">
<param name="frequency" value="10" />
<param name="sensor_timeout" value="2" />
<param name="two_d_mode" value="true" />
<param name="publish_tf" value="true" />
<param name="map_frame" value="map" />
<param name="odom_frame" value="odom" />
<param name="base_link_frame" value="base_link" />
<param name="world_frame" value="map" />
<param name="twist0" value="/cmd_vel_mux/input/teleop" />
<rosparam param="twist0_config">
[false, false, false, false, false, false,
true, true, false, false, false, true,
false, false, false]</rosparam>
<param name="pose0" value="/pose" />
<rosparam param="pose0_config">
[true, true, false, false, false, true,
false, false, false, false, false, false,
false, false, false]</rosparam>
<remap from="odometry/filtered" to="odometry/filtered_map"/>
</node>
</code></pre>
<p>I have also tried to increase the frequency, it has a little bit improved (generate the global path, but nearly not develop the local plan, which means that sometimes it moves following the global path, but most of the time it stops or just rotates). Note that /pose is a topic I publish, and the value is subscribed from gazebo model_state, I have checked it. I think it works fine.</p>
<p>Any suggestions would be appreciated.</p>
| 3 | 1,115 |
Switching from "if" to "elseif" breaks code
|
<p>I'm using multiple if statements to check a containing div, and output an image based on the container name. The code was working fine until I add a final "else" or change the if's out to elseif and I can't figure out why that's happening. When I try to add the else or elseif, the entire page fails to load. Any idea why this is happening? </p>
<pre><code> <?php
if($viewMore['container_type'] == 'Large IMG' || $viewMore['container_type'] == 'Gallery') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'large_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$large = 0; foreach ($photoArray as $photo => $upload): if (++$large == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach ?>
<?php } ?>
<?php
elseif($viewMore['container_type'] == 'Medium IMG') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'small_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$medium = 0; foreach ($photoArray as $photo => $upload): if (++$medium == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach; ?>
<?php } ?>
<?php else { ?> SOMETHING HERE <?php } ?>
</code></pre>
<p>EDIT:</p>
<p>Other notes</p>
<p>I've tried wrapping the break; in brackets because I thought that piece following the count might be messing with something. Also removing the counter altogether or adding a semi colon after the endforeach didn't help. </p>
| 3 | 1,139 |
Libreswan Route-based VPN
|
<p>I'm trying to configure IPSEC tunnel between two virtual machines (R2 R3) in the same network where one of them would work as a router (R2) so I can send data from third virtual machine (R1) over the IPSEC tunnel to R3.</p>
<p>I have made the following topology:</p>
<p><a href="https://i.stack.imgur.com/ZsJc1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZsJc1.png" alt="enter image description here" /></a></p>
<p>I changed IP addresses wrong but the VM's are in the same network so it could be like R3: 1.2.3.4, R2: 1.2.3.5, R1: 1.2.3.6</p>
<p>Configuration of R3 VM /etc/ipsec.d/mytunnel.conf:</p>
<pre><code>config setup
protostack=netkey
#conn mysubnet
# also=mytunnel
# leftsubnet=10.0.1.1/24
# rightsubnet=10.0.0.1/24
# auto=start
conn mytunnel
left=4.6.7.8
right=1.2.3.4
authby=secret
leftsubnet=10.0.1.1/24
rightsubnet=10.0.0.1/24
auto=start
# route-based VPN requires marking and an interface
mark=5/0xffffffff
vti-interface=vti03
# do not setup routing because we don't want to send 0.0.0.0/0 over the tunnel
vti-routing=yes
# If you run a subnet with BGP (quagga) daemons over IPsec, you can configure the VTI interface
leftvti=10.0.7.1/24
</code></pre>
<p>Configuration of R2 /etc/ipsec.d/mytunnel.conf:</p>
<pre><code>config setup
protostack=netkey
#conn mysubnet
# also=mytunnel
# leftsubnet=10.0.1.1/24
# rightsubnet=10.0.0.1/24
# auto=start
conn mytunnel
left=4.6.7.8
right=1.2.3.4
authby=secret
leftsubnet=10.0.1.1/24
rightsubnet=10.0.0.1/24
auto=start
# route-based VPN requires marking and an interface
mark=5/0xffffffff
vti-interface=vti03
# do not setup routing because we don't want to send 0.0.0.0/0 over the tunnel
vti-routing=yes
# If you run a subnet with BGP (quagga) daemons over IPsec, you can configure the VTI interface
leftvti=10.0.7.1/24
</code></pre>
<p>With the configuration above I can ping from R2 to R3 with ping -I 10.0.1.1 10.0.0.1</p>
<p>On the R1 machine I configured static routing which is:</p>
<pre><code>root@9.10.11.12:~# ip route
default via 9.10.11.1 dev ens18 onlink
10.0.0.0/24 via 5.6.7.8 dev ens18
10.0.1.0/24 via 5.6.7.8 dev ens18
</code></pre>
<p>But when I want to ping 10.0.0.1 from R1 via R2 it gives me <code>icmp_seq=1 Destination Host Unreachable</code></p>
<p>What should I change so R1 could see R3 via R2 dummy0 interface which is 10.0.1.1 ?</p>
<p>Thanks for any help!</p>
| 3 | 1,089 |
Python - webscraping to go several depth-levels within a page with requests module
|
<p>I have a Python3 script that is performing web scraping based on the urls provided in a csv file.
I am trying to achieve the following:</p>
<p>1.) Get a page from the URL provided in the CSV file</p>
<p>2.) Scrape it and search for email addresses with regex + beautifulsoup, then, if email is found, save it to a results.csv file</p>
<p>3.) Search for all other (links) on the page</p>
<p>4.) Go to/get all the links found in the 1st page (1st level of scraping) and do the same</p>
<p>5.) Perform the same based on the user's defined level of depth (if the user would say go 3 levels deeper than it would do this: Get the page from 1st level (url from CSV file) and do what is needed on that page -> Get all the pages from 2nd level (scraped links from 1st level) and do what is needed -> Get all the pages from 3rd level (scraped links from 2nd level) and do what is needed -> and so on...</p>
<p>How do I create a loop which would take care of the depth-level scraping?
I have tried playing with multiple variants of for and while loops, but I am unable to come up with a working solution.</p>
<p>This is the code that I currently have (currently it's only able to take care of the 1st level scraping):</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import csv
import re
import time
import sys, os
#Type the amount of max level of depth for this instance of script
while True:
try:
max_level_of_depth = int(input('Max level of depth for webscraping (must be a number - integer): '))
print('Do not open the input and neither the output CSV files before the script finishes!')
break
except:
print('You must type a number (integer)! Try again...\n')
#Read the csv file with urls
with open('urls.csv', mode='r') as urls:
#Loop through each url from the csv file
for url in urls:
#Strip the url from empty new lines
url_from_csv_to_scrape = url.rstrip('\n')
print('[FROM CSV] Going to ' + url_from_csv_to_scrape)
#time.sleep(3)
i = 1
#Get the content of the webpage
page = requests.get(url_from_csv_to_scrape)
page_content = page.text
soup = BeautifulSoup(page_content, 'lxml')
#Find all <p> tags on the page
paragraphs_on_page = soup.find_all('p')
for paragraph in paragraphs_on_page:
#Search for email address in the 1st level of the page
emails = re.findall(r'[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,5}', str(paragraph))
#If some emails are found on the webpage, save them to csv
if emails:
with open('results.csv', mode='a') as results:
for email in emails:
print(email)
if email.endswith(('.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG')):
continue
results.write(url_from_csv_to_scrape + ', ' + email + '\n')
print('Found an email. Saved it to the output file.\n')
results.close()
#Find all <a> tags on the page
links_on_page = soup.find_all('a')
#Initiate a list with all links which will later be populated with all found urls to be crawled
found_links_with_href = []
#Loop through all the <a> tags on the page
for link in links_on_page:
try:
#If <a> tag has href attribute
if link['href']:
link_with_href = link['href']
#If the link from the webpage does not have domain and protocol in it, prepend them to it
if re.match(r'https://', link_with_href) is None and re.match(r'http://', link_with_href) is None:
#If the link already has a slash in it, remove it because it will be added after prepending
link_with_href = re.sub(r'/', '', link_with_href)
#Prepend the domain and protocol in front of the link
link_with_href = url_from_csv_to_scrape + link_with_href
#print(link_with_href)
found_links_with_href.append(link_with_href)
found_links_with_href_backup = found_links_with_href
except:
#If <a> tag does not have href attribute, continue
print('No href attribute found, going to next <a> tag...')
continue
</code></pre>
<p>Any help is much appreciated.</p>
<p>Thank you</p>
| 3 | 1,976 |
How to find probability of subsequences obtained from sequences in the given dataset?
|
<p>I have a dataset(CSV file) of sequence of links with their order placed status for each sequence. I have got the subsequences with their count with the help of prefixSpan algorithm(as described <a href="https://github.com/sequenceanalysis/sequenceanalysis.github.io/blob/master/notebooks/part2.ipynb" rel="nofollow noreferrer">here</a>).
But I also want to find probability of each subsequences in leading to order placed =1. Suppose links are <code>a</code> ,<code>b</code>,<code>c</code>,<code>d</code> and their sequences and order status are as follows in data frame:</p>
<pre><code> Link sequences Order status
a,b,c,a,c,c 0
a,c,b,c 1
a,b,d,c,b,c 1
a,c,b,c 0
</code></pre>
<p>Subsequences I get if I put minimum Support =4 with help of prefixSpan algorithm</p>
<pre><code> Subsequences Support
[a] 4
[a,b] 4
[a,b,c] 4
[a,c] 4
[a,c,c] 4
[b] 4
[b,c] 4
[c] 4
[c,c] 4
</code></pre>
<p>What changes should I make in prefixSpan algorithm code as mentioned in above link to get probability also as following :</p>
<pre><code>Subsequence Support Prob
[a] 4 0.5
[a,b] 4 0.5
[a,b,c] 4 0.5
[a,c] 4 0.5
[a,c,c] 4 0.5
[b] 4 0.5
[b,c] 4 0.5
[c] 4 0.5
[c,c] 4 0.5
</code></pre>
<p>The procedure used to calculate probability of the subsequence is:</p>
<p>Add order placed status of all sequences where the subsequence is present and divide it by count of sequences where it is present eg : </p>
<pre><code>P(subsequence [a,c,c]) =( 0+1+1+0)/4 = 0.5
</code></pre>
| 3 | 1,317 |
Adapting a Win8 store app tutorial to WPF
|
<p>I'm following <a href="http://www.youtube.com/watch?feature=player_embedded&v=m-EqckhJNvI" rel="nofollow">this tutorial</a> that explains how to create a Dial in Visual Studio with XAML/C#. The problem is that the tutorial is targeted for windows 8 store apps.</p>
<p>Knowing that, I still tried to use this tutorial in a WPF application that will support previous OSs too.</p>
<p>I came across a few compatibility problems:</p>
<ol>
<li><code>ManipulationMode="All"</code> doesn't exists as the author of the tutorial uses it for me. It only exists as <code>Manipulation.ManipulationMode="All"</code> which gives me an error "Manipulation is not active on the specified element". How could I solve it?</li>
<li>The author set the <code>ManipulationDelta</code> property on the <code>grid</code> element, which I didn't have problem with at first... Until I realized the author's event/action code-behind created by VS uses <code>ManipulationDeltaRoutedEventArgs e</code> instead of the <code>ManipulationDeltaEventArgs e</code> which is used in my code-behind file. This means I can't use the <code>Position</code> property (<code>e.Position</code>) to get the mouse position on the user control as easily. What could be an alternative to it? I don't think it could be supported as it was declared as Win8 only...</li>
<li>In an MVVM-style application, the code-behind actions would have been set in the <code>ViewModel</code>. How would I 'bind' that action code to the <code>ManipulationDelta</code> property of an element?</li>
</ol>
<p>Thanks in advance!</p>
<p>P.S; Both mine and the author's version of VS is 2012 so that's not the problem.</p>
<p>UPDATE:
Here's the partially-completed code: </p>
<p>The XAML:</p>
<pre><code>//Manipulation.ManipulationMode="All" => ERROR 'Manipulation is not active on the specified element'
<Grid Manipulation.ManipulationMode="All" ManipulationDelta="Grid_ManipulationDelta_1">
<Ellipse Fill="#FF7171E6" Margin="30"/>
<Grid>
<Grid.RenderTransform>
<RotateTransform CenterX="225" CenterY="225" Angle="{Binding Angle}"/>
</Grid.RenderTransform>
<Ellipse Fill="White" Height="100" VerticalAlignment="Top" Margin="50" Width="100"/>
</Grid>
</Grid>
</code></pre>
<p>The code-behind:</p>
<pre><code>public partial class dial : UserControl, INotifyPropertyChanged
{
private int m_Amount;
public int Amount {...}
private double m_Angle;
public double Angle {...}
public dial()
{
InitializeComponent();
this.DataContext = this;
}
private void Grid_ManipulationDelta_1(object sender, ManipulationDeltaEventArgs e)
{
this.Angle = GetAngle(e.Position, this.RenderSize); //e.Position doesn't exist in ManipulationDeltaEventArgs...
this.Amount = (int)(this.Angle / 360 * 100);
}
public enum Quadrants : int { nw = 2, ne = 1, sw = 4, se = 3 }
private double GetAngle(Point touchPoint, Size circleSize)
{
var _X = touchPoint.X - (circleSize.Width / 2d);
var _Y = circleSize.Height - touchPoint.Y - (circleSize.Height / 2d);
var _Hypot = Math.Sqrt(_X * _X + _Y * _Y);
var _Value = Math.Asin(_Y / _Hypot) * 180 / Math.PI;
var _Quadrant = (_X >= 0) ?
(_Y >= 0) ? Quadrants.ne : Quadrants.se :
(_Y >= 0) ? Quadrants.nw : Quadrants.sw;
switch (_Quadrant)
{
case Quadrants.ne: _Value = 090 - _Value; break;
case Quadrants.nw: _Value = 270 + _Value; break;
case Quadrants.se: _Value = 090 - _Value; break;
case Quadrants.sw: _Value = 270 + _Value; break;
}
return _Value;
}
public event PropertyChangedEventHandler PropertyChanged;
}
</code></pre>
| 3 | 1,432 |
understanding "slice" in console in Jquery/javascript
|
<p>i am deconstructing a carasoul plugin called Unslider.js , and i have a difficulty understanding a little peice of code , so here i am on stack overflow . </p>
<p>My difficulty is understanding the below line : </p>
<pre><code>target = li.eq(index);
</code></pre>
<p>lets analyse that , </p>
<p><strong>target</strong> is a variable . </p>
<p><strong>li</strong> is an object , actually let me clarify what li is , previously in the code using the find() method in Jquery which returns a set of child elements so basically li is a set of <code><li></code> elements . </p>
<p>next , <strong>eq</strong> is often used to filter element further . </p>
<p><strong>index</strong> is ofcourse the current element (i am not sure about this interpretation though) . </p>
<p>so basically i understand the below line : </p>
<pre><code> target = li.eq(index);
</code></pre>
<p>target is the current li element, am i right , i think so . </p>
<p>well lets move on to what my real difficulty is , when i console.log(target) , i get the following results : </p>
<pre><code>"taget is" unslider.js:285
Object { length: 0, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(3,4)" } unslider.js:286
"taget is" unslider.js:285
Object { 0: <li>, length: 1, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(1,2)" } unslider.js:286
"taget is" unslider.js:285
Object { 0: <li>, length: 1, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(2,3)" } unslider.js:286
"taget is" unslider.js:285
Object { length: 0, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(3,4)" } unslider.js:286
"taget is" unslider.js:285
Object { 0: <li>, length: 1, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(1,2)" } unslider.js:286
"taget is" unslider.js:285
Object { 0: <li>, length: 1, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(2,3)" } unslider.js:286
"taget is" unslider.js:285
Object { length: 0, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(3,4)" } unslider.js:286
"taget is" unslider.js:285
Object { 0: <li>, length: 1, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(1,2)" } unslider.js:286
"taget is" unslider.js:285
Object { 0: <li>, length: 1, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(2,3)" } unslider.js:286
"taget is" unslider.js:285
Object { length: 0, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(3,4)" } unslider.js:286
"taget is" unslider.js:285
Object { 0: <li>, length: 1, prevObject: Object, context: <div.banner>, selector: ">ul >li.slice(1,2)" }
</code></pre>
<p>now what does this line mean .. </p>
<pre><code>selector: ">ul >li.slice(3,4)",
</code></pre>
<p>i mean the <code>slice(3,4)</code> part and that part keeps changing with different values !! it would be great if somebody could come along and explain what that is . </p>
<p>Thank you. </p>
<p>Alexander. </p>
| 3 | 1,241 |
basic rails model has_many and belongs_to with group by date
|
<p>I'm a rails newbie so pardon if this is a basic question. I'm setting up some models and the relationships should be pretty basic, but I'm a little stuck in the best way to set everything up.</p>
<p>I'm trying to display a list of seminars that have different times. Here are my two tables:</p>
<pre><code>create_table "seminars", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "seminar_times", :force => true do |t|
t.datetime "start_date"
t.datetime "end_date"
t.integer "seminar_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
</code></pre>
<p>I'd like to display my seminars at localhost:3000/seminars like so:</p>
<pre><code>Intro To Rails Aug 1 3-5pm and 6-8pm
How To Juggle Aug 10 6-8pm
Stackoverflow Rocks Aug 13 2-5pm or 6-8pm
</code></pre>
<p>One seminar can have many different seminar times (which is why i put them into two separate tables). To do this normally with straight SQL I'd join the tables, order by start_date, then group by DAY and by seminar id.</p>
<p>How would I do this the "rails way"?</p>
<p>Here's what I've done so far, but it doesn't seem like the right way to go.</p>
<p>Seminar model:</p>
<pre><code>class Seminar < ActiveRecord::Base
attr_accessible :name
has_many :seminar_times, :dependent => :destroy
validates :name, :presence => true
end
</code></pre>
<p>SeminarTime model:</p>
<pre><code>class SeminarTime < ActiveRecord::Base
attr_accessible :end_date, :seminar_id, :start_date
belongs_to :seminar, :foreign_key => 'seminar_id'
default_scope :order => 'start_date'
end
</code></pre>
<p>seminars_controller:</p>
<pre><code>def index
@seminars = SeminarTime.group('date(start_date), seminar_id') #THIS LINE ESPECIALLY SEEMS WRONG TO ME
respond_to do |format|
format.html # index.html.erb
format.json { render json: @seminars }
end
end
</code></pre>
<p>seminar_times_controller:</p>
<pre><code>def index
@seminar_times = SeminarTime.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @seminar_times }
end
end
</code></pre>
<p>routes.rb</p>
<pre><code>resources :seminars
resources :seminar_times
root to: 'static_pages#home'
match '/seminars', to: 'seminars#index'
</code></pre>
<p>views/seminars/index.html.erb:</p>
<pre><code>#this also needs some work. i'm not sure how to loop into that group by statement
<% @seminars.each do |seminar| %>
<%= seminar.seminar.name %>
<%= seminar.start_date %>
<%= seminar.end_date %>
<% end %>
</code></pre>
<p>I've tried also getting everything through the seminar_times_controller and then routing /seminars to:
match '/seminars', to: 'seminar_times#index'
but that also seems kinda off to me.</p>
<p>Hopefully I'm being clear enough. Any guidance is much appreciated. Thanks!</p>
<hr>
<p>My app evolved some since I asked this question. I ended up adding some categories, so I made a shared module so I could use my sorting code throughout the app. The sort and grouping looks like this:</p>
<pre><code>module Shared
def self.category_group_by_day(categories_array)
seminars = Seminar.joins(:seminar_times, :categories).
where(:categories => {:name => categories_array}).
where("date(start_time) > ?", DateTime.now)
seminars.sort_by! { |s| s.start_date }
seminar_days = seminars.group_by { |s| [s.start_date.beginning_of_day, s.course_id] }
end
end
</code></pre>
<p>I call it in my controller like this:</p>
<pre><code>@seminar_days = Shared::category_group_by_day(['Free Seminar', 'Online Seminar'])
</code></pre>
<p>And then in my view:</p>
<pre><code><% @seminar_days.keys.sort.each do |day| %>
<%= @seminar_days[day].first.course_name %>
<%= day.to_s.to_date.strftime("%b %e") %> <%= day.to_s.to_date.strftime("%a") %>
<% for seminar in @seminar_days[day] %>
<div>
<%= seminar.start_date.strftime("%l").strip %>—<%= seminar.end_date.strftime("%l").strip %> <%= seminar.end_date.strftime("%p") %>
</div>
<% end %>
<% end %>
</code></pre>
| 3 | 1,695 |
Sometime Postgresql Query takes to much time to load Data
|
<p>I am using PostgreSQL 13.4 and has intermediate level experience with PostgreSQL.</p>
<p>I have a table which stores reading from a device for each customer. For each customer we receive around ~3,000 data in a day and we store them in to our <code>usage_data</code> table as below</p>
<p><a href="https://i.stack.imgur.com/RKPbn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RKPbn.png" alt="enter image description here" /></a></p>
<p>We have the proper indexing in place.</p>
<pre><code> Column | Data Type | Index name | Idx Access Type
-------------+-----------------------------+---------------------------+---------------------------
id | bigint | |
customer_id | bigint | idx_customer_id | btree
date | timestamp | idx_date | btree
usage | bigint | idx_usage | btree
amount | bigint | idx_amount | btree
</code></pre>
<p>Also I have common index on 2 columns which is below.</p>
<p><strong>CREATE INDEX idx_cust_date
ON public.usage_data USING btree
(customer_id ASC NULLS LAST, date ASC NULLS LAST)</strong>
;</p>
<p><strong>Problem</strong></p>
<p>Few weird incidents I have observed.
When I tried to get data for 06/02/2022 for a customer it took almost 20 seconds. It's simple query as below</p>
<pre><code>SELECT * FROM usage_data WHERE customer_id =1 AND date = '2022-02-06'
</code></pre>
<p>The execution plan
<a href="https://i.stack.imgur.com/YlZFx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YlZFx.jpg" alt="enter image description here" /></a></p>
<p>When I execute same query for 15 days then I receive result in 32 milliseconds.</p>
<pre><code>SELECT * FROM usage_data WHERE customer_id =1 AND date > '2022-05-15' AND date <= '2022-05-30'
</code></pre>
<p>The execution plan
<a href="https://i.stack.imgur.com/I7ZzA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I7ZzA.jpg" alt="enter image description here" /></a></p>
<p><strong>Tried Solution</strong></p>
<p>I thought it might be the issue of indexing as for this particular date I am facing this issue.</p>
<p>Hence I dropped all the indexing from the table and recreate it.</p>
<p>But the problem didn't resolve.</p>
<p><strong>Solution Worked (Not Recommended)</strong></p>
<p>To solve this I tried another way. Created a new database and restored the old database
I executed the same query in new database and this time it takes 10 milliseconds.</p>
<p>The execution plan
<a href="https://i.stack.imgur.com/SDKbu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SDKbu.jpg" alt="enter image description here" /></a></p>
<p>I don't think this is proper solution for <strong>production server</strong></p>
<p>Any idea why for any specific data we are facing this issue?
Please let me know if any additional information is required.</p>
<p>Please guide. Thanks</p>
| 3 | 1,169 |
failed to connect to all addresses exception when trying to connect GRPC server from a winforms app
|
<p>Hello grpc newbie here,</p>
<p>I've a winforms application that I want to connect to a grpc server.</p>
<p>I have no problem running the grpc server on localhost and make a connection to it with the winforms app.</p>
<p>I've deployed my grpc server to a temporary url : <a href="http://mujf94-001-site1.gtempurl.com/" rel="nofollow noreferrer">http://mujf94-001-site1.gtempurl.com/</a></p>
<p>but when I try to connect it I get the following error:</p>
<pre><code>Status(StatusCode="Unavailable", Detail="failed to connect to all addresses",
DebugException="Grpc.Core.Internal.CoreErrorDetailException:
{"created":"@1630271164.373000000","description":"Failed to pick
subchannel","file":"..\..\..\src\core\ext\filters\client_channel\client_channel.cc",
"file_line":3009,"referenced_errors":[{"created":"@1630271164.373000000","description":
"failed to connect to all addresses","file":"..\..\..\src\core\ext\filters\client_channel\
lb_policy\pick_first\pick_first.cc","file_line":398,"grpc_status":14}]}")
</code></pre>
<p>This is how I try connecting to the grpc server:</p>
<pre><code> var ip = "mujf94-001-site1.gtempurl.com".ToIPAddress();
var channel = new Channel(ip.ToString(),80, ChannelCredentials.Insecure);
//var channel = new Channel("http://mujf94-001-site1.gtempurl.com", 80, ChannelCredentials.Insecure);
Client = channel.CreateGrpcService<T>();
</code></pre>
<p>and my grpc server options are like this:</p>
<pre><code>public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
webBuilder.ConfigureKestrel(options =>
{
options.Listen("mujf94-001-site1.gtempurl.com".ToIPAddress(), 80, o => o.Protocols = HttpProtocols.Http2);
});
webBuilder.UseStartup<Startup>();
});
</code></pre>
<p>I'm very new to this so any help is very appreciated</p>
| 3 | 1,037 |
How do I get rid of the \t within this python regex match object?
|
<p>The data is derived from this page:
<a href="https://simple.wikipedia.org/wiki/List_of_U.S._states_by_population" rel="nofollow noreferrer">https://simple.wikipedia.org/wiki/List_of_U.S._states_by_population</a></p>
<pre><code>text = '''
1 1 California 39,512,223 37,254,523 6.1% +2,257,700 53 718,404 745,514 702,885 11.96%
2 2 Texas 28,995,881 25,145,561 15.3% +3,850,320 36 763,050 805,441 698,503 8.68%
3 4 Florida 21,477,737 18,801,310 14.2% +2,676,427 27 740,611 795,472 696,468 6.44%
4 3 New York 19,453,561 19,378,102 0.4% +75,459 27 670,812 720,502 717,707 5.91%
5 6 Pennsylvania 12,801,989 12,702,379 0.8% +99,610 18 640,099 711,222 705,715 3.87%
6 5 Illinois 12,671,821 12,830,632 -1.2% −158,811 18 633,591 703,990 712,864 3.85%
7 7 Ohio 11,689,100 11,536,504 1.3% +152,596 16 649,394 730,569 721,032 3.53%
8 9 Georgia 10,617,423 9,687,653 9.6% +929,770 14 663,589 758,387 691,975 3.18%
9 10 North Carolina 10,488,084 9,535,483 10.0% +952,601 13 699,206 806,776 733,498 3.14%
10 8 Michigan 9,986,857 9,883,640 1.0% +103,217 14 624,179 713,347 705,974 3.02%
11 11 New Jersey 8,882,190 8,791,894 1.0% +90,296 12 634,442 740,183 732,658 2.69%
12 12 Virginia 8,535,519 8,001,024 6.7% +534,495 11 656,578 775,956 727,366 2.58%
13 13 Washington 7,614,893 6,724,540 13.2% +890,353 10 634,574 751,489 672,454 2.28%
14 16 Arizona 7,278,717 6,392,017 13.9% +886,700 9 661,702 808,746 710,224 2.17%
15 14 Massachusetts 6,949,503 6,547,629 5.3% +344,874 9 626,591 765,834 727,514 2.09%
16 17 Tennessee 6,833,174 6,346,105 7.6% +483,069 9 620,834 758,797 705,123 2.05%
17 15 Indiana 6,732,219 6,483,802 3.8% +248,417 9 612,020 748,024 720,422 2.02%
18 18 Missouri 6,137,428 5,988,927 2.5% +148,501 8 613,743 767,179 748,615 1.85%
19 19 Maryland 6,045,680 5,773,552 4.7% +272,128 8 604,568 755,710 721,694 1.83%
20 20 Wisconsin 5,822,434 5,686,986 2.4% +135,448 8 582,243 727,804 710,873 1.76%
21 22 Colorado 5,758,736 5,029,196 14.5% +729,540 7 639,860 822,677 720,704 1.72%
22 21 Minnesota 5,639,632 5,303,925 6.3% +335,707 8 563,963 704,954 662,991 1.70%
23 24 South Carolina 5,148,714 4,625,364 11.3% +523,350 7 572,079 735,531 660,766 1.54%
24 23 Alabama 4,903,185 4,779,736 2.6% +123,449 7 544,798 700,455 682,819 1.48%
25 25 Louisiana 4,648,794 4,533,372 2.5% +115,422 6 581,099 774,799 755,562 1.41%
26 26 Kentucky 4,467,673 4,339,367 3.0% +128,306 6 558,459 744,612 723,228 1.35%
27 27 Oregon 4,217,737 3,831,074 10.1% +386,663 5 602,534 843,547 766,215 1.27%
28 28 Oklahoma 3,956,971 3,751,351 5.5% +205,620 5 565,282 791,394 750,270 1.19%
29 30 Connecticut 3,565,287 3,574,097 -0.2% −8,810 5 509,327 713,057 714,824 1.08%
30 35 Utah 3,205,958 2,763,885 16.0% +442,073 4 534,326 801,490 690,972 0.96%
32 31 Iowa 3,155,070 3,046,355 3.6% +108,715 4 525,845 788,768 761,717 0.95%
31 29 Puerto Rico 3,193,694 3,725,789 -14.3% −532,095 1 (non-voting) — 3,193,694 3,725,789 0.97%
33 36 Nevada 3,080,156 2,700,551 14.1% +379,605 4 513,359 770,039 675,173 0.92%
34 33 Arkansas 3,017,825 2,915,918 3.5% +101,886 4 502,967 754,451 728,990 0.91%
35 32 Mississippi 2,976,149 2,967,297 0.3% +8,852 4 496,024 744,037 742,026 0.90%
36 34 Kansas 2,913,314 2,853,118 2.1% +60,196 4 485,552 728,329 713,280 0.88%
37 37 New Mexico 2,096,829 2,059,179 1.8% +37,650 3 419,366 698,943 686,393 0.63%
38 39 Nebraska 1,934,408 1,826,341 5.9% +108,067 3 386,882 644,803 608,780 0.58%
39 40 Idaho 1,792,065 1,567,582 13.9% +218,483 2 446,516 893,033 783,826 0.53%
40 38 West Virginia 1,787,147 1,852,994 -3.3% −60,820 3 358,435 597,391 617,670 0.55%
41 41 Hawaii 1,415,872 1,360,301 4.1% +55,571 2 353,968 707,936 680,151 0.43%
42 43 New Hampshire 1,359,711 1,316,470 3.3% +43,241 2 339,928 679,856 658,233 0.41%
43 42 Maine 1,344,212 1,328,361 1.2% +15,851 2 336,053 672,106 664,181 0.40%
44 45 Montana 1,068,778 989,415 8.0% +79,363 1 356,259 1,068,778 989,417 0.32%
45 44 Rhode Island 1,059,361 1,052,567 0.6% +6,794 2 264,840 529,681 526,466 0.32%
46 46 Delaware 973,764 897,934 8.4% +75,830 1 324,588 973,764 897,934 0.29%
47 47 South Dakota 884,659 814,180 8.7% +70,479 1 294,886 884,659 814,180 0.27%
48 49 North Dakota 762,062 672,591 13.3% +89,471 1 254,021 762,062 672,591 0.23%
49 48 Alaska 731,545 710,231 3.0% +21,314 1 243,848 731,545 710,231 0.22%
50 51 District of Columbia 705,749 601,723 17.3% +104,026 1 (non-voting) 235,250 — — 0.21%
51 50 Vermont 623,989 625,741 -0.2% -1,752 1 207,996 623,989 625,741 0.19%
52 52 Wyoming 578,759 563,626 2.7% +15,133 1 192,920 578,759 563,626 0.17%
53 53 Guam 165,718 159,358[4] 4.0% +6,360 1 (non-voting) — — 0.05%
54 54 U.S. Virgin Islands 104,914 106,405[5] -1.4% −1,491 1 (non-voting) — — 0.03%
55 55 American Samoa 55,641 55,519[6] 0.22% +122 1 (non-voting) — — 0.02%
56 56 Northern Mariana Islands 55,194 53,883[7] 2.4% +1,311 1 (non-voting) — — 0.02%
'''
</code></pre>
<p>Then, I used re.compile() to make a match object. I only want the state/territory name, and the population estimate as of July 1, 2019 (the column directly to the right). </p>
<pre><code>text_lines = text.split('\n')
pattern = re.compile(r'([A-Z]\D*)'
'(\d*\,\d*\,\d*)')
data = []
for line in text_lines:
s = re.search(pattern, line)
if s:
data.append(s.group(1, 2))
for item in data:
print(item)
</code></pre>
<pre><code>('California\t', '39,512,223')
('Texas\t', '28,995,881')
('Florida\t', '21,477,737')
('New York\t', '19,453,561')
('Pennsylvania\t', '12,801,989')
('Illinois\t', '12,671,821')
('Ohio\t', '11,689,100')
('Georgia\t', '10,617,423')
('North Carolina\t', '10,488,084')
('Michigan\t', '9,986,857')
('New Jersey\t', '8,882,190')
('Virginia\t', '8,535,519')
('Washington\t', '7,614,893')
('Arizona\t', '7,278,717')
('Massachusetts\t', '6,949,503')
('Tennessee\t', '6,833,174')
('Indiana\t', '6,732,219')
('Missouri\t', '6,137,428')
('Maryland\t', '6,045,680')
('Wisconsin\t', '5,822,434')
('Colorado\t', '5,758,736')
('Minnesota\t', '5,639,632')
('South Carolina\t', '5,148,714')
('Alabama\t', '4,903,185')
('Louisiana\t', '4,648,794')
('Kentucky\t', '4,467,673')
('Oregon\t', '4,217,737')
('Oklahoma\t', '3,956,971')
('Connecticut\t', '3,565,287')
('Utah\t', '3,205,958')
('Iowa\t', '3,155,070')
('Puerto Rico\t', '3,193,694')
('Nevada\t', '3,080,156')
('Arkansas\t', '3,017,825')
('Mississippi\t', '2,976,149')
('Kansas\t', '2,913,314')
('New Mexico\t', '2,096,829')
('Nebraska\t', '1,934,408')
('Idaho\t', '1,792,065')
('West Virginia\t', '1,787,147')
('Hawaii\t', '1,415,872')
('New Hampshire\t', '1,359,711')
('Maine\t', '1,344,212')
('Montana\t', '1,068,778')
('Rhode Island\t', '1,059,361')
</code></pre>
<p>How would I need to change how I wrote the pattern so that the \t is not included?
Also, why does it stop at Rhode Island? I'm not sure what I did wrong. </p>
| 3 | 4,100 |
Sequelize - ForeignKey relationship - problem with alias
|
<p>I have two tables. One is skills, another is ratings. My problem is specific to ratings:
The model of ratings is:</p>
<pre><code>var sequelize = require('../sequelizeConfig');
var Sequelize = require('sequelize');
var Ratings=sequelize.define('ratings',{
ratingID:{
type:Sequelize.BIGINT,
field:'rating_id',
primaryKey:true
},
empID:{
type: Sequelize.STRING,
field:'emp_id'
},
skillID:{
type:Sequelize.STRING,
field:'skill_id',
references: {
model: 'skills',
key: 'skill_id'
}
},
rating:{
type: Sequelize.BIGINT ,
field:'rating'
}
},{
tableName:'ratings',
freezeTableName: true
})
module.exports=Ratings;
</code></pre>
<p>In controller, i have below relation. I am unsure if use of hasOne is right. With only 'belongsTo' to state foreignkey relationship, i only got ratings is not associated to skills. Basically skill_id in ratings table has reference to skill_id in skills table.</p>
<pre><code>var skillsets = require('../../models/skillsets');
var ratings = require('../../models/ratings');
skillsets.hasOne(ratings,{foreignKey:'skillID',sourceKey:'skillsetID'});
ratings.belongsTo(skillsets,{foreignKey:'skillID',targetKey:'skillsetID'});
</code></pre>
<p>I tried to query as below:</p>
<pre><code>skillsets.findAll({
where:{
roleID: role
},
include:[{
model:ratings,
where:{
emp_id: empID
},
attributes:['rating'],
required:false
}]
})
</code></pre>
<p>Everything seem fine but this hasOne does something fishy.
It generates query as:</p>
<pre><code>SELECT "skills"."skill_id" AS "skillsetID", "skills"."role_id" AS "roleID", "skills"."field", "skills"."skill_name" AS "skillName", "rating"."rating_id" AS "rating.ratingID", "rating"."rating" AS "rating.rating" FROM "skills" AS "skills" LEFT OUTER JOIN "ratings" AS "rating" ON "skills"."skill_id" = "rating"."skill_id" AND "rating"."emp_id" = '12344' WHERE "skills"."role_id" = 'developer';
</code></pre>
<p>Due to "rating"."rating" AS "rating.rating" , result comes as below:</p>
<pre><code>[
{
"skillsetID": "Angular",
"roleID": "developer",
"field": "Frontend",
"skillName": "Angular",
"rating":
{
"rating": "4"
}
}]
</code></pre>
<p>What i expect is just like:</p>
<pre><code> [
{
"skillsetID": "Angular",
"roleID": "developer",
"field": "Frontend",
"skillName": "Angular",
"rating":4
}]
</code></pre>
<p>Could you please favour?</p>
| 3 | 1,261 |
Android studio layout become blank when i enter text into multiline text
|
<p><a href="https://i.stack.imgur.com/C0lSj.jpg" rel="nofollow noreferrer">Image 1-Before entering text</a></p>
<p>In this edit text view i if i enter a single word it becomes like this</p>
<p><a href="https://i.stack.imgur.com/okMkb.jpg" rel="nofollow noreferrer">Image 2-after entering text</a></p>
<p>XMl </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/edittext"
android:layout_width="215dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:autofillHints=""
android:ems="10"
android:inputType="textMultiLine"
android:scrollbarSize="8dp"
android:scrollbars="horizontal|vertical"
app:layout_constraintBottom_toTopOf="@id/button2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/textView"
app:layout_constraintTop_toBottomOf="@id/textView"
tools:ignore="HardcodedText"
tools:targetApi="o" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
android:text="OK"
app:layout_constraintBaseline_toBaselineOf="@id/button2"
app:layout_constraintEnd_toStartOf="@id/button2" />
</android.support.constraint.ConstraintLayout>
</code></pre>
<p>I have added whole XMl file
I want to enter the text into my text field but i am not able to do it,i have tried my of the solutions before but still this issue is the same</p>
| 3 | 1,290 |
stopping threads that run indefinitely
|
<p>I have been trying to implement the producer consumer pattern. If both producer and consumer are running indefinitely how should one try to stop them?</p>
<p>I have been trying to test the status of <code>isInterrupted()</code> but the following code does not guarantee all threads to stop. </p>
<pre><code>public class Monitor {
private int value;
private boolean readable = false;
public synchronized void setVal(int value) {
while (readable) {
try {
this.wait();
} catch (InterruptedException e) {
break;
}
}
if (!Thread.currentThread().isInterrupted()) {
this.readable = true;
this.value = value;
this.notifyAll();
}
}
public synchronized int getVal() {
while (!readable) {
try {
this.wait();
} catch (InterruptedException e) {
break;
}
}
if (!Thread.currentThread().isInterrupted()) {
this.readable = false;
this.notifyAll();
}
return this.value;
}
}
</code></pre>
<p>The producer class looks like this:</p>
<pre><code>import java.util.Random;
public class Producer implements Runnable {
private Monitor monitor;
private Random r = new Random();
private String name;
public Producer(Monitor m) {monitor = m;}
public void run() {
name = Thread.currentThread().getName();
while (!Thread.currentThread().isInterrupted()) {
int value = r.nextInt(1000);
monitor.setVal(value);
System.out.println("PRODUCER: " + name + " set " + value);
}
System.out.println("PRODUCER: " + name + " interrupted");
}
}
</code></pre>
<p>The consumer</p>
<pre><code>public class Consumer implements Runnable {
private Monitor monitor;
private String name;
public Consumer(Monitor m) {monitor = m;}
public void run() {
name = Thread.currentThread().getName();
while (!Thread.currentThread().isInterrupted()) {
int value = monitor.getVal();
System.out.println("CONSUMER: " + name + " got " + value);
}
System.out.println("CONSUMER: " + name + " interrupted");
}
}
</code></pre>
<p>And the main:</p>
<pre><code>public class Main {
public static void main(String[] args) {
final int n = 2;
Monitor m = new Monitor();
Thread[] producers = new Thread[n];
Thread[] consumers = new Thread[n];
for (int i = 0; i < n; i++) {
producers[i] = new Thread(new Producer(m));
producers[i].start();
consumers[i] = new Thread(new Consumer(m));
consumers[i].start();
}
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {}
for (int i = 0; i < n; i++) {
producers[i].interrupt();
consumers[i].interrupt();
}
}
}
</code></pre>
<p>I get the following results </p>
<pre><code>PRODUCER: Thread-0 set 917
CONSUMER: Thread-1 got 917
PRODUCER: Thread-2 set 901
PRODUCER: Thread-0 set 29
CONSUMER: Thread-3 interrupted
CONSUMER: Thread-1 got 29
CONSUMER: Thread-1 interrupted
PRODUCER: Thread-2 set 825
...program hangs
</code></pre>
<p>and </p>
<pre><code>PRODUCER: Thread-0 set 663
CONSUMER: Thread-1 got 663
PRODUCER: Thread-0 set 129
CONSUMER: Thread-1 got 129
PRODUCER: Thread-2 set 93
PRODUCER: Thread-2 interrupterd
CONSUMER: Thread-3 interrupted
PRODUCER: Thread-0 set 189
PRODUCER: Thread-0 interrupterd
CONSUMER: Thread-1 got 129
...program hangs
</code></pre>
<p>etc... </p>
<p>There is clearly something wrong. Why am I not registering the calls the <code>interrupt</code> on a consistent basis? </p>
| 3 | 1,636 |
Django form won't display
|
<p>I'm working on a project and we need to add a form to add an event. It lists the name, date, time, and address. I got the form to work but when I added the base, the form doesn't show up on the web page with the base loaded. I'm thinking it has something to do with my html file. Here is my html file.</p>
<pre><code>{% extends "base.html" %}
{% block heading %}My Events{% endblock %}
{% block content3 %}
</h1><b><font size="5">Save Event</b></h1></font>
<form method="POST" action=".">{% csrf_token %}
{{form.as_p}}
<input type ="submit" value="Add Event"/>
</form>
{% endblock %}
</code></pre>
<p>views:</p>
<pre><code>def add_event(request):
user = request.user
events = user.event_set.all()
if request.method == "POST":
form = EventForm(request.POST)
if form.is_valid():
event = Event.objects.create(
eventname = form.cleaned_data['eventname'],
eventdate = form.cleaned_data['eventdate'],
eventtime = form.cleaned_data['eventtime'],
address = form.cleaned_data['address'],
user = request.user
)
return HttpResponseRedirect('/')
else:
form = EventForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('add_event.html',variables)
</code></pre>
<p>base:</p>
<pre><code>HTML (base.html)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>DelMarVa Happenings | {% block title %}{% endblock %}</title>
<link rel="stylesheet" href="/site_media/style.css" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="masthead">
<div id="logo">
<img src="/site_media/Delmarva.gif" width="100px" height="80px" />
</div>
<h1>DelMarVa Happenings</h1>
<br />
<h4>A listing of events in and around Delaware, Maryland, and Virginia</h4>
</div>
<div id="nav">
{% if user.is_authenticated %}
<h3>welcome, {{ user.username }}</h3>
{% else %}
<h3>welcome, guest</h3>
{% endif %}
<ul>
<li><a href="/">home<a/></li>
{% if user.is_authenticated %}
<li><a href="/event/">add event</a></li>
<li><a href="/user/">my events</a></li>
<li><a href="/account/">my account</a></li>
<li><a href="/logout/">logout</a></li>
{% else %}
<li><a href="/login/">login</a></li>
<li><a href="/register/">register</a></li>
{% endif %}
</ul>
</div>
<div id="ads">
<img src="/site_media/ad.jpg" />
</div>
<div id="main">
<h2>{% block head %}{% endblock %}</h2>
{% block content %}{% endblock %}
</div>
</div>
</body>
</html>
</code></pre>
| 3 | 1,918 |
how to increment to the next variable?
|
<p>I am writing a program that takes in a CSV file and makes a table out of the content from it. Then I apply a filter that will eliminate the bad entries in it, and I want to store those into a different ArrayList using the .add(originalTable()) </p>
<p>The problem I am having is I want to apply different filters and get different ArrayList each with the incremented number. So the OriginalTable is filter0 than filter1 than filter2. The problem I am running into is how do I increment the number of Filter over one ? </p>
<pre><code> State Population Death
1 10000 10
2 10001 10
3 10002 0
4 1200 100
5 1 900
6 1213 900
</code></pre>
<p>Okay so I have data like this in my Table which is just an arrayList of ArrayList, ArrayList one being the rows stored into the columns. Now let say I apply the filter that I want deaths less than or equal to 10 deaths and this should give me another "table" called filter which will give me: </p>
<pre><code> State Population Death
1 10000 10
2 10001 10
3 10002 0
</code></pre>
<p>This will be called filter1 now I apply another filter to this saying let me have only only with population bigger than 10,000 population and this is will result in another "table" called filter2.
Which would look something like this: </p>
<pre><code> State Population Death
2 10001 10
3 10002 0
</code></pre>
<p>I don't know how to increment it from filter0 to filter1 to filter2 and they have to be arrayList of ArrayList each time. Thank you guys so much! :) </p>
<pre><code> else if (task.contentEquals("filter")){
String filter = keyboard.nextLine();
String[] filterArray = filter.split(" ");
int colmn = 0;
String predicate ;
String Value = "W";
if(filter.contains("-v ")){
// do the seperate cutoff strings System.out.println("yeah it contains v");
}else{
colmn = Integer.parseInt(filterArray[1]);
predicate = filterArray[2];
//Value = filterArray[3];
System.out.println(colmn +" "+ predicate + " "+Value);
}
for(int i =0; i <table.size(); i++){
if(table.get(i).get(colmn).toString().contains(Value)){
filterTable.add(table.get(i));
System.out.println(table.get(i));
}
}
</code></pre>
| 3 | 1,077 |
Scrollview under the header
|
<p>Is there a way to do this in android studio? I want to achieve that when you scroll down the header will overlap above and under is the scrollview part. What I've got is it scrolls over the header. <a href="https://i.stack.imgur.com/LhwQ0.png" rel="nofollow noreferrer">In android studio</a></p>
<p>This is what Im trying to achieve that was made in figma</p>
<p><a href="https://i.stack.imgur.com/g4gGX.png" rel="nofollow noreferrer">Default</a></p>
<p><a href="https://i.stack.imgur.com/6JJ4L.png" rel="nofollow noreferrer">When you scroll</a></p>
<p>So far this is what my code looks like</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".Fragment.RecordFragment"
android:orientation="vertical">
<View
android:layout_width="369dp"
android:layout_height="71dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="13dp"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:background="@drawable/ic_header"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="25dp"
android:layout_marginTop="25dp"
android:layout_marginEnd="25dp"
android:layout_marginBottom="25dp"
android:text="Record"
android:textAlignment="center"
android:textColor="@color/white"
android:textSize="35sp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="100dp">
<TextView
android:id="@+id/txtDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="128dp"
android:text="Date for today"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="50sp" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<View
android:layout_width="316dp"
android:layout_height="201dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:background="@drawable/sec_bp" />
<EditText
android:layout_width="250dp"
android:layout_height="30dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="70dp"
android:background="@drawable/rounded_corner"
android:gravity="center"
android:hint="SBP" />
<EditText
android:layout_width="250dp"
android:layout_height="30dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="120dp"
android:background="@drawable/rounded_corner"
android:gravity="center"
android:hint="DBP" />
<EditText
android:layout_width="250dp"
android:layout_height="30dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="170dp"
android:background="@drawable/rounded_corner"
android:gravity="center"
android:hint="BPM" />
<Button
android:layout_width="70dp"
android:layout_height="30dp"
android:layout_marginLeft="120dp"
android:layout_marginTop="210dp"
android:background="@drawable/rounded_corner"
android:gravity="center"
android:text="save" />
</RelativeLayout>
<View
android:layout_width="316dp"
android:layout_height="117dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:background="@drawable/sec_temp" />
<View
android:layout_width="316dp"
android:layout_height="117dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:background="@drawable/sec_temp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
</code></pre>
| 3 | 3,326 |
Setup a Kibana dashboard for data about last Jenkins build
|
<p>I use Kibana to show data about automated test cases stored in a single elastic search index.</p>
<p>These tests can be repeated multiple times during the day and right now are identified by a build number that comes from Jenkins. So, if I want to see the latest results, I need to add a filter in my dashboards where I set the last known value of the build number.</p>
<p>Is there a way to automatically show in a dashboard the values about the last build?</p>
<p>Thank you.</p>
<p>EDIT: Here's a data sample:</p>
<pre><code>{
"_index": "data",
"_type": "_doc",
"_id": "33rugH0B0CwJH7IcV11v",
"_score": 1,
"_source": {
"market": "FRA",
"price_code": "DIS22FREH1003",
"test_case_id": "NPM_14",
"environment": "PROD",
"cruise_id": "DI20220707CPVCP1",
"jenkins_job_name": "MonitoringNPM_14",
"@timestamp": "2021-12-03T16:34:03.360+0100",
"jenkins_job_number": 8,
"agency": "FR900000",
"fail_code": "IncorrectGuarantee",
"build_number": 8,
"category": "IR2"
},
"fields": {
"environment.keyword": [
"PROD"
],
"test_case_id": [
"NPM_14"
],
"category.keyword": [
"IR2"
],
"price_code": [
"DIS22FREH1003"
],
"cruise_id": [
"DI20220707CPVCP1"
],
"price_code.keyword": [
"DIS22FREH1003"
],
"agency": [
"FR900000"
],
"jenkins_job_number": [
"8"
],
"agency.keyword": [
"FR900000"
],
"jenkins_job_number.keyword": [
"8"
],
"market": [
"FRA"
],
"jenkins_job_name.keyword": [
"MonitoringNPM_14"
],
"test_case_id.keyword": [
"NPM_14"
],
"environment": [
"PROD"
],
"@timestamp": [
"2021-12-03T15:34:03.360Z"
],
"jenkins_job_name": [
"MonitoringNPM_14"
],
"fail_code.keyword": [
"IncorrectGuarantee"
],
"fail_code": [
"IncorrectGuarantee"
],
"build_number": [
8
],
"market.keyword": [
"FRA"
],
"cruise_id.keyword": [
"DI20220707CPVCP1"
],
"category": [
"IR2"
]
}
}
</code></pre>
| 3 | 1,549 |
how to assign the output of a string separated by column to a variable in PowerShell
|
<p>I am trying to write a PowerShell script to get the required contents from a log/text file. The file looks like below:</p>
<pre><code>node1 : data1
node2 : data2
Administrators : Data is Not Available at this moment
desiredouput : data3
format : format-type
node1 : data4
node2 : data5
Administrators : user1, user2, user3, user4, user5, user6
desiredoutput : data6
format : format-type
node1 : data7
node2 : data8
Administrators : user1, user2, user3, user4, user5, user6, user7, user8, user9, user10, user11,
user12, user13, user14, user15, user16, user17, user18, user19, user20
desiredoutput : data9
format : format-type
.....
the sequence continues
.....
</code></pre>
<p>As you can see after every five lines, the new data will be displayed to the same variable on the left.</p>
<p>I want to fetch the data after <strong>:</strong> in each and every line and assign that to a variable. Here is the code I am writing:</p>
<pre><code> $deliverycontent = @()
$filecontent = Get-Content -Path <path to the text file>
$datacount = $filecontent.Length
for ($i=0; $i -lt $datacount; $i+=5)
{
$temp = "" |select Header1, Header2, Header3, Header4, Header5
$temp.Header1 = ($filecontent[$i]).Split(":")[1]
$temp.Header2 = ($filecontent[$i+1]).Split(":")[1]
$temp.Header3 = ($filecontent[$i+2]).Split(":")[1]
$temp.Header4 = ($filecontent[$i+3]).Split(":")[1]
$temp.Header5 = ($filecontent[$i+4]).Split(":")[1]
$deliverycontent += $temp
}
</code></pre>
<p>while running the above script, I am seeing the data is not properly assigned especially for the output of the <strong>administrators</strong> because the output of the administrators is a huge string and it is printing the output in the next line instead in a single line in the text file so the powershell output is not displaying as expected. How can I assign the entire string of the administrators to a single variable even it is printed in the next lines as per the loop condition provided.</p>
<p>The desired output is:</p>
<pre><code>Header1: data1
Header2: data2
Header3 : Data is Not Available at this moment
Header4: data3
Header5: format-type
Header1: data4
Header2: data5
Header3 : user1, user2, user3, user4, user5, user6
Header4: data6
Header5: format-type
Header1: data7
Header2: data8
Header3 : user1, user2, user3, user4, user5, user6, user7, user8, user9, user10, user11, user12,
user13, user14, user15, user16, user17, user18, user19, user20
Header4: data6
Header5: format-type
....
<the sequence follows>
....
How can I achieve this?
</code></pre>
| 3 | 1,032 |
Optaplanner unable to add nearbySelection to subChainSelector
|
<p>My question is essentially the same as <a href="https://stackoverflow.com/questions/54719539/nearby-selection-with-subchainchangemoveselector-or-subchainswapmoveselector">Nearby selection with subChainChangeMoveSelector or subChainSwapMoveSelector</a></p>
<p>I am unable to configure a <code><nearbySelection></code> for a <code>subChainSwapMoveSelector</code> or <code>subChainChangeMoveSelector</code>. </p>
<p>The docs outline the use of <code>nearbySelector</code> as for example:</p>
<pre><code>
<tailChainSwapMoveSelector>
<entitySelector id="entitySelector3"/>
<valueSelector>
<nearbySelection>
<originEntitySelector mimicSelectorRef="entitySelector3"/>
<nearbyDistanceMeterClass>...CustomerNearbyDistanceMeter</nearbyDistanceMeterClass>
<parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximum>
</nearbySelection>
</valueSelector>
</tailChainSwapMoveSelector>
</code></pre>
<p>However, setting an <code>entitySelector</code> on a <code>subChainChangeMove</code> or <code>subChainSwapMove</code>is not possible due to them lacking an <a href="https://github.com/kiegroup/optaplanner/blob/master/optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/value/chained/SubChainSelectorConfig.java#L37" rel="nofollow noreferrer">entitySelectorConfig</a>. They do support a <a href="https://github.com/kiegroup/optaplanner/blob/master/optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/value/ValueSelectorConfig.java" rel="nofollow noreferrer">valueSelectorConfig</a>, which in turn supports a <a href="https://github.com/kiegroup/optaplanner/blob/master/optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/common/nearby/NearbySelectionConfig.java" rel="nofollow noreferrer">nearbySelectionConfig</a>. However it is impossible to do something like this:</p>
<pre><code><subChainSwapMoveSelector>
<entityClass>...</entityClass>
<selectReversingMoveToo>true</selectReversingMoveToo>
<subChainSelector>
<minimumSubChainSize>2</minimumSubChainSize>
<maximumSubChainSize>10</maximumSubChainSize>
<valueSelector variableName="previousStandstill" mimicSelectorRef="subChainSwapMove">
<nearbySelection>
<originEntitySelector mimicSelectorRef="subChainSwapMove"/>
<nearbyDistanceMeterClass>....</nearbyDistanceMeterClass>
<parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximum>
</nearbySelection>
</valueSelector>
</subChainSelector>
</subChainSwapMoveSelector>
</code></pre>
<p>Because when ValueSeletorConfig tries to call <code>buildMimicReplaying()</code> it fails on </p>
<pre><code>if (id != null
|| variableName != null
|| cacheType != null
|| selectionOrder != null
|| nearbySelectionConfig != null
</code></pre>
<p>Is this a bug? Is there supposed to be an <code>entitySelectorConfig</code> for both these moves, or how do I get the <code>nearbySelection</code> to work with a <code>valueSelector</code> as the docs only outline the use of <code>entitySelector</code> ?</p>
<p>Thanks!</p>
| 3 | 1,352 |
Unable to connect error - Node Express app on Linux server
|
<p>I receive an 'Unable to Connect' error in my browser when trying to connect to my Node Express application. At (my servers ip address) 1.1.1.1:5000. The application works fine in my development environment but not on my AWS EC2 Linux server.</p>
<ul>
<li>The Node Express app works on my computer in dev</li>
<li>Port 5000 is allowing incoming TCP. I tested and confirmed this with a smaller application (<a href="https://hackernoon.com/deploying-a-node-app-on-amazon-ec2-d2fb9a6757eb" rel="nofollow noreferrer">https://hackernoon.com/deploying-a-node-app-on-amazon-ec2-d2fb9a6757eb</a>).</li>
<li>I confirmed my Node Express application is running . (I am using pm2)</li>
<li>PM2 keeps restarting my Node Express app at ~14s</li>
<li>I tried to curl from my machine to hit port 5000, I received a connection refused error <code>curl: (7) Failed to connect to 1.1.1.1 port 5000: Connection refused</code></li>
</ul>
<p><strong>UPDATE</strong></p>
<ul>
<li>Instead of starting the application with <code>pm2 start app.js</code> I started it with <code>npm start</code> and I the app is hosted at port 5000 successfully. </li>
<li>I can go to 1.1.1.1:5000 and am returned <code>API is running</code></li>
<li>I use js <code>fetch</code> api to call the backend at 127.0.0.1:5000 and receive a <code>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:5000/pickTicket/21780482. (Reason: CORS request did not succeed).
2
TypeError: NetworkError when attempting to fetch resource.</code> (*Note: My api is on the same server as my nginx/react app)`</li>
</ul>
<p>My application starts with app.js</p>
<pre><code>var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var compression = require('compression');
var fetch = require('node-fetch');
var pickTicketRouter = require('./routes/pickTicket');
var kdlRouter = require('./routes/kdl')
console.log('Creating API')
var app = express();
app.use(cors());
app.options('*', cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compression());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('API is running\n');
});
app.use('/pickTicket', pickTicketRouter);
app.use('/kdl', kdlRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
</code></pre>
<p>/bin/www</p>
<pre><code>#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('api:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '5000');
console.log('Listening on port: ', port);
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
</code></pre>
<p>package.json</p>
<pre><code>{
"name": "api",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon ./bin/www"
},
"dependencies": {
"compression": "^1.7.4",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "~4.16.1",
"forever": "^1.0.0",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"morgan": "~1.9.1",
"mssql": "^5.1.0",
"node-fetch": "^2.6.0",
"sequelize": "^5.11.0",
"tedious": "^6.2.0"
},
"devDependencies": {
"nodemon": "^1.19.1"
}
}
</code></pre>
<p>I expect to see get a response from the api but instead got a CORS error.</p>
| 3 | 2,029 |
How to fix this 2 issue by php (edit user from admin)?
|
<p>Currently: user can be changed through admin and a problem comes if I empty the pass form... a new hashed pass is saved in the database and the user can no longer login with the old pass... where as pass form was blank.</p>
<p>So I need to fix these two issues....</p>
<p>How do I do that ? </p>
<p>1) Username cant be change by admin through admin panel.
2) If Password form empty, hashed password will not change to database auto .</p>
<pre><code><?php
//if form has been submitted process it
if(isset($_POST['submit'])){
//collect form data
extract($_POST);
//very basic validation
if($username ==''){
$error[] = 'Please enter the username.';
}
if( strlen($password) > 0){
if($password ==''){
$error[] = 'Please enter the password.';
}
if($passwordConfirm ==''){
$error[] = 'Please confirm the password.';
}
if($password != $passwordConfirm){
$error[] = 'Passwords do not match.';
}
}
if($email ==''){
$error[] = 'Please enter the email address.';
}
if(!isset($error)){
try {
if(isset($password)){
$hashedpassword = $user->password_hash($password, PASSWORD_BCRYPT);
//update into database
$stmt = $db->prepare('UPDATE blog_members SET username = :username, password = :password, email = :email WHERE memberID = :memberID') ;
$stmt->execute(array(
':username' => $username,
':password' => $hashedpassword,
':email' => $email,
':memberID' => $memberID
));
} else {
//update database
$stmt = $db->prepare('UPDATE blog_members SET username = :username, email = :email WHERE memberID = :memberID') ;
$stmt->execute(array(
':username' => $username,
':email' => $email,
':memberID' => $memberID
));
}
//redirect to index page
header('Location: users.php?action=updated');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo $error.'<br />';
}
}
try {
$stmt = $db->prepare('SELECT memberID, username, email FROM blog_members WHERE memberID = :memberID') ;
$stmt->execute(array(':memberID' => $_GET['id']));
$row = $stmt->fetch();
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<form action='' method='post'>
<input type='hidden' name='memberID' value='<?php echo $row['memberID'];?>'>
<p><label>Username</label><br />
<input type='text' name='username' value='<?php echo $row['username'];?>'></p>
<p><label>Password (only to change)</label><br />
<input type='password' name='password' value=''></p>
<p><label>Confirm Password</label><br />
<input type='password' name='passwordConfirm' value=''></p>
<p><label>Email</label><br />
<input type='text' name='email' value='<?php echo $row['email'];?>'></p>
<p><input type='submit' name='submit' value='Update User'></p>
</form>
</code></pre>
| 3 | 1,743 |
Refreshing a div in Modal
|
<p>I am having a modal with two div user can add items by clicking on the button on the first div but as the user select that item i want to show the selected item in the second div. I am able to insert the selected item in database but i am unable to refresh the second div. So that user can see what item he has selected, Here is my jQuery code</p>
<pre><code>function PreCont(cont_id) { //THIS FUNCTION ADD ITEM IN DB{
var nit = $('#contractor').val();
$.ajax({
url: 'data/add_pre_cont.php',
type: 'post',
data: {
nit: nit,
cont_id: cont_id,
},
success: function() {
display_pre_cont(nit); // HERE I AM TRYING TO REFRESH THE DIV BY CALLING A FUNCTION
},
error: function() {},
});
}
</code></pre>
<p>This function is trying to display the data</p>
<pre><code>function display_pre_cont(nit) {
$.ajax({
url: 'data/pre_cont_modal.php',
type: 'post',
data: {
nit:nit,
},
success: function(data) {
$('#pre-contractor').html(data);
},
error: function (data){},
});
}
</code></pre>
<p>My code works fine if I refresh it i can see the new items</p>
<p>HTML Code</p>
<pre><code><div> // First Div
<div class="table-responsive">
<table id="myTable-item-order" class="table table-bordered table-hover table-striped">
<thead><tr>
<th width="5%"><center>Cate.</center></th>
<th width="5%"><center>Enlist</center></th>
<th width="41%"><center>Contractor Name</center></th>
<th width="19%"><center>District</center></th>
<th width="9%"><center></center></th>
</tr>
</thead>
<tbody>
<?php foreach($valid_contractor as $v): ?>
<tr align="center">
<td width="15%"><?= $v['category']; ?></td>
<td><?= $v['reionno']; ?></td>
<td align="left"><?= ucwords($v['contractorname']) ?></td>
<td align="left"><?= ucwords($v['district']) ?></td>
<td>
<button onclick="PreCont('<?= $v['id']; ?>');" type="button" class="btn btn-success btn-xs">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</code></pre>
<p>
2nd Div needs to be refreshed</p>
<pre><code><div class="col-md-6" id="pre-contractor">
<? require_once('modal/pre_cont_modal.php'); ?>
</div>
</code></pre>
| 3 | 1,372 |
How could I evenly split up buttons on a single line using HTML and CSS?
|
<p>In my HTML code I am trying to create a couple buttons inside a modal. I am using Bootstrap for this. Within the footer part, I am trying to split these buttons evenly among the width of the modal (or modal footer).</p>
<p>I could be using Bootstrap columns to achieve this but the padding (between the elements containing the <code>.col-*</code> class) might be a bit too big for this purpose. I could assign a width but this does not split the elements evenly among the amount of space available.</p>
<p>This is what I tried so far:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
$(".modal").modal();
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.foo {
/* Hardcoded width, how could I make it that when adding buttons, width is split among amount of buttons? */
float: left;
width: 30%;
margin: 0 5px;
}
.bar {
/* Not working to center the buttons: */
margin: 0 auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>&hellip;</p>
</div>
<div class="modal-footer">
<!-- Content with three evenly spread/divided buttons on a single line -->
<div class="bar">
<div class="foo">
<button type="button" class="btn btn-default btn-block">Button 1</button>
</div>
<div class="foo">
<button type="button" class="btn btn-default btn-block">Button 2</button>
</div>
<div class="foo">
<button type="button" class="btn btn-default btn-block">Button 3</button>
</div>
</div>
<!-- End of content -->
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/51xzr9jh/" rel="nofollow noreferrer">JSFiddle</a></p>
<p>Setting the width to a 30% obviously does not always make the buttons split evenly (e.g. if I add another button, the buttons are not evenly spread anymore). Also notice that the buttons are somewhat leaning to the left. I Would like the buttons to grow with the size of the modal (a.k.a. responsiveness). What is the best way to split/spread the buttons on a single line within the Modal's footer?</p>
| 3 | 1,382 |
Right sidebar moves when zooming in and out
|
<p>This is not a problem when I zoom out smaller than the original size, but when I zoom in, it covers my content. This also happens on screens of any other size than my own. My screen resolution is 1366x768. This is my website: <a href="http://justiceroulette.com/" rel="nofollow noreferrer">http://justiceroulette.com/</a> The "right sidebar" appears on all the pages except the home page.</p>
<p>I created this theme all on my own, and it's my first one, so I expected there to be errors to be worked out, but I am not sure how to go about adapting my theme to different screen sizes until I know the theme is even functioning properly on the "default" size. Why isn't the sidebar simply appearing bigger like the rest of the page instead of scooting to the left when I zoom in or view it on my phone?</p>
<p>Here are screenshots in case people reading this don't share my screen size: <a href="https://sta.sh/212zs5aq86oy?edit=1" rel="nofollow noreferrer">https://sta.sh/212zs5aq86oy?edit=1</a></p>
<p>I will provide any code requested. I have many php files to put this theme together, including multiple CSS files.</p>
<p>Thank you in advance to anyone that tries to help.</p>
<p><em>EDIT</em></p>
<p>I have compiled all the relevant code together, and have tested to see if the problem continues if I compile my header, sidebars, body, and footer in one file. It is the same.</p>
<p>Things I have done to try and fix this problem include:<br>
-Changing the #ads from an aside to a div<br>
-Trying different "position"s in CSS other than relative<br>
-Changing "float: right" to "clear: left" or "clear: both"<br>
-Adding "width: 100%;" under "html, body"</p>
<p>None of these seemed to change anything at all.</p>
<pre><code><div id='site-content'>
<div id="comic-wrapper">
<section id="comic">
Content goes here.
</section>
</div>
<aside id="ads">
<div align="center">
<a href="https://www.patreon.com/ispazzykitty"><img src="http://i.imgur.com/PQEvTVF.png" width="197px" height="240px"></a>
<a href="https://www.youtube.com/channel/UC8f1XRc2GAUJ9UXIsr72Pfg"><img src="http://i.imgur.com/YBOGFHb.png" width="197px" height="240px"></a>
<a href="https://ispazzykitty.deviantart.com/journal/New-Commission-Price-Guide-700723632"><img src="http://i.imgur.com/aN1UnKc.png" width="197px" height="361px"></a>
<p></p>
</div>
</aside>
</div> <!-- site content -->
<div id='site-footer'>
Justice Roulette is &copy; Starr Law, 2014-<?php echo date ('Y'); ?>.
<br>
</div>
</body>
</html>
</code></pre>
<p>Here is the CSS:</p>
<pre><code>html, body{
background-color: #002A0C;
background-image: url(http://i.imgur.com/bux1YSO.png);
padding: 0;
margin: 0;
border: 0;
width: 100%;
}
#comic-wrapper{
width: 1032px;
min-height: 779px;
position: absolute;
left: 97px;
}
#ads{
background-color: clear;
float: right;
width: 220px;
height: 1000px;
position: relative;
top: 10px;
}
#comic{
background-color: #078E2D;
background-image: url(http://i.imgur.com/cWA1Zj0.png);
height: 859px;
width: auto;
}
.comicpagespace{
margin-top: 10px;
width: 954px;
height: 536px;
}
img{
max-width: 100%;
max-height: 100%;
}
#site-footer {
clear: both;
text-align: center;
width: auto;
padding: 10px;
background-color: #150028;
color: #E2F7ED;
font-family: "Dosis", "Liberation Sans", sans-serif;
line-height: 20px;
}
</code></pre>
| 3 | 1,412 |
ValueError: Cannot feed value of shape (40, 244, 244) for Tensor 'Placeholder_4:0', which has shape '(40, 224, 224, 3)'
|
<p>I am new to TensorFlow and machine learning. I'm trying to extract features of images. I extracted the features of 1 image successfully but I can't extract images[]
Here's the script:</p>
<pre><code>#read image
def readfile(pathdir):
paths = glob.glob(pathdir + "*.png")
img_data_list=[]
imgs = [cv2.imread(file,cv2.IMREAD_COLOR) for file in paths]
for img in imgs:
img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_resize=cv2.resize(img,(244,244),3)
img_data_list.append(img_resize)
img_data = np.array(img_data_list)
np.expand_dims(img_data, axis=0)
#img_data = array(img_data).reshape(1, 244,244,3)
names = [os.path.basename(path) for path in paths]
with open(pathdir + "value.txt") as file:
nvl= file.readlines()
nvl = {line.split()[0]:float(re.sub(r'\n', "", line.split()[1])) for line
in nvl}
value =[]
for i in names:
value.append(nvl[i])
return img_data, np.array(value), names
# extract features
def feature(train_imgs):
with tf.Session(config=tf.ConfigProto(gpu_options=
(tf.GPUOptions(per_process_gpu_memory_fraction=0.7)))) as sess:
#with tf.device('/cpu:0'):
#with tf.Session() as sess:
images = tf.placeholder("float", [np.shape(train_imgs)[0], 224,
224, 3])
[bunch of code]
return features
</code></pre>
<p>I get the following error:</p>
<pre><code>ValueError Traceback (most recent call
last)
<ipython-input-23-b21a5d063db6> in feature(train_imgs)
47 vgg.build(images)
48 print("Extracting feature...")
---> 49 features = sess.run(vgg.fc6, feed_dict=feed_dict)
50 print('FC6 feature: ', features)
51 print('Number of input: ', len(features))
/usr/local/lib/python3.6/dist-
packages/tensorflow/python/client/session.py in run(self, fetches,
feed_dict, options, run_metadata)
927 try:
928 result = self._run(None, fetches, feed_dict, options_ptr,
--> 929 run_metadata_ptr)
930 if run_metadata:
931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
/usr/local/lib/python3.6/dist-
packages/tensorflow/python/client/session.py in _run(self, handle,
fetches, feed_dict, options, run_metadata)
1126 'which has shape %r' %
1127 (np_val.shape, subfeed_t.name,
-> 1128 str(subfeed_t.get_shape())))
1129 if not self.graph.is_feedable(subfeed_t):
1130 raise ValueError('Tensor %s may not be fed.' %
subfeed_t)
ValueError: Cannot feed value of shape (40, 244, 244) for Tensor
Placeholder_4:0', which has shape '(40, 224, 224, 3)'
</code></pre>
<p>What's Wrong and how to fix this problem.
Thank in advance!! </p>
| 3 | 1,270 |
Parse a very large text file with Python?
|
<p>So, the file has about 57,000 book titles, author names and a ETEXT No. I am trying to parse the file to only get the ETEXT NOs</p>
<p>The File is like this:</p>
<pre><code>TITLE and AUTHOR ETEXT NO.
Aspects of plant life; with special reference to the British flora, 56900
by Robert Lloyd Praeger
The Vicar of Morwenstow, by Sabine Baring-Gould 56899
[Subtitle: Being a Life of Robert Stephen Hawker, M.A.]
Raamatun tutkisteluja IV, mennessä Charles T. Russell 56898
[Subtitle: Harmagedonin taistelu]
[Language: Finnish]
Raamatun tutkisteluja III, mennessä Charles T. Russell 56897
[Subtitle: Tulkoon valtakuntasi]
[Language: Finnish]
Tom Thatcher's Fortune, by Horatio Alger, Jr. 56896
A Yankee Flier in the Far East, by Al Avery 56895
and George Rutherford Montgomery
[Illustrator: Paul Laune]
Nancy Brandon's Mystery, by Lillian Garis 56894
Nervous Ills, by Boris Sidis 56893
[Subtitle: Their Cause and Cure]
Pensées sans langage, par Francis Picabia 56892
[Language: French]
Helon's Pilgrimage to Jerusalem, Volume 2 of 2, by Frederick Strauss 56891
[Subtitle: A picture of Judaism, in the century
which preceded the advent of our Savior]
Fra Tommaso Campanella, Vol. 1, di Luigi Amabile 56890
[Subtitle: la sua congiura, i suoi processi e la sua pazzia]
[Language: Italian]
The Blue Star, by Fletcher Pratt 56889
Importanza e risultati degli incrociamenti in avicoltura, 56888
di Teodoro Pascal
[Language: Italian]
</code></pre>
<p>And this is what I tried:</p>
<pre><code>def search_by_etext():
fhand = open('GUTINDEX.ALL')
print("Search by ETEXT:")
for line in fhand:
if not line.startswith(" [") and not line.startswith("~"):
if not line.startswith(" ") and not line.startswith("TITLE"):
words = line.rstrip()
words = line.lstrip()
words = words[-7:]
print (words)
search_by_etext()
</code></pre>
<p>Well the code mostly works. However for some lines it gives me part of title or other things. Like:
This kind of output(), containing 'decott' which is a part of author name and shouldn't be here.
<img src="https://i.stack.imgur.com/Zi8Eh.png" alt="This kind of output"><a href="https://i.stack.imgur.com/Zi8Eh.png" rel="nofollow noreferrer">2</a></p>
<p>For this:
The Bashful Earthquake, by Oliver Herford 56765
[Subtitle: and Other Fables and Verses]</p>
<p>The House of Orchids and Other Poems, by George Sterling 56764</p>
<p>North Italian Folk, by Alice Vansittart Strettel Carr 56763
and Randolph Caldecott
[Subtitle: Sketches of Town and Country Life]</p>
<p>Wild Life in New Zealand. Part 1, Mammalia, by George M. Thomson 56762
[Subtitle: New Zealand Board of Science and Art, Manual No. 2]</p>
<p>Universal Brotherhood, Volume 13, No. 10, January 1899, by Various 56761</p>
<p>De drie steden: Lourdes, door Émile Zola 56760
[Language: Dutch]</p>
<p>Another example:</p>
<p><img src="https://i.stack.imgur.com/PQAKv.png" alt=""><a href="https://i.stack.imgur.com/PQAKv.png" rel="nofollow noreferrer">4</a></p>
<p>For
Rhandensche Jongens, door Jan Lens 56702
[Illustrator: Tjeerd Bottema]
[Language: Dutch]</p>
<p>The Story of The Woman's Party, by Inez Haynes Irwin 56701</p>
<p>Mormon Doctrine Plain and Simple, by Charles W. Penrose 56700
[Subtitle: Or Leaves from the Tree of Life]</p>
<p>The Stone Axe of Burkamukk, by Mary Grant Bruce 56699
[Illustrator: J. Macfarlane]</p>
<p>The Latter-Day Prophet, by George Q. Cannon 56698
[Subtitle: History of Joseph Smith Written for Young People]</p>
<p>Here: Life] shouldn't be there. Lines starting with blank space has been parsed out with this:</p>
<pre><code>if not line.startswith(" [") and not line.startswith("~"):
</code></pre>
<p>But Still I am getting those off values in my output results. </p>
| 3 | 1,960 |
WPF - Xceed GridControl - saving when edited row has focus
|
<p>I have an XCeed grid with cell editing enabled.
When i make a change to my cell, leave the row and then save it is persited to the database.</p>
<p>But when i hit my save button when the changed cell is still selected the change doens't get persisted. </p>
<p>How can i make sure when i save the current content is saved?</p>
<p>My Grid xaml:</p>
<pre><code><xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource MySource}}"
BorderThickness="1" AutoCreateColumns="False" ReadOnly="False" NavigationBehavior="CellOnly">
<xcdg:DataGridControl.DefaultCellEditors>
<xcdg:CellEditor x:Key="{x:Type system:Boolean}">
<xcdg:CellEditor.EditTemplate>
<DataTemplate>
<xcdg:CheckBox xcdg:Cell.IsCellFocusScope="True"
IsChecked="{xcdg:CellEditorBinding}"
HorizontalContentAlignment="Right"
/>
</DataTemplate>
</xcdg:CellEditor.EditTemplate>
<xcdg:CellEditor.ActivationGestures>
<xcdg:TextInputActivationGesture />
</xcdg:CellEditor.ActivationGestures>
</xcdg:CellEditor>
</xcdg:DataGridControl.DefaultCellEditors>
<xcdg:DataGridControl.Columns>
<xcdg:Column Title="Description" FieldName="Description" ReadOnly="True"/>
<xcdg:Column Title="Start period" FieldName="Start" ReadOnly="True"/>
<xcdg:Column Title="End Period" FieldName="End" ReadOnly="True"/>
<xcdg:Column Title="Finished" FieldName="IsFinished"/>
</xcdg:DataGridControl.Columns>
<!--<xcdg:DataGridControl.Columns>
</xcdg:DataGridControl.Columns>-->
</xcdg:DataGridControl>
</code></pre>
| 3 | 1,035 |
Need to turn javascript (ajax) vote script into reusable (dynamic) script so it can be used over and over
|
<p>Need to turn javascript (ajax) vote script into reusable (dynamic) script so it can be used over and over.</p>
<p>I have some ajax that works great, but I have to reproduce it and add unique identifiers [where you see 9 in the code are the unique identifiers that I have to change] for every question added that needs a vote. Need to make it dynamic so it will reproduce itself or can be reused with onclick identifiers no matter how many questions are in the database.</p>
<p>Tried to put the javascript in-between <CFOUTPUT QUERY="GetVotes"> </CFOUTPUT> tags so I could change the 9 to what ever the #GetVoteID# is for the vote question and dynamically reproduce the script as the questions are reproduce from the CFOUTPUT. But that didn’t work as the #GetVoteID# in the javascript caused the script not to work and I don’t know how to make the script reusable with onclick identifiers. </p>
<p>I see the thumbs up and down vote questions on lots of sites and the questions are dynamically reproduce though a database output, what are they doing to reuse there ajax?</p>
<p>I know onclick identifiers are the way to go, so any help on how I can convert my script, CFC’s, and whatever else so that it can handle 10, 20 or 1000 questions that need a vote.</p>
<p>Below is my code (The links, cfajaxproxy, CFC’s, and javascript)</p>
<p><strong>Yes / No links</strong><br>
<code><CFOUTPUT QUERY="GetVoteList"><br>
<A HREF="javascript:()" onclick="GetVoteYes9(#GetVoteID#);">Yes</A><br>
<A HREF="javascript:()" onclick="GetVoteNo9(#GetVoteID#);">No</A><br>
</CFOUTPUT></code></p>
<p><strong>Style for ajax</strong><br>
<code><STYLE><br>
GetVoteDescription9{visibility : visible}<br>
</STYLE></code> </p>
<p><strong>cfajaxproxy</strong><br>
<code><cfajaxproxy cfc="CFC/GetVoteYes9" jsclassname="YesVote9CFC"><br>
<cfajaxproxy cfc="CFC/GetVoteNo9" jsclassname="NoVote9CFC"></code> </p>
<p><strong>YesVoteCFC</strong> </p>
<pre><code><cfcomponent>
<cffunction name="NewCount9" access="remote">
<CFQUERY NAME="YesCount9CK" DATASOURCE="MyDSN">
SELECT *
FROM GetVote
WHERE GetVoteID = <cfqueryparam value="9" cfsqltype="CF_SQL_INTEGER">
</CFQUERY>
<CFSET NewCount9=#YesCount9CK.YesCount#+1>
<CFQUERY NAME="UpdateYesCount" DATASOURCE="MyDSN">
UPDATE GetVote
SET YesCount = <cfqueryparam value="#NewCount9#" cfsqltype="CF_SQL_INTEGER">
WHERE GetVoteID = <cfqueryparam value="9" cfsqltype="CF_SQL_INTEGER">
</CFQUERY>
<cfreturn NewCount9>
</cffunction>
</cfcomponent>
</code></pre>
<p><strong>NoVoteCFC</strong> </p>
<pre><code><cfcomponent>
<cffunction name="NewCount9" access="remote">
<CFQUERY NAME="NoCount9CK" DATASOURCE="MyDSN">
SELECT *
FROM GetVote
WHERE GetVoteID = <cfqueryparam value="9" cfsqltype="CF_SQL_INTEGER">
</CFQUERY>
<CFSET NewCount9=#NoCount9CK.NoCount#+1>
<CFQUERY NAME="UpdateNoCount" DATASOURCE="MyDSN">
UPDATE GetVote
SET NoCount = <cfqueryparam value="#NewCount9#" cfsqltype="CF_SQL_INTEGER">
WHERE GetVoteID = <cfqueryparam value="9" cfsqltype="CF_SQL_INTEGER">
</CFQUERY>
<cfreturn NewCount9>
</cffunction>
</cfcomponent>
</code></pre>
<p><strong>ajax script</strong> </p>
<pre><code><SCRIPT TYPE="text/javascript">
function GetVoteNo9()
{
var GetVoteNo9 = document.getElementById("GetVoteNo9");
var cfc = new NoCFC9();
cfc.setCallbackHandler(getDataResultNo9);
cfc.NewCount9(true);
var GetVoteDescription9 = document.getElementById("GetVoteDescription9").style.display='none';
var content = document.getElementById('YesResponse9').innerHTML='';
var content = document.getElementById('NoResponse9').innerHTML='You voted No';
}
function getDataResultNo9(NoResult9)
{
var content = document.getElementById('NoCount9').innerHTML=NoResult;
}
function GetVoteYes9()
{
var GetVoteYes9 = document.getElementById("GetVoteYes9");
var cfc = new YesCFC9();
cfc.setCallbackHandler(getDataResultYes9);
cfc.NewCount9(true);
var GetVoteDescription9 = document.getElementById("GetVoteDescription9").style.display='none';
var content = document.getElementById('YesResponse9').innerHTML='You voted Yes';
var content = document.getElementById('NoResponse9').innerHTML='';
}
function getDataResultYes9(YesResult9)
{
var content = document.getElementById('YesCount9').innerHTML=YesResult;
}
</SCRIPT>
</code></pre>
| 3 | 2,195 |
JavaScript checking the background color of a div
|
<p>I have a simple program where you can select a color and fill a box with it. I have a 4x4 grid of boxes(divs) and I want to check if the backgroundColor of all the divs(boxes) has a value, so that when all the boxes are filled with a color the grid resets and all the boxes are blank again. </p>
<p>However, I am having some problems implementing this. My first idea was to check that every div in the array (I've used querySelectorAll) has a backgroundColor 'red' or 'blue'. I've tried to store the backgroundColor of the array item into a variable but that doesn't return the string when I console log it.</p>
<p>I also tried the every() method on the Array but that didn't seem to work.</p>
<p>So my question would be, how do I get the backgroundColor of an element in a nodelist and check to see if that element has a backgroundColor. </p>
<p>Here is my JavaScript code:</p>
<pre><code>var redColor = document.getElementById('red');
var blueColor = document.getElementById('blue');
var box = document.querySelectorAll('.box');
var colorPick = document.getElementById('color picker');
let currentColor = [];
Array.from(box);
console.log(box);
loadEventListeners();
function loadEventListeners(){
redColor.addEventListener('click', pickRed);
blueColor.addEventListener('click', pickBlue);
for (i = 0; i < box.length; i++){
box[i].addEventListener('click', addColor);
}
};
function pickRed(e){
currentColor.push('red');
var textRed = document.createTextNode("You have selected red");
colorPick.appendChild(textRed);
console.log(currentColor);
}
function pickBlue(e){
currentColor.push('blue')
console.log(currentColor);
}
function addColor(e){
if (currentColor.slice(-1)[0] === 'blue'){
e.currentTarget.style.backgroundColor = 'blue';
} else { e.currentTarget.style.backgroundColor = 'red';
}
}
</code></pre>
<p>And here is the HTML I'm using: </p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<style>
.container{
grid-template-columns: repeat(5, 1fr);
grid-column-gap: 200px;
display: grid;
align-items: auto;
width: 50%;
margin: auto;
}
.game-grid{
display: grid;
grid-template-columns: repeat(4, 100px);
margin: 0;
}
#color-picker{
display: grid;
grid-template-rows: 100px 50px 50px;
}
.box{
width: 100px;
height: 100px;
border: solid 2px;
}
#red{
background-color: red;
width: 50px;
height: 50px;
}
#blue {
background-color: blue;
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div class="container">
<div class="game-grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div id="color picker">
<h2>Pick a color!</h2>
<div id="red"></div>
<div id="blue"></div>
<div id="green"></div>
</div>
</div>
</body>
</html>
</code></pre>
<p>Thank you for your help! </p>
| 3 | 1,513 |
Why the hashset's performance is way faster than list?
|
<p>This problem is from leetcode (<a href="https://leetcode.com/problems/word-ladder/" rel="nofollow noreferrer">https://leetcode.com/problems/word-ladder/</a>)!</p>
<p>Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:</p>
<p>Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:</p>
<p>Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.</p>
<p>This is my code which takes 800 ms to run:</p>
<pre><code>class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList){
if(!wordList.contains(endWord))
return 0;
int ret = 1;
LinkedList<String> queue = new LinkedList<>();
Set<String> visited = new HashSet<String>();
queue.offer(beginWord);
queue.offer(null);
while(queue.size() != 1 && !queue.isEmpty()) {
String temp = queue.poll();
if(temp == null){
ret++;
queue.offer(null);
continue;
}
if(temp.equals(endWord)) {
//System.out.println("succ ret = " + ret);
return ret;
}
for(String word:wordList) {
if(diffOf(temp,word) == 1){
//System.out.println("offered " + word);
//System.out.println("ret =" + ret);
if(!visited.contains(word)){
visited.add(word);
queue.offer(word);
}
}
}
}
return 0;
}
private int diffOf(String s1, String s2) {
if(s1.length() != s2.length())
return Integer.MAX_VALUE;
int dif = 0;
for(int i=0;i < s1.length();i++) {
if(s1.charAt(i) != s2.charAt(i))
dif++;
}
return dif;
}
}
</code></pre>
<p>Here is another code which takes 100ms to run:</p>
<pre><code>class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> set = new HashSet<>(wordList);
if (!set.contains(endWord)) {
return 0;
}
int distance = 1;
Set<String> current = new HashSet<>();
current.add(beginWord);
while (!current.contains(endWord)) {
Set<String> next = new HashSet<>();
for (String str : current) {
for (int i = 0; i < str.length(); i++) {
char[] chars = str.toCharArray();
for (char c = 'a'; c <= 'z'; c++) {
chars[i] = c;
String s = new String(chars);
if (s.equals(endWord)) {
return distance + 1;
}
if (set.contains(s)) {
next.add(s);
set.remove(s);
}
}
}
}
distance++;
if (next.size() == 0) {
return 0;
}
current = next;
}
return 0;
}
}
</code></pre>
<p>I think the second code is less efficient, because it test 26 letters for each word. Why is it so fast?</p>
| 3 | 1,682 |
Pass js var through query string
|
<p>I need to pass a js variable through out all pages where at the end of navigation, i need to summarize the total from all page and display the value.
Here is my JS code:</p>
<pre><code> <script>
$(document).ready(function() {
$('input[name=q1]').click(function() {
var selectedValue = $(this).val();
if($(this).val() == "A3")
var count=1;
else
var count=0;
});
});
</script>
</code></pre>
<p>HTML:</p>
<pre><code><form name="login" action=“page2.html" method="post">
<section class="heading">
<p><strong>Test1</strong></p>
</section>
<p class="pstyle">1st page</p>
<table>
<tr>
<td>
<input type="radio" name="q1" id="q1A1" required value="A1" />
Topic1
</td>
<td style="padding-left: 30px;">
<input type="radio" name="q1" id="q1A2" required value="A2"/>
Topic2
</td>
</tr><br>
<tr style="height: 77px;">
<td>
<input type="radio" name="q1" id="q1A3" required value="A3"/>
Topic3
</td>
<td style="padding-left: 30px;">
<input type="radio" name="q1" id="q1A4" required value="A4"/>
Topic4
</td><br>
<tr>
<td>
<input type="Submit" value=“Next “Page style="font-size: 40px;"/>
</td>
<td style="padding-left: 30px;">
<input type="Submit" value="Cancel" style="font-size: 40px;"/>
</td>
</tr>
</table>
</form>
</code></pre>
<p>Please let me know how I can pass the variable "Count" to my another page. I am able to implement this with local storage but I need to pass it using query string. Please advice. Thanks.</p>
| 3 | 1,134 |
Using FormFactory in Play 2.5.18 causes InvocationTargetException error
|
<p>I am upgrading the Form objects in Play 2.5.18 to use the FormFactory object as listed here:</p>
<p><a href="https://www.playframework.com/documentation/2.5.18/JavaForms" rel="nofollow noreferrer">https://www.playframework.com/documentation/2.5.18/JavaForms</a></p>
<p>I have my controller looking like this:</p>
<pre><code>public class Application extends Controller {
public final MailerClient mailerClient;
public final FormFactory formFactory;
public final MessagesApi messagesApi;
public final Collection<Lang> candidates;
public final Messages messages;
@Inject
public Application(MailerClient mailerClient, FormFactory formFactory, MessagesApi messagesApi) {
this.mailerClient = mailerClient;
this.formFactory = formFactory;
this.messagesApi = messagesApi;
this.candidates = Collections.singletonList(new Lang(Locale.US));
this.messages = messagesApi.preferred(candidates);
}
public Result authenticate() {
String errorMessage = "";
Form<Login> loginForm = formFactory.form(Login.class).bindFromRequest();
Logger.debug("authenticate");
...
}
...
}
</code></pre>
<p>When I run the application and attempt to login, I receive this error:</p>
<pre><code>! @77hah0j80 - Internal server error, for (POST) [/auth] ->
play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[RuntimeException: java.lang.reflect.InvocationTargetException]]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:255)
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:182)
at play.core.server.AkkaHttpServer$$anonfun$$nestedInanonfun$executeHandler$1$1.applyOrElse(AkkaHttpServer.scala:230)
at play.core.server.AkkaHttpServer$$anonfun$$nestedInanonfun$executeHandler$1$1.applyOrElse(AkkaHttpServer.scala:229)
at scala.concurrent.Future.$anonfun$recoverWith$1(Future.scala:414)
at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:37)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
at play.api.libs.streams.Execution$trampoline$.executeScheduled(Execution.scala:109)
at play.api.libs.streams.Execution$trampoline$.execute(Execution.scala:71)
at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68)
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at play.data.Form.callLegacyValidateMethod(Form.java:495)
at play.data.Form.bind(Form.java:530)
at play.data.Form.bindFromRequest(Form.java:257)
at controllers.Application.authenticate(Application.java:342)
at router.Routes$$anonfun$routes$1.$anonfun$applyOrElse$64(Routes.scala:2254)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:136)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:135)
at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$8$$anon$2$$anon$1.invocation(HandlerInvoker.scala:110)
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:78)
at play.http.DefaultActionCreator$1.call(DefaultActionCreator.java:31)
Caused by: java.lang.reflect.InvocationTargetException: null
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 play.data.Form.callLegacyValidateMethod(Form.java:486)
at play.data.Form.bind(Form.java:530)
at play.data.Form.bindFromRequest(Form.java:257)
at controllers.Application.authenticate(Application.java:342)
at router.Routes$$anonfun$routes$1.$anonfun$applyOrElse$64(Routes.scala:2254)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:136)
Caused by: java.lang.NullPointerException: null
at play.i18n.MessagesApi.preferred(MessagesApi.java:131)
at controllers.Application$Login.validate(Application.java:133)
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 play.data.Form.callLegacyValidateMethod(Form.java:486)
at play.data.Form.bind(Form.java:530)
at play.data.Form.bindFromRequest(Form.java:257)
at controllers.Application.authenticate(Application.java:342)
</code></pre>
<p>The error:</p>
<pre><code>at controllers.Application.authenticate(Application.java:342)
</code></pre>
<p>is this line of code:</p>
<pre><code>Form<Login> loginForm = formFactory.form(Login.class).bindFromRequest();
</code></pre>
<p>I have found a few posts, but they seem to point to what I am doing already:</p>
<p><a href="https://stackoverflow.com/questions/36099834/the-method-formclasst-from-form-class-is-deprecated-in-play-framework">The method form(Class<T>) from Form class is deprecated in Play! Framework</a></p>
<p><a href="https://stackoverflow.com/questions/40339240/formfactory-form-doesnt-exist-playframework">formFactory.form() doesn't exist ! PlayFramework</a></p>
<p>I think this is an easy fix and appreciate the help.</p>
<p>---------------------------- EDIT ------------------------------</p>
<p>Image of variables in Eclipse:
<a href="https://i.stack.imgur.com/qCzEv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qCzEv.png" alt="enter image description here"></a></p>
| 3 | 2,222 |
One form is working while other form is not working in laravel 5.4
|
<p>I've UserController in which I've two options - </p>
<p>1) For Updating Profile</p>
<p>2) For Updating Password</p>
<pre><code>namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\User;
use Auth;
use Hash;
class UserController extends Controller
{
public function profile(){
return view('profile', array('user' => Auth::user()));
}
public function update_avatar(Request $request){
if(isset($request->avatar) && $request->avatar->getClientOriginalName()){
$ext = $request->avatar->getClientOriginalExtension();
$file = date('YmdHis').rand(1,99999).'.'.$ext;
$request->avatar->storeAs('public/avatar',$file);
}
else
{
$user = Auth::user();
if(!$user->avatar)
$file = '';
else
$file = $user->avatar;
}
$user = Auth::user();
$user->avatar = $file;
$user->name = $request->name;
$user->email = $request->email;
$user->mb_number = $request->mb_number;
$user->home_town = $request->home_town;
$user->save();
return view('profile', array('user' => Auth::user()));
}
public function update_password(Request $request){
$user = Auth::user();
if(Hash::check(Input::get('old_password'), $user['password']) && Input::get('new_password') == Input::get('confirm_new_password')){
$user->password = bcrypt(Input::get('new_password'));
$user->save();
}
return view('profile', array('user' => Auth::user()));
}
}
</code></pre>
<p>In my view blade, I've two forms - </p>
<ol>
<li>update_avatar for updating profile like name, phone number and avatar.</li>
<li><p>update_password for updating password.</p>
<p>
</p>
<pre><code> </div>
<div class="widget-user-image">
<img class="img-circle" src="{{ asset('public/storage/avatar/'.$user->avatar) }}" alt="User Avatar">
</div>
<div class="box-footer">
<div class="row">
<div class="col-sm-4 border-right">
<div class="description-block">
<h5 class="description-header">{{ $user->email }}</h5>
<span class="description-text">Email</span>
</div>
<!-- /.description-block -->
</div>
<!-- /.col -->
<div class="col-sm-4 border-right">
<div class="description-block">
<h5 class="description-header">{{ $user->name }}</h5>
<span class="description-text">{{ $user->home_town }}</span>
</div>
<!-- /.description-block -->
</div>
<!-- /.col -->
<div class="col-sm-4">
<div class="description-block">
<h5 class="description-header">{{ $user->mb_number }}</h5>
<span class="description-text">Phone No.</span>
</div>
<!-- /.description-block -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!--
<div class="box-footer no-padding">
<ul class="nav nav-stacked">
<li><a href="#">Projects <span class="pull-right badge bg-blue">31</span></a></li>
<li><a href="#">Tasks <span class="pull-right badge bg-aqua">5</span></a></li>
<li><a href="#">Completed Projects <span class="pull-right badge bg-green">12</span></a></li>
<li><a href="#">Followers <span class="pull-right badge bg-red">842</span></a></li>
</ul>
</div>
-->
</div>
</div>
<section class="content">
<div class="container-fluid">
<form action="/profile" enctype="multipart/form-data" method="POST">
<div class="form-group">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Title" value="{{$user->name}}">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Description" value="{{$user->email}}" readonly>
</div>
<div class="form-group">
<label for="mb_number">Mobile No.</label>
<input type="text" name="mb_number" class="form-control" id="mb_number" placeholder="Schedule" value="{{$user->mb_number}}">
</div>
<div class="form-group">
<label for="home_town">Home Town</label>
<input type="text" name="home_town" class="form-control" id="home_town" placeholder="Deadline" value="{{$user->home_town}}">
</div>
<div class="form-group">
<label>Update Profile Image</label>
<input type="file" name="avatar">
@if($user->avatar)
<img src="{{ asset('public/storage/avatar/'.$user->avatar) }}" style="width:150px;">
@endif
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}"
<a href="" type="submit" class="btn btn-info"></a>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</section>
<section class="content">
<div class="container-fluid">
<form action="/profile" enctype="multipart/form-data" method="POST">
<div class="form-group">
<div class="form-group">
<label for="old_password">Old Password</label>
<input type="password" name="old_password" class="form-control" id="old_password" placeholder="Old Password">
</div>
<div class="form-group">
<label for="new_password">New Password</label>
<input type="password" name="new_password" class="form-control" id="new_password" placeholder="New Password">
</div>
<div class="form-group">
<label for="confirm_new_password">Confirm New Password </label>
<input type="password" name="confirm_new_password" class="form-control" id="confirm_new_password" placeholder="Confirm New Password">
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}"
<a href="" type="submit" class="btn btn-info"></a>
<button type="submit" class="btn btn-primary">Update Password</button>
</div>
</div>
</section>
</code></pre></li>
</ol>
<p>update_password function is working fine but update_avatar function is not working neither it's showing any error. I've tried dd($user) but still not giving output to dd.</p>
| 3 | 4,639 |
Sharded mongodb won't redistribute data
|
<p>I've setup a sharded mongo db environment on localhost, with 3 config servers and 2 sharded mongo instances and a single mongos.</p>
<p>Once the cluster has started up, I run the following sequence of commands:</p>
<pre><code>sh.addShard( "127.0.0.1:27010")
sh.addShard( "127.0.0.1:27011")
a = {"_id" : 1, "value" : 1}
b = {"_id" : 2, "value" : 2}
c = {"_id" : 3, "value" : 3}
d = {"_id" : 4, "value" : 4}
use foobar;
db.foo.insert(a);
db.foo.insert(b);
db.foo.insert(c);
db.foo.insert(d);
</code></pre>
<p>The I enable the db for sharding and create an index etc.</p>
<pre><code>sh.enableSharding("foobar");
db.foo.ensureIndex({"value":"hashed"});
sh.shardCollection("foobar.foo", { value: "hashed" } )
</code></pre>
<p>The result of all the above operations is successful.</p>
<p>But once I do:
db.foo.stats()</p>
<p>I see that all the data ends just in one shard without being distributed. And running</p>
<pre><code>db.printShardingStatus();
</code></pre>
<p>produces: </p>
<pre><code>--- Sharding Status ---
sharding version: {
"_id" : 1,
"version" : 3,
"minCompatibleVersion" : 3,
"currentVersion" : 4,
"clusterId" : ObjectId("52170e8a7633066f09e0c9d3")
}
shards:
{ "_id" : "shard0000", "host" : "127.0.0.1:27010" }
{ "_id" : "shard0001", "host" : "127.0.0.1:27011" }
databases:
{ "_id" : "admin", "partitioned" : false, "primary" : "config" }
{ "_id" : "foobar", "partitioned" : true, "primary" : "shard0000" }
foobar.foo
shard key: { "value" : "hashed" }
chunks:
shard0000 1
{ "value" : { "$minKey" : 1 } } -->> { "value" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
</code></pre>
<p>Interestingly, though, if I start off with a blank collection and have enable sharding on it before adding any data to it, the results are very different:</p>
<pre><code>db.foo.stats();
{
"sharded" : true,
"ns" : "foobar.foo",
"count" : 4,
"numExtents" : 2,
"size" : 144,
"storageSize" : 16384,
"totalIndexSize" : 32704,
"indexSizes" : {
"_id_" : 16352,
"value_hashed" : 16352
},
"avgObjSize" : 36,
"nindexes" : 2,
"nchunks" : 4,
"shards" : {
"shard0000" : {
"ns" : "foobar.foo",
"count" : 1,
"size" : 36,
"avgObjSize" : 36,
"storageSize" : 8192,
"numExtents" : 1,
"nindexes" : 2,
"lastExtentSize" : 8192,
"paddingFactor" : 1,
"systemFlags" : 1,
"userFlags" : 0,
"totalIndexSize" : 16352,
"indexSizes" : {
"_id_" : 8176,
"value_hashed" : 8176
},
"ok" : 1
},
"shard0001" : {
"ns" : "foobar.foo",
"count" : 3,
"size" : 108,
"avgObjSize" : 36,
"storageSize" : 8192,
"numExtents" : 1,
"nindexes" : 2,
"lastExtentSize" : 8192,
"paddingFactor" : 1,
"systemFlags" : 1,
"userFlags" : 0,
"totalIndexSize" : 16352,
"indexSizes" : {
"_id_" : 8176,
"value_hashed" : 8176
},
"ok" : 1
}
},
"ok" : 1
}
</code></pre>
<p>So the question is whether I'm missing something, if I shard an existing collection?</p>
| 3 | 1,529 |
Moving Spring Web Project using LDAP Authentication and Authorities to Spring and CAS
|
<p>I am trying to move a Spring Web Project using LDAP for Authentication and Authorities to Spring and CAS. My project was working great using LDAP but now I have to use CAS.. Once I changed the XML file everything stopped.</p>
<p>XML using LDAP:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
"
xmlns="http://www.springframework.org/schema/security">
<http auto-config="true" use-expressions="true">
<intercept-url access="hasRole('ROLE_MEMBER_INQUIRY')"
pattern="/requests/**" />
<form-login default-target-url="/requests/add.html" />
</http>
<authentication-manager>
<ldap-authentication-provider
user-search-base="ou=webusers" user-search-filter="(uid={0})">
<password-compare>
<password-encoder ref="passwordEncoder">
</password-encoder>
</password-compare>
</ldap-authentication-provider>
</authentication-manager>
<beans:bean id="passwordEncoder"
class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
</beans:bean>
<beans:bean id="contextSource"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<beans:constructor-arg
value="ldaps://dvldap01.uftwf.dev:636/dc=uftwf,dc=dev" />
<beans:property name="userDn" value="cn=Manager,dc=uftwf,dc=dev" />
<beans:property name="password" value="uftwf" />
</beans:bean>
<beans:bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.ldap.authentication.BindAuthenticator">
<beans:constructor-arg ref="contextSource" />
<beans:property name="userDnPatterns">
<beans:list>
<beans:value>
uid={0},ou=webusers
</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</beans:constructor-arg>
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
<beans:constructor-arg ref="contextSource" />
<beans:constructor-arg value="ou=groups" />
<beans:property name="groupRoleAttribute" value="ou" />
</beans:bean>
</beans:constructor-arg>
</beans:bean>
<ldap-server url="ldaps://dvldap01.uftwf.dev:636/dc=uftwf,dc=dev" />
<beans:bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<beans:property name="location" value="classpath:jdbc.properties2" />
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
> <beans:property name="driverClassName" value="${database.driver}" /> <beans:property
name="url" value="${database.url}" /> <beans:property name="username" value="${database.user}"
/> <beans:property name="password" value="${database.password}" /> <beans:property
name="initialSize" value="5" /> <beans:property name="maxActive" value="10"
/> </beans:bean>
<!--
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
> <beans:property name="driverClassName" value="${database.driver}" /> <beans:property
name="url" value="${database.url}" /> <beans:property name="username" value="${database.user}"
/> <beans:property name="password" value="${database.password}" /> <beans:property
name="initialSize" value="5" /> <beans:property name="maxActive" value="10"
/> </beans:bean>
<jee:jndi-lookup id="dataSourcejndi" jndi-name="dataSourcejndi"
lookup-on-startup="false" proxy-interface="javax.sql.DataSource"
cache="true" resource-ref="true" />
<beans:bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"
lazy-init="true">
<beans:property name="dataSource" ref="dataSourcejndi" />
</beans:bean>
<beans:bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:dataSourcejndi" />
</beans:bean>
<beans:bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/mi"/>
</beans:bean>
<mvc:annotation-driven />
-->
<!-- <beans:bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:dataSourcejndi" />
</beans:bean>
-->
</beans:beans>
</code></pre>
<p>XML using CAS:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url access="hasRole('ROLE_MEMBER_INQUIRY')"
pattern="/requests/**" />
<form-login default-target-url="/requests/add.html" />
</http>
<bean id="securityFilter" class="org.springframework.security.util.FilterChainProxy">
<sec:filter-chain-map path-type="ant">
<sec:filter-chain pattern="/images/**" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/css/**" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/js/**" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/403.jsp" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/404.jsp" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/error.jsp" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/**/cas/changePassword.htm*" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/**/cas/login.htm*" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/**/cas/passwordExpired.htm*" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/**/*.html*" filters="channelProcessingFilter"/>
<sec:filter-chain pattern="/**"
filters="channelProcessingFilter,httpSessionContextIntegrationFilter,logoutFilter,casSingleSignOutFilter,casProcessingFilter,securityContextHolderAwareRequestFilter,exceptionTranslationFilter,filterInvocationInterceptor"/>
</sec:filter-chain-map>
</bean>
<!-- this is what hooks up the CAS entry point -->
<bean id="exceptionTranslationFilter" class="org.springframework.security.ui.ExceptionTranslationFilter">
<property name="authenticationEntryPoint">
<ref local="casProcessingFilterEntryPoint"/>
</property>
</bean>
<!-- where do I go when I need authentication from CAS-->
<bean id="casProcessingFilterEntryPoint" class="org.springframework.security.ui.cas.CasProcessingFilterEntryPoint">
<property name="loginUrl" value="https://dvjvm11.uftwf.dev:8443/cas-server-webapp/login"/>
<property name="serviceProperties" ref="serviceProperties"/>
</bean>
<!-- defines which roles are allowed to access http resources -->
<bean id="filterInvocationInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="accessDecisionManager"/>
<property name="objectDefinitionSource">
<value>
PATTERN_TYPE_APACHE_ANT
**=ROLE_ALLOWED_ROLES_HERE
</value>
</property>
</bean>
<!-- hooks up CAS ticket validator and user details loader -->
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<list>
<ref bean="casAuthenticationProvider"/>
</list>
</property>
</bean>
<!-- supporting class for filterInvocationInterceptor -->
<bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false"/>
<property name="decisionVoters">
<list>
<ref local="roleVoter"/>
</list>
</property>
</bean>
<bean id="roleVoter" class="org.springframework.security.vote.RoleVoter">
<property name="rolePrefix" value=""/>
</bean>
<!-- setup method level security using annotations -->
<sec:global-method-security jsr250-annotations="enabled" secured-annotations="enabled"/>
<alias name="authenticationManager" alias="_authenticationManager"/>
<bean id="passwordEncoder" class="org.springframework.security.providers.encoding.ShaPasswordEncoder"/>
<!-- which service (application) am I authenticating -->
<bean id="serviceProperties" class="org.springframework.security.ui.cas.ServiceProperties">
<property name="service" value="https://dvjvm11.uftwf.dev:8443/cas-server-webapp/j_spring_cas_security_check"/>
<property name="sendRenew" value="false"/>
</bean>
<!-- handles a logout request from the CAS server -->
<bean id="casSingleSignOutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/>
<!-- performs CAS authentication -->
<bean id="casProcessingFilter" class="org.springframework.security.ui.cas.CasProcessingFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationFailureUrl" value="/403.jsp"/>
<property name="alwaysUseDefaultTargetUrl" value="false"/>
<property name="defaultTargetUrl" value="/"/>
</bean>
<!-- Does the CAS ticket validation and user details loading -->
<bean id="casAuthenticationProvider" class="org.springframework.security.providers.cas.CasAuthenticationProvider">
<property name="userDetailsService" ref="pickYourUserDetailsServiceImplementation"/>
<property name="serviceProperties" ref="serviceProperties"/>
<property name="ticketValidator">
<bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
<constructor-arg index="0" value="https://dvjvm11.uftwf.dev:8443/cas-server-webapp/"/>
</bean>
</property>
<property name="key" value="my_password_for_this_auth_provider_only"/>
</bean>
<!-- Log failed authentication attempts to commons-logging -->
<bean id="loggerListener" class="org.springframework.security.event.authentication.LoggerListener"/>
<bean id="httpSessionContextIntegrationFilter"
class="org.springframework.security.context.HttpSessionContextIntegrationFilter"/>
<bean id="securityContextHolderAwareRequestFilter"
class="org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter"/>
<!-- ===================== SSL SWITCHING ==================== -->
<bean id="channelProcessingFilter" class="org.springframework.security.securechannel.ChannelProcessingFilter">
<property name="channelDecisionManager" ref="channelDecisionManager"/>
<property name="filterInvocationDefinitionSource">
<value>
PATTERN_TYPE_APACHE_ANT
**=REQUIRES_SECURE_CHANNEL
</value>
</property>
</bean>
<bean id="channelDecisionManager" class="org.springframework.security.securechannel.ChannelDecisionManagerImpl">
<property name="channelProcessors">
<list>
<bean class="org.springframework.security.securechannel.SecureChannelProcessor">
<property name="entryPoint" ref="channelEntryPoint"/>
</bean>
<bean class="org.springframework.security.securechannel.InsecureChannelProcessor">
<property name="entryPoint" ref="channelEntryPoint"/>
</bean>
</list>
</property>
</bean>
<bean id="channelEntryPoint" class="org.springframework.security.securechannel.RetryWithHttpsEntryPoint">
<property name="portMapper" ref="portMapper"/>
</bean>
<bean id="portMapper" class="org.springframework.security.util.PortMapperImpl">
<property name="portMappings">
<map>
<entry key="80" value="443"/>
<entry key="8080" value="8443"/>
<entry key="5580" value="5543"/>
</map>
</property>
</bean>
<!-- Invoked when the user clicks logout -->
<bean id="logoutFilter" class="org.springframework.security.ui.logout.LogoutFilter">
<!-- URL redirected to after logout success -->
<constructor-arg value="https://dvjvm11.uftwf.dev:8443/cas-server-webapp/logout"/>
<constructor-arg>
<list>
<bean class="org.springframework.security.ui.logout.SecurityContextLogoutHandler">
<property name="invalidateHttpSession" value="false"/>
</bean>
</list>
</constructor-arg>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${database.driver}" /> <property
name="url" value="${database.url}" /> <property name="username" value="${database.user}"
/> <property name="password" value="${database.password}" /> <property
name="initialSize" value="5" /> <property name="maxActive" value="10"
/> </bean>
</beans>
</code></pre>
<p>can someone please tell me why everything stopped working</p>
| 3 | 7,252 |
PHP - moving forwards and backwards through mysql rows
|
<p>I have a page that displays a row depending on the id given in the browser bar (page.php?id=1). I am trying to use forward and back buttons to display the corresponding next or previous row on the page. So essentially the prev and next buttons will just be links to page.php, with the id being the next in the list. It isn't a sequential list, so I can't just do id+1 etc. </p>
<p>Anyway, I have it working fine, but basically I want the forward and back links to only display as text if there isn't a page to go to. I've been trying to run code to display only text if the $backformat is empty, but it seems to hold "Resource id#(and a random number)". So I've tried some other ways to match "Resource" in the string but that hasn't worked</p>
<p>Any ideas?</p>
<pre><code> <?php
$backresult = mysql_query("SELECT id FROM studies WHERE niche = '$niche' AND date < '$currentdate' ORDER BY date DESC LIMIT 1", $connection);
if (!$backresult) {
die("Database query failed: " . mysql_error());
}
$forwardresult = mysql_query("SELECT id FROM studies WHERE niche = '$niche' AND date > '$currentdate' ORDER BY date ASC LIMIT 1", $connection);
if (!$forwardresult) {
die("Database query failed: " . mysql_error());
}
?>
</code></pre>
<p>
<pre><code>while ($row = mysql_fetch_array($forwardresult)) {
$forward = $row["id"];
$forwardformat = preg_replace('/\s+/','',$forward);
echo $forwardformat;
$pos = strpos($forwardformat,'source');
if($pos == false) {
// string needle NOT found in haystack
echo 'Exploring moves us <a href="casestudy.php?id=';
echo $forwardformat;
echo '">forward</a>';
}
else {
// string needle found in haystack
echo "forward";
}
//other code I've tried before
/* if (!empty($forwardformat)) {
echo 'Exploring moves us <a href="casestudy.php?id=';
echo $forwardformat;
echo '">forward</a>';
}
else {
echo "forward";
}*/
}
echo $backresult;
while ($row = mysql_fetch_array($backresult)) {
$back = $row["id"];
$backformat = preg_replace('/\s+/','',$back);
echo $backformat;
//$pos = strpos($backformat,'source');
//$match = preg_match("R",$backformat);
if (substr($backformat,0,1) == 'R') {
// string needle NOT found in haystack
echo ', studying we look <a href="casestudy.php?id=';
echo $backformat;
echo '">back</a>';
}
else {
// string needle found in haystack
echo "back";
}
//other code I've tried before
/*if (!empty($backformat)) {
echo ', studying we look <a href="casestudy.php?id=';
echo $backformat;
echo '">back</a>';
}
if ($backformat==false) {
echo "back";
} */
}
</code></pre>
| 3 | 1,855 |
How to submit image along with fields to node js
|
<p>I am trying to send form with multiple images so that i can save to mysql data base
my form is like</p>
<pre><code>import React from 'react';
import axios from 'axios'
export const Imageupload = ()=>
{
const[File,setImageFiles] = React.useState(null)
const[firstName,setFirstName] = React.useState(null)
const[lastName,setLastName] = React.useState(null)
const upload = ()=>
{
if (File) {
console.log(File)
var formData = new FormData();
formData.append('firstname', firstName);
formData.append('lastname', lastName);
formData.append('fileslist', File);
var options = {
firstname:firstName,
lastname:lastName,
fileslist:File,
}
try {
const res = axios.post('/students/imgUpload', formData);
}
catch (err) {
if (err) {
console.log(err);
}
}
} else {
console.log("Please enter all fields");
}
}
return(
<>
<form encType="multipart/form-data">
<input name="firstName" onChange={(e)=>setFirstName(e.target.value)} placeholder="enter first name"/>
<input name="lastName" onChange={(e)=>setLastName(e.target.value)} placeholder="enter last name"/>
<input type="file" name="ourimage" onChange={(e)=>setImageFiles(e.target.files[0])}/>
<button onClick={upload} type="button">submit</button>
</form>
</>
)
}
</code></pre>
<p>but when I log the req on node js i got this response in which files are in req.body but it should be in req.files
however, req.files is empty</p>
<p><a href="https://i.stack.imgur.com/RNjQX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RNjQX.png" alt="req logged on node js controller" /></a></p>
<p>I am using multer and body-parser in following way</p>
<pre><code>const bodyParser = require('body-parser')
var multer = require('multer');
var upload = multer();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(upload.array('fileslist', 1));
app.use(express.static('public'));
app.use('/students',students)
</code></pre>
<p>My router and controller looks like</p>
<pre><code>router.post("/create-product",products.store)
</code></pre>
<p>//controller</p>
<pre><code>exports.uploadForm = (req,res)=>
{
var file = req
console.log( file)
}
</code></pre>
<p>Note: I have tried inserting them separately such that inserting fields into mysql separately and image separately using formidable but i am failing to insert it completely as in one go</p>
| 3 | 1,288 |
Remove existing product and install it again.guide me with example code
|
<p>I want to add feature if setup run second time it will remove existing product first. without version feature. kindly guide me how i make sure if product already exist. setup will remove it first and install it again and after installation launch application.
OR
if product with same version already exist setup launch the Application.
its good if having sample code please share that too. Thanks advance.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<?define EmbeddApp_TargetDir=$(var.EmbeddApp.TargetDir)?>
<Product Id="*" Name="Troytec_TestEngine" Language="1033" Version="1.0.0.0" Manufacturer="TroyTec" UpgradeCode="c28ad43a-4fe4-4d14-ba4f-6422c00b13c2">
<Package Id="*" InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
<!--<MajorUpgrade AllowDowngrades="yes" />-->
<MediaTemplate />
<Property Id="PREVIOUSVERSIONSINSTALLED" Secure="yes" />
<Upgrade Id="a61287ef-e184-421b-ac76-d8b91e489a6d">
<UpgradeVersion
Minimum="1.0.0.0" Maximum="99.0.0.0"
Property="PREVIOUSVERSIONSINSTALLED"
IncludeMinimum="yes" IncludeMaximum="no" />
</Upgrade>
<Feature Id="ProductFeature" Title="Troytec_TestEngine" Level="1">
<ComponentGroupRef Id="ProductComponents" />
<ComponentRef Id="ApplicationShortcut" />
<ComponentRef Id="ApplicationShortcutDesktop" />
<ComponentRef Id="CMP_MyEmptyDir" />
<ComponentRef Id="CMP_MyEmptyDir2" />
<ComponentRef Id="CMP_MyEmptyDir3" />
</Feature>
<!--Step 2: Add UI to your installer / Step 4: Trigger the custom action-->
<!--<UI>
<UIRef Id="WixUI_Minimal" />
<Publish Dialog="ExitDialog"
Control="Finish"
Event="DoAction"
Value="LaunchApplication">WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 and NOT Installed</Publish>
</UI>-->
<Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT" Value="Launch My Application Name" />
<!--Step 3: Include the custom action-->
<!--<Property Id="WixShellExecTarget" Value="[EmbeddApp.exe]" />-->
<CustomAction Id="LaunchApplication"
BinaryKey="WixCA"
DllEntry="WixShellExec"
Impersonate="yes" />
</Product>
<!--<Fragment>
<InstallExecuteSequence>
<Custom Action='902bc339-5cef-4f74-9d04-07941afa8ba1' Before='6d48fcc2-99cb-4ab6-867a-79f0484db05c'>
(NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")
</Custom>
</InstallExecuteSequence>
</Fragment>-->
<Fragment>
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ProgramFilesFolder">
<Directory Id="INSTALLFOLDER" Name="Troytec_TestEngine" >
<Directory Id="FOLDER1" Name="GPUCache">
</Directory>
<Directory Id="FOLDER2" Name="locales">
</Directory>
<Directory Id="FOLDER3" Name="swiftshader">
</Directory>
</Directory>
</Directory>
<Directory Id="ProgramMenuFolder">
<Directory Id="ApplicationProgramsFolder" Name="Troytec_TestEngine" />
</Directory>
<Directory Id="DesktopFolder" Name="Desktop"/>
</Directory>
</Fragment>
<Fragment>
<Icon Id="City.ico" SourceFile="letter-t-24.ico" />
<DirectoryRef Id="ApplicationProgramsFolder">
<Component Id="ApplicationShortcut" Guid="9bd13330-6540-406f-a3a8-d7f7c69ae7f9">
<Shortcut Id="ApplicationStartMenuShortcut" Name="Troytec_TestEngine" Description="MyWpfApplication" Target="[INSTALLFOLDER]EmbeddApp.exe" WorkingDirectory="INSTALLFOLDER" Icon ="City.ico" />
<RemoveFolder Id="RemoveApplicationProgramsFolder" Directory="ApplicationProgramsFolder" On="uninstall" />
<RegistryValue Root="HKCU" Key="Software\MyWpfApplication" Name="installed" Type="integer" Value="1" KeyPath="yes" />
</Component>
</DirectoryRef>
<DirectoryRef Id="DesktopFolder">
<Component Id="ApplicationShortcutDesktop" Guid="cde1e030-eb64-49a5-b7b8-400b379c2d1a">
<Shortcut Id="ApplicationDesktopShortcut" Name="Troytec_TestEngine" Description="MyWpfApplication" Target="[INSTALLFOLDER]EmbeddApp.exe" WorkingDirectory="INSTALLFOLDER" Icon ="City.ico" />
<RemoveFolder Id="RemoveDesktopFolder" Directory="DesktopFolder" On="uninstall" />
<RegistryValue Root="HKCU" Key="Software\Troytec_TestEngine" Name="installed" Type="integer" Value="1" KeyPath="yes" />
</Component>
</DirectoryRef>
</Fragment>
<Fragment>
</Fragment>
<Fragment>
<ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
<!-- TODO: Remove the comments around this Component element and the ComponentRef below in order to add resources to this installer. -->
<!-- <Component Id="ProductComponent"> -->
<!-- TODO: Insert files, registry keys, and other resources here. -->
<!-- </Component> -->
<Component Id="EmbeddApp.exe" Guid="85c6f764-7517-4bc6-8e5a-ec52ae6ece1e">
<File Id="EmbeddApp.exe" Name="EmbeddApp.exe" Source="$(var.EmbeddApp_TargetDir)EmbeddApp.exe" />
</Component>
<Component Id="EmbeddApp.exe.config" Guid="8ee125d7-7043-498a-ad65-24055252218a">
<File Id="EmbeddApp.exe.config" Name="EmbeddApp.exe.config" Source="$(var.EmbeddApp_TargetDir)EmbeddApp.exe.config" />
</Component>
<Component Id="CefSharp.WinForms.dll" Guid="9fdb1c25-2275-4a14-8f4f-6832b7a617dc">
<File Id="CefSharp.WinForms.dll" Name="CefSharp.WinForms.dll" Source="$(var.EmbeddApp_TargetDir)CefSharp.WinForms.dll" />
</Component>
<Component Id="CefSharp.dll" Guid="9bdbc9cc-52a6-4213-b941-0248e995aa71">
<File Id="CefSharp.dll" Name="CefSharp.dll" Source="$(var.EmbeddApp_TargetDir)CefSharp.dll" />
</Component>
<Component Id="CefSharp.Core.dll" Guid="0e058c32-f73b-4b3f-acbd-b0c29c019297">
<File Id="CefSharp.Core.dll" Name="CefSharp.Core.dll" Source="$(var.EmbeddApp_TargetDir)CefSharp.Core.dll" />
</Component>
<!--other files-->
<Component Id="cef.pak" Guid="283c053a-c66e-4889-9c6b-2884b50b8cbb">
<File Id="cef.pak" Name="cef.pak" Source="$(var.EmbeddApp_TargetDir)cef.pak" />
</Component>
<Component Id="cef_100_percent.pak" Guid="12342b21-68e4-4874-ac3f-87ac8a9f40c2">
<File Id="cef_100_percent.pak" Name="cef_100_percent.pak" Source="$(var.EmbeddApp_TargetDir)cef_100_percent.pak" />
</Component>
<Component Id="cef_200_percent.pak" Guid="b261180b-0fa2-41ea-ba8d-63d329f2d047">
<File Id="cef_200_percent.pak" Name="cef_200_percent.pak" Source="$(var.EmbeddApp_TargetDir)cef_200_percent.pak" />
</Component>
<Component Id="cef_extensions.pak" Guid="a4a0a9d0-0308-46be-b24a-7de985018039">
<File Id="cef_extensions.pak" Name="cef_extensions.pak" Source="$(var.EmbeddApp_TargetDir)cef_extensions.pak" />
</Component>
<Component Id="CefSharp.BrowserSubprocess.Core.dll" Guid="f3e2f9bc-066a-43f0-9e14-445d7af00243">
<File Id="CefSharp.BrowserSubprocess.Core.dll" Name="CefSharp.BrowserSubprocess.Core.dll" Source="$(var.EmbeddApp_TargetDir)CefSharp.BrowserSubprocess.Core.dll" />
</Component>
<Component Id="CefSharp.BrowserSubprocess.Core.pdb" Guid="6127f13d-4b77-4a7f-992d-5b49abb2dfee">
<File Id="CefSharp.BrowserSubprocess.Core.pdb" Name="CefSharp.BrowserSubprocess.Core.pdb" Source="$(var.EmbeddApp_TargetDir)CefSharp.BrowserSubprocess.Core.pdb" />
</Component>
<Component Id="CefSharp.BrowserSubprocess.exe" Guid="4b029801-a97e-47a0-8f37-0a0540bed89e">
<File Id="CefSharp.BrowserSubprocess.exe" Name="CefSharp.BrowserSubprocess.exe" Source="$(var.EmbeddApp_TargetDir)CefSharp.BrowserSubprocess.exe" />
</Component>
<Component Id="CefSharp.BrowserSubprocess.pdb" Guid="d47f6d16-c6f5-4cf3-98a8-a342444e225f">
<File Id="CefSharp.BrowserSubprocess.pdb" Name="CefSharp.BrowserSubprocess.pdb" Source="$(var.EmbeddApp_TargetDir)CefSharp.BrowserSubprocess.pdb" />
</Component>
<Component Id="CefSharp.Core.pdb" Guid="f9ae3c06-3c49-40af-8047-da555d43304b">
<File Id="CefSharp.Core.pdb" Name="CefSharp.Core.pdb" Source="$(var.EmbeddApp_TargetDir)CefSharp.Core.pdb" />
</Component>
<Component Id="CefSharp.Core.xml" Guid="71e6a1c8-e1c2-4f41-bf09-c664cd62b0a7">
<File Id="CefSharp.Core.xml" Name="CefSharp.Core.xml" Source="$(var.EmbeddApp_TargetDir)CefSharp.Core.xml" />
</Component>
<Component Id="CefSharp.pdb" Guid="1f6df66a-972c-4945-a675-ab7f6bff3207">
<File Id="CefSharp.pdb" Name="CefSharp.pdb" Source="$(var.EmbeddApp_TargetDir)CefSharp.pdb" />
</Component>
<Component Id="CefSharp.WinForms.pdb" Guid="9f9aa753-8be7-4349-bf90-3799c9cb8560">
<File Id="CefSharp.WinForms.pdb" Name="CefSharp.WinForms.pdb" Source="$(var.EmbeddApp_TargetDir)CefSharp.WinForms.pdb" />
</Component>
<Component Id="CefSharp.WinForms.xml" Guid="56dc62fa-e64e-4f92-a8df-3415423e65cd">
<File Id="CefSharp.WinForms.xml" Name="CefSharp.WinForms.xml" Source="$(var.EmbeddApp_TargetDir)CefSharp.WinForms.xml" />
</Component>
<Component Id="CefSharp.xml" Guid="c567fe97-a411-477d-8f5b-82432593c090">
<File Id="CefSharp.xml" Name="CefSharp.xml" Source="$(var.EmbeddApp_TargetDir)CefSharp.xml" />
</Component>
<Component Id="chrome_elf.dll" Guid="8272cf27-65c6-499e-b503-b56ed9f80db1">
<File Id="chrome_elf.dll" Name="chrome_elf.dll" Source="$(var.EmbeddApp_TargetDir)chrome_elf.dll" />
</Component>
<Component Id="d3dcompiler_47.dll" Guid="3405163c-2405-41e7-aeef-3f4f65df1dd2">
<File Id="d3dcompiler_47.dll" Name="d3dcompiler_47.dll" Source="$(var.EmbeddApp_TargetDir)d3dcompiler_47.dll" />
</Component>
<Component Id="devtools_resources.pak" Guid="e2ffd1f6-9283-442f-b83f-fde86ddf1553">
<File Id="devtools_resources.pak" Name="devtools_resources.pak" Source="$(var.EmbeddApp_TargetDir)devtools_resources.pak" />
</Component>
<Component Id="EmbeddApp.pdb" Guid="e040e421-d4b4-4916-9089-f2efb1459594">
<File Id="EmbeddApp.pdb" Name="EmbeddApp.pdb" Source="$(var.EmbeddApp_TargetDir)EmbeddApp.pdb" />
</Component>
<Component Id="icudtl.dat" Guid="a14f1e18-8813-42c1-bad6-f40ad21d1b25">
<File Id="icudtl.dat" Name="icudtl.dat" Source="$(var.EmbeddApp_TargetDir)icudtl.dat" />
</Component>
<Component Id="libcef.dll" Guid="22493d08-ed8f-4bf3-9708-ace297e0d2d7">
<File Id="libcef.dll" Name="libcef.dll" Source="$(var.EmbeddApp_TargetDir)libcef.dll" />
</Component>
<Component Id="libEGL.dll" Guid="8ffc6d72-f929-4162-b7d4-49b8229aeb32">
<File Id="libEGL.dll" Name="libEGL.dll" Source="$(var.EmbeddApp_TargetDir)libEGL.dll" />
</Component>
<Component Id="libGLESv2.dll" Guid="8e759d91-3e4c-4a02-9ba7-6dfaf4c0fa7e">
<File Id="libGLESv2.dll" Name="libGLESv2.dll" Source="$(var.EmbeddApp_TargetDir)libGLESv2.dll" />
</Component>
<Component Id="natives_blob.bin" Guid="15c51480-6cf0-4127-a949-d899ba5a3422">
<File Id="natives_blob.bin" Name="natives_blob.bin" Source="$(var.EmbeddApp_TargetDir)natives_blob.bin" />
</Component>
<Component Id="snapshot_blob.bin" Guid="50f987cb-551e-4734-9d15-b59e0fa7f868">
<File Id="snapshot_blob.bin" Name="snapshot_blob.bin" Source="$(var.EmbeddApp_TargetDir)snapshot_blob.bin" />
</Component>
<Component Id="v8_context_snapshot.bin" Guid="492bb45e-1cdf-4ee1-992f-5479edff99e9">
<File Id="v8_context_snapshot.bin" Name="v8_context_snapshot.bin" Source="$(var.EmbeddApp_TargetDir)v8_context_snapshot.bin" />
</Component>
<!--<Component Id="data_0" Guid="b2f7d81e-587b-4e5e-835a-e29b394ae574">
<File Id="data_0" Name="data_0" Source="$(var.EmbeddApp_TargetDir)GPUCache\data_0" />
</Component>-->
</ComponentGroup>
<CustomAction Id="EXECUTE_AFTER_FINALIZE"
Execute="immediate"
Impersonate="no"
Return="asyncNoWait"
FileKey="EmbeddApp.exe"
ExeCommand="" />
<InstallExecuteSequence>
<RemoveExistingProducts Before="InstallInitialize" Overridable="yes" />
<Custom Action="EXECUTE_AFTER_FINALIZE" After="InstallFinalize">NOT Installed</Custom>
<!--<RemoveExistingProducts Overridable="yes" Sequence="1" />
<Custom Action="EXECUTE_AFTER_FINALIZE" After="InstallFinalize">NOT Installed</Custom>-->
</InstallExecuteSequence>
</Fragment>
<!--<Fragment>
<ComponentGroup Id="ProductSubComponents" Directory="FOLDER1">
<Component Id="data_0" Guid="b2f7d81e-587b-4e5e-835a-e29b394ae574">
<File Id="data_0" Name="data_0" Source="$(var.EmbeddApp_TargetDir)GPUCache\data_0" />
</Component>
</ComponentGroup>
</Fragment>-->
</Wix>
</code></pre>
| 3 | 6,616 |
Adding search and time stamp filter to Elastic Search Nest client
|
<p>I want to search and filter data using c# Nest client
Below is the query written using Javascript-Elastic search and similar client i am trying to write in c# but its not working as expected</p>
<p>Javascript Elastic Search client :</p>
<pre><code> var from_ms = from.getTime();
var to_ms = to.getTime();
var query = 'temp:' + Temp + ' AND url:"type=' + value + '"';
client.search({
type: 'Type',
size: 5000,
q: query,
body: {
sort: [
{
"@timestamp": {
"order": "desc"
}
}
],
filter: {
"range": {
"@timestamp": {
"from": from_ms,
"to": to_ms
}
}
//"range": { "@timestamp": { "from": 1444118389, "to": 1444120189 }}
}
}
}).
</code></pre>
<p>C# Elastic Search code i tried but its not working as expected
I am not getting how can i add the query in c# as i have in JS and how to filter data using time stamp</p>
<pre><code> class ElasticearchQuery
{
public class REstt
{
public string test{ get; set; }
public string url { get; set; }
}
static void Main(string[] args)
{
try
{
var connection = new X509CertificateHttpConnection();
var connectionPool = new SingleNodeConnectionPool(new Uri("https://www.yy.com"));
var settings = new ConnectionSettings(connectionPool, connection);
var client = new ElasticClient(settings);
REstt person = new REstt();
QueryContainer query = new TermQuery()
{
Field = "temp",
Value = "value"
};
var searchRequest = new SearchRequest
{
From = 0,
Size = 5000,
Query = query
};
var searchResults = client.Search<REstt>(searchRequest);
var temp = searchResults.Hits;
Console.WriteLine(temp);
}
catch (Exception e)
{
}
}
</code></pre>
<p>}</p>
| 3 | 1,061 |
Multiple connected/dependent sliders with Dojo
|
<p>I am trying to create some sliders, which are interconnected. All sliders should always give a sum of 100. So, if Slider 1 = 50, Slider 2 and 3 should be set to 25 automatically.</p>
<p>The code works so far with some limitations: I cannot manipulate the sliders live (intermediateChange: true) and the sliders do not move any more, when one of them reached 100 and so the residuum got 0.</p>
<p>Here's my code:</p>
<pre><code><script>
require(["dijit/form/HorizontalSlider"], function(HorizontalSlider) {
var slider1 = new HorizontalSlider({
minimum: 0,
maximum: 100,
value: 10,
intermediateChanges: false,
onChange: function() {
console.log("Slider 1: " + slider1.get('value'));
var residue = slider2.get('value') + slider3.get('value')
slider2.set('value', (slider2.get('value') / residue) * (100 - slider1.get('value')));
slider3.set('value', (slider3.get('value') / residue) * (100 - slider1.get('value')));
}
}, "slider1");
var slider2 = new HorizontalSlider({
minimum: 0,
maximum: 100,
value: 45,
intermediateChanges: false,
onChange: function() {
console.log("Slider 2: " + slider2.get('value'));
var residue = slider1.get('value') + slider3.get('value')
slider1.set('value', (slider1.get('value') / residue) * (100 - slider2.get('value')));
slider3.set('value', (slider3.get('value') / residue) * (100 - slider2.get('value')));
}
}, "slider2");
var slider3 = new HorizontalSlider({
minimum: 0,
maximum: 100,
value: 45,
intermediateChanges: false,
onChange: function() {
console.log("Slider 3: " + slider3.get('value'));
var residue = slider1.get('value') + slider2.get('value')
slider1.set('value', (slider1.get('value') / residue) * (100 - slider3.get('value')));
slider2.set('value', (slider2.get('value') / residue) * (100 - slider3.get('value')));
}
}, "slider3");
slider1.startup();
slider2.startup();
slider3.startup();
});
</script>
</code></pre>
<p>How can I achieve the sliders keep connected, even if one was put to maximum?
Is there a smarter solution? In this way the code gets longer with every additional slider...</p>
| 3 | 1,149 |
Passportjs Google OAuth does not return profile object
|
<p>I am working on a MERN stack appliaction and I wanna integrate google authencation using PassportJs, I already configured the server-side and ran a couple of test which were successful but all of a sudden it no longers returns the usual profile object which contains the user's name, first_name, _json e.t.c, instead it sends back this object;</p>
<pre><code>{
access_token: 'ya29.A0ARrdaM8QpjEP_3sDyDRBT8OJiOlXVgOHFcyEV1nne13jd_qRelaTYh5ry0H0E8WvmOs14h6PycgTHqteS85U9lPxj2sfhnabOI6XdMgWAM_Z_y4WR1F50NR7MVDcjpH6aS8xLzewScSt8R-6Cs6t4Adn3Vgu',
expires_in: 3599,
scope: 'https://www.googleapis.com/auth/userinfo.email openid https://www.googleapis.com/auth/userinfo.profile',
token_type: 'Bearer',
id_token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImNlYzEzZGViZjRiOTY0Nzk2ODM3MzYyMDUwODI0NjZjMTQ3OTdiZDAiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiI5NDc2NDU0NDY5NTctZWhiNXN1dWduZnZkcGJzNnE5cXZjNDQ2ZWRzZTY4ZWwuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI5NDc2NDU0NDY5NTctZWhiNXN1dWduZnZkcGJzNnE5cXZjNDQ2ZWRzZTY4ZWwuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDA3NDM5NTc3MzIwMDkwMzE5OTAiLCJlbWFpbCI6InNpbW9uY2NvdmVuYW50QGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhdF9oYXNoIjoiODBfN20xMVJVNHV5SHZiblc2UEZIZyIsIm5hbWUiOiJTaW1vbiBDb3ZlbmFudCIsInBpY3R1cmUiOiJodHRwczovL2xoMy5nb29nbGV1c2VyY29udGVudC5jb20vYS9BQVRYQUp4QWtNdEhtSWFjLV9CNEFzVkVYQU5jMUF1WEh5QU5KNTdFVVRVPXM5Ni1jIiwiZ2l2ZW5fbmFtZSI6IlNpbW9uIiwiZmFtaWx5X25hbWUiOiJDb3ZlbmFudCIsImxvY2FsZSI6ImVuIiwiaWF0IjoxNjQ5MTA5MDk5LCJleHAiOjE2NDkxMTI2OTl9.cRn6YA8OYSkp_MGLoDQTqeu6R5Ajm3KQMg6cQkZaBXuduJIJOnVL1r-lgCAIDHmkTsH-gohBIWcELPL0Pzm0rueW2X6b0LEzPdFNMsHFL_RkbRh2bwPwqAZqToaEJsN6M9DqqQwjuc8aENwHOxflVfTqM71aidt96cEIucRcCYxF1Q-rxBw4STNy0c2Lqae_85fFO5uArEJPyOPYDjVYjEqR0wNWFezRadA8zAKV7tv2WJFhEbA2tgnnbIKP5rWmkF6V6mlbFKv9p2qFvBLUpj6ffqVnQZmwILJng6GvNrWu03VfbAvHao4PA-qLwPnge65hqjet3S8TxzlNkkAtDA'
}
</code></pre>
<p>This my passport setup:</p>
<pre><code>const strategy = new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/callback",
},
function (accessToken, refreshToken, profile, cb, done) {
console.log(profile);
const { email, given_name, family_name, email_verified, gender } = profile._json;
User.findOne({ email }).exec((err, user) => {
if (user) {
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {
expiresIn: "7d",
});
const { password, ...others } = user._doc;
return cb(err, others, token);
} else {
let password = email + process.env.JWT_SECRET;
user = new User({
firstname: given_name,
lastname: family_name,
email,
password: CryptoJS.AES.encrypt(
password,
process.env.PASS_SEC
).toString(),
gender: "male",
});
console.log(user);
user.save((err, data) => {
console.log(data);
if (err) {
console.log("Save error", errorHandler(err));
return done(null, false, { message: errorHandler(err) });
} else {
const token = jwt.sign({ _id: data._id }, process.env.JWT_SECRET, {
expiresIn: "7d",
});
const { password, ...others } = data._doc;
console.log(others);
return cb(err, token, others);
}
});
}
});
}
);
passport.use(strategy);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
</code></pre>
<p>And this is my routes :</p>
<pre><code>router.get(
"/google",
passport.authenticate("google", {
scope: ["profile", "email"],
})
);
router.get(
"/google/callback",
passport.authenticate("google", {
successRedirect: "/login/success",
failureRedirect: "/login/failed",
})
);
</code></pre>
<p>I thought maybe it had something to do with the accessToken so I tried using the "passport-oauth2-refresh" dependency to refresh and get a new accessToken;</p>
<pre><code>const refresh = require("passport-oauth2-refresh");
refresh.use(strategy);
</code></pre>
<p>But that didnt work, I have tried searching stack-overflow for similar issues but found none. The strange thing was that it was working before, cant seem to figure out what went wrong.</p>
<p>I also wanna ask, after successful authentication I want to be able to send the user to my frontend and store it in localStorage but I found out that <a href="https://stackoverflow.com/questions/46818363/how-to-handle-cors-in-a-service-account-call-to-google-oauth/46818486">Google or Oauth don't support CORS</a>. So I cannot make axios request nor catch server response, so what would be the optimal way to handle the authentication on the frontend?</p>
<p>My frontend google login code:</p>
<pre><code>const google = () => {
window.open(`${process.env.REACT_APP_API_URL}/auth/google`, "_self");
}
</code></pre>
| 3 | 2,601 |
Using pmax/pmin with vector of variable string names in R
|
<p>Is there a way to use pmax and pmin function in R with a vector of string variable names using the tidyverse (dplyr) format?</p>
<p>For instance,
I want to run the following:</p>
<pre><code>data(mtcars)
mtcars %>% mutate(maxval = pmax(drat, wt, na.rm = T)
</code></pre>
<p>This properly gets me the following:</p>
<pre><code> mpg cyl disp hp drat wt qsec vs am gear carb maxval
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 3.900
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 3.900
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 3.850
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 3.215
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 3.440
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 3.460
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 3.570
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 3.690
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 3.920
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 3.920
Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 3.920
Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 4.070
Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 3.730
Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 3.780
Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 5.250
Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 5.424
Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 5.345
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 4.080
</code></pre>
<p>But, say that I'm working on a very large data with quite a lot of variables, and I want to just use a vector of strings like <code>x1 = sprintf("xval_%1.0f", 1:25)</code> where x1 will be the list of variable columns I want to run pmax and pmin with. But when I do this, then I'm always given an error message that confuses the number of vectors with the number of observations. For instance, say I run the following:</p>
<pre><code>values = c("drat", "wt")
mtcars %>% mutate(maxval = pmax(all_of(values), na.rm = T))
</code></pre>
<p>Then I get the following error:</p>
<pre><code>Error: Problem with `mutate()` column `maxval`.
i `maxval = pmax(values, na.rm = T)`.
i `maxval` must be size 32 or 1, not 2.
</code></pre>
<p>Which seems to be getting at the number of observations (32).</p>
| 3 | 1,324 |
UIImage Upside Down When Reconverted From String Stored in SQLite
|
<p>I save an image from the simulator photo library.</p>
<p><a href="https://i.stack.imgur.com/gYibC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gYibC.png" alt="Original image from stock photo library" /></a></p>
<p>I then save the image as a string and when the user clicks Save, it is reconverted from the string into an image and placed in a table view in another controller. For some reason, only certain stock photos are being reconverted upside down.</p>
<p><a href="https://i.stack.imgur.com/Z1unF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z1unF.png" alt="Upside down image after reconverted back to image from string" /></a></p>
<p><strong>Code for converting image to string:</strong></p>
<pre><code>extension UIImage
{
func toString() -> String?
{
let data: Data? = self.pngData()
return data?.base64EncodedString(options: .lineLength64Characters)
}
}
</code></pre>
<p><strong>Code to reconvert string back to image:</strong></p>
<pre><code>extension String
{
func toImage() -> UIImage?
{
if let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters)
{
return UIImage(data: data)
}
return nil
}
}
</code></pre>
<p>The conversion is a derivation based on another StackOverflow page: <a href="https://stackoverflow.com/questions/11251340/convert-between-uiimage-and-base64-string">Convert between UIImage and Base64 string</a></p>
<p><strong>Database store code for entire 'family':</strong></p>
<pre><code> /**
INSERT operation prepared statement for family
- Parameters
- family: Contains the data for each child and parents' name and image
*/
func insertFamily(family: Family)
{
var insertStatement: OpaquePointer? = nil
let result = sqlite3_prepare_v2(self.db, self.insertFamilyQuery, -1, &insertStatement, nil)
if result == SQLITE_OK
{
// Bind values to insert statement
sqlite3_bind_text(insertStatement, 1, (family.childName! as NSString).utf8String, -1, nil)
sqlite3_bind_text(insertStatement, 2, (family.childImage! as NSString).utf8String, -1, nil)
sqlite3_bind_text(insertStatement, 3, (family.parentOneName! as NSString).utf8String, -1, nil)
sqlite3_bind_text(insertStatement, 4, (family.parentOneImage! as NSString).utf8String, -1, nil)
sqlite3_bind_text(insertStatement, 5, (family.parentTwoName! as NSString).utf8String, -1, nil)
sqlite3_bind_text(insertStatement, 6, (family.parentTwoImage! as NSString).utf8String, -1, nil)
// Execute statement
let result = sqlite3_step(insertStatement)
sqlite3_finalize(insertStatement) // Destroy statement to avoid memory leak
if result == SQLITE_DONE
{
os_log("Inserted family for %s", log: self.oslog, type: .info, family.childName!)
}
else
{
os_log("Could not insert family", log: self.oslog, type: .error)
os_log("Expected: %s Received: %s", log: self.oslog, type: .error, SQLITE_DONE, result)
}
}
else
{
os_log("INSERT statement could not be prepared", log: self.oslog, type: .error)
os_log("Expected: %s Received: %s", log: self.oslog, type: .error, SQLITE_DONE, result)
}
}
</code></pre>
<p><strong>Database read code for entire 'family':</strong></p>
<pre><code> /**
Pull the family for the given childName if it exists
- Parameters
- childName: The child's name associated with the family
- Returns: The family found
*/
func pullFamily(childName: String) -> Family?
{
var family = Family()
var readStatement: OpaquePointer? = nil
let selectStatement = self.pullFamilyQuery + childName + "'"
// Read
if sqlite3_prepare_v2(self.db, selectStatement, -1, &readStatement, nil) == SQLITE_OK
{
if sqlite3_step(readStatement) == SQLITE_ROW
{
let childName = String(describing: String(cString: sqlite3_column_text(readStatement, 0)))
let childImage = String(describing: String(cString: sqlite3_column_text(readStatement, 1)))
let parentOneName = String(describing: String(cString: sqlite3_column_text(readStatement, 2)))
let parentOneImage = String(describing: String(cString: sqlite3_column_text(readStatement, 3)))
let parentTwoName = String(describing: String(cString: sqlite3_column_text(readStatement, 4)))
let parentTwoImage = String(describing: String(cString: sqlite3_column_text(readStatement, 5)))
family = Family(childName: childName,
childImage: childImage,
parentOneName: parentOneName,
parentOneImage: parentOneImage,
parentTwoName: parentTwoName,
parentTwoImage: parentTwoImage)
}
}
else
{
os_log("Could not pull family by child name ", log: self.oslog, type: .error, childName)
}
sqlite3_finalize(readStatement) // Destroy statement to avoid memory leak
return family
}
</code></pre>
<p>Family Initializer</p>
<pre><code>init(childName: String?, childImage: UIImage?,
parentOneName: String?, parentOneImage: UIImage?,
parentTwoName: String?, parentTwoImage: UIImage?)
{
self.childName = childName
self.childImage = childImage
self.parentOneName = parentOneName
self.parentOneImage = parentOneImage
self.parentTwoName = parentTwoName
self.parentTwoImage = parentTwoImage
}
</code></pre>
<p>Test Code for Blob Write</p>
<pre><code>// Child Image
result = (family.childImage!.unrotatedPngData()?.withUnsafeBytes { bufferPointer -> Int32 in
sqlite3_bind_blob(insertStatement, 1, bufferPointer.baseAddress, Int32(bufferPointer.count), SQLITE_TRANSIENT) })!
guard result == SQLITE_OK else {
logger.error("[\(#function); \(#line)] ERROR: Could not bind child image")
logger.error("[\(#function); \(#line)] ERROR: Expected - \(SQLITE_OK), Received - \(result)")
logger.error("[\(#function); \(#line)] [ERROR: \(self.getDatabaseError())")
return
</code></pre>
<p>Test Code for Blob Read</p>
<pre><code>while sqlite3_step(readStatement) == SQLITE_ROW
{
guard
let childName = sqlite3_column_text(readStatement, 0).flatMap({ String(cString: $0) }),
let childImageBlob = sqlite3_column_blob(readStatement, 1)
//let parentOneName = sqlite3_column_text(readStatement, 2).flatMap({ String(cString: $0) }),
//let parentOneImageBlob = sqlite3_column_blob(readStatement, 3),
//let parentTwoName = sqlite3_column_text(readStatement, 4).flatMap({ String(cString: $0) }),
//let parentTwoImageBlob = sqlite3_column_blob(readStatement, 5)
else {
logger.error("[\(#function); \(#line)] Could not pull family")
logger.error("\(String(cString: sqlite3_errmsg(self.db)))")
return families
}
// Convert child image data to child image
let childData = Data(bytes: childImageBlob, count: Int(sqlite3_column_bytes(readStatement, 1)))
guard let childImage = UIImage(data: childData) else {
logger.error("Could not convert child image for child name \(childName)")
return families
}
...
}
</code></pre>
| 3 | 3,057 |
Hot track doesn't work in a virtual TListView while dragging
|
<p>If I take a virtual <code>TListView</code> and try to drag items (<code>Accept:= True</code> always) the "hot tracking" system looks corrupted. In win 7 the hot item remains near the selected item, while in win 8.1 it remains fixed at random positions.
I recorded this behavior to better understand what I mean:</p>
<p><a href="https://www.youtube.com/watch?v=e5eKWlqx_pA" rel="nofollow noreferrer">Here is the recording from win 7</a></p>
<p><a href="https://www.youtube.com/watch?v=_dl7-ryxexs" rel="nofollow noreferrer">Here is the recording from win 8.1</a></p>
<p>And this is the minimal code to reproduce the problem:</p>
<p><strong>.dfm</strong></p>
<pre><code>object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClientHeight = 378
ClientWidth = 398
Color = clBtnFace
DoubleBuffered = True
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object ListView1: TListView
Left = 78
Top = 40
Width = 221
Height = 286
Columns = <
item
Width = 130
end>
DragMode = dmAutomatic
MultiSelect = True
OwnerData = True
ReadOnly = True
RowSelect = True
TabOrder = 0
ViewStyle = vsReport
OnData = ListView1Data
OnDragOver = ListView1DragOver
end
end
</code></pre>
<p><strong>.pas</strong></p>
<pre><code>unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls;
type
TForm1 = class(TForm)
ListView1: TListView;
procedure ListView1Data(Sender: TObject; Item: TListItem);
procedure FormCreate(Sender: TObject);
procedure ListView1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
ListView1.Items.Count:= 10;
end;
procedure TForm1.ListView1Data(Sender: TObject; Item: TListItem);
begin
Item.Caption:= 'Item '+IntToStr(Item.Index);
end;
procedure TForm1.ListView1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept:= True;
end;
end.
</code></pre>
<p>Of course, the question is, if anything can be done to correct this behavior ?</p>
<p><strong>Edit:</strong></p>
<p>I tried to implement my own tracking system, and it seems it's working but with a little exception: the uppermost item under the cursor remains always selected...</p>
<pre><code>function TListView.GetItemIndexAt(X, Y: Integer): Integer;
var Info: TLVHitTestInfo;
begin
Result:= -1;
if HandleAllocated then begin
Info.pt:= Point(X, Y);
Result:= ListView_HitTest(Handle, Info);
end;
end;
procedure TForm1.ListView1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
var Src, Dest, I: Integer;
begin
Accept:= True;
Src:= ListView1.Selected.Index;
Dest:= ListView1.GetItemIndexAt(X, Y);
for I:= 0 to ListView1.Items.Count-1 do
if (I = Src) or (I = Dest) then ListView1.Items[I].Selected:= True
else ListView1.Items[I].Selected:= False;
end;
</code></pre>
| 3 | 1,231 |
Accessing JSON values in JQUERY/AJAX based on condition
|
<p>Please be patient because I know this question might have been answered but I have not been able to find it. I have been working on a project & lately I just started using AJAX.</p>
<p>My JSON is coming from PHP, which includes errors and success, now the issue is how do I access success(if the registrattion is successful to display as Text(not alert)) and display errors when registration fails.</p>
<p>What conditions should be used?</p>
<pre><code><div class="remodal" data-remodal-id="RegisterModal">
<div class="popup-1">
<div class="popup-content" id="register_container">
<div id="register_title" class="popup-title text-purple">Sign Up</div>
<div class="reg-notification">
<p>You Successfully registered to our website and now you can login and use our services</p>
<a href="feed.php" class="popup-link">Continue</a>
</div>
<div id="json"></div>
<form id="register-form" action="register.php" method="POST">
<div class="form-grp">
<!--<label>Username</label>-->
<input type="text" id="username" name="username" placeholder="Username">
</div>
<div class="form-grp">
<input type="email" name="register_email" id="register_email" placeholder="Email">
</div>
<div class="form-grp">
<input type="password" id="register_password" name="register_password" placeholder="Password">
</div>
<div class="form-grp">
<input type="password" id="confirm_password" name="confirm_password" placeholder="Retype Password">
</div>
<div class="btn-grp">
<button type="submit" name="submit" class="button-purple" id="do_register">Sign Up</button>
<button class="button-white" style="margin-left: 30px;" data-remodal-target="LoginModal">Login to access</button>
</div>
</form>
</div>
</code></pre>
<p>This is my PHP below</p>
<pre><code> if (strlen($password) >= 8 && strlen($password) <= 60) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$account->addUser($username, $password, $email);
if ($account->userExist()) {
$message['email'] = "Email Address Is Already Registered!";
} else {
$account->create();
$message['type'] = "success";
}
} else {
$message = 'Invalid email!, Please enter a valid Email';
}
header('Content-Type: application/json');
$response = ['message' => $message];
echo json_encode($response);
// echo json_encode($message);
//echo $message;
</code></pre>
<p>and this is my AJAX</p>
<pre><code>$.ajax({
type: 'POST',
url: 'register.php',
dataType: 'json',
data: formData,
success: function (data) {
$("#json").html(data["message"]);
//response = response.slice(0, -1);
//response = JSON.parse(response);
//var json = JSON.parse(response);
//var resdata = response;
//var json = $.parseJSON(response);
//if (resdata) {
//alert(resdata['success']);
//alert(json['success']);
// $("#register-form").addClass("remove-form");
// $("#register_container").addClass("register-container-active");
// $("#register_title").html("Register was Successful");
// $(".reg-notification").addClass("show-reg-notification");
//}else if (resdata['email']) {
//alert(resdata['email']);
//}
//alert(json['email']);
//$("#msg").html(json.email);
//}
console.log(response);
},
error:function(error){
console.log(error);
}
});
</code></pre>
<p>As you can see all the codes I commented are failed codes, I like to display the message coming from PHP in my #json ID.</p>
<p>What I like to do is get the 'success' encoded from PHP to my HTML through AJAX, if user registration is successful, also get the 'email' error out if user exists. </p>
<p>I have no idea what condition to use in AJAX to test this or how to go about it and I know it will be something simple. </p>
<p>But I may be to clustered in the head to figure it ..as I keep looking at :(</p>
| 3 | 2,444 |
error is coming in this line os.path.exists()
|
<p>i am getting an error like below when I am trying to search the server after adding the server .</p>
<p>Linux server </p>
<pre><code>while(h):
ch= raw_input("""####################################
1.Search
2.Add
3.Edit 5.Exit
####################################
""")
print(ch)
if "1" in ch:
a=''
ser1 = raw_input ("Enter Server Name Which You Want To Search:")
print(ser1)
a=('/opt/Projects/avo_user_error/Inv/'+ ser1 +'.txt')
print(a)
c=os.path.exists(a)
print(c)
if q == c:
aa=('/opt/Projects/avo_user_error/Inv/'+ ser1 +'.txt')
#print(aa)
file=open(aa,"r")
re=file.read()
print(re)
else:
print("Server Not Found Kindly Check...")
elif "2" in ch:
ser = raw_input ("Enter Server Name :")
print(ser)
x=( ser +'.txt')
print(x)
v=os.path.exists(x)
print(v)
if q != v:
d3 = ('/opt/Projects/avo_user_error/Inv/'+ ser +'.txt')
fi = open(d3, "w+")
fi.write('Server Name :' +ser +'\n')
app = raw_input ("Enter Server Is Blowing To Which Application :")
print(app)
fi.write('Server Is Blowing To Which Application :' + app +'\n')
ser_os = raw_input ("Enter Server is in Unix/Windows :")
print(ser_os)
fi.write('Server is in Unix/Windows :' + ser_os +'\n')
ser_db = raw_input ("Enter The DB Server :")
print(ser_db)
fi.write('DB Server :' + ser_db +'\n')
db_type = raw_input ("Enter The Type Of DB :")
print(db_type)
fi.write('Type Of DB :' + db_type +'\n')
os = raw_input ("Enter The OS :")
print(os)
fi.write('OS :' + os +'\n')
sup = raw_input ("Enter The Support / Functional Team/SPOC :")
print(sup)
fi.write('The Support / Functional Team/SPOC :' + sup +'\n')
ven = raw_input ("Enter The Vendor Support(Yes/No) :")
print(ven)
fi.write('The Vendor Support(Yes/No) :' + ven +'\n')
ven_det = raw_input ("Enter The Vendor Details :")
print(ven_det)
fi.write('The Vendor Details :' + ven_det +'\n')
fi.close()
print("Server Added Successfully...")
else:
print("Server Already Present Kindly Check...")
elif "3" in ch:
print("Edit")
elif "4" in ch:
ser2 = raw_input ("Enter Server Name Which You Want To Retire:")
print(ser2)
y=( ser2 +'.txt')
print(y)
g=os.path.exists(y)
print(g)
if q == g:
d3 = ('/opt/Projects/avo_user_error/Inv/'+ ser2 +'.txt')
fi = open(d3, "w+")
r_comm = raw_input ("Enter The Comment For Retirement :")
print(r_comm)
fi.write('Comment For Retirement :' + r_comm +'\n')
fi.close()
cmd1 = 'mv /opt/Projects/avo_user_error/Inv/'+ ser2 +'.txt /opt/Projects/avo_user_error/Inv/Retire/'
#print(cmd1)
os.system(cmd1)
print("Server Retirement Completed...")
else:
print("Server Not Found Kindly Check...")
elif"5" in ch:
exit()
print("Thany You...")
else:
print("Please Choose Correct Option...")
</code></pre>
<p>it should search the server and display the details. below is the error msg</p>
<p>Traceback (most recent call last):
File "Inv.py", line 32, in
c=os.path.exists(a)
AttributeError: 'str' object has no attribute 'path'</p>
| 3 | 2,685 |
Wordpress post categories Ajax URL structure
|
<p>I have a basic wordpress blog that has categories and when the categories are clicked the posts filter. This works great but I ideally want when the category is clicked the URL to change to</p>
<pre><code>http://site.preview/resources/CATEGORYNAME
</code></pre>
<p>currently the blog loads as <code>http://site.preview/resources/</code> and when a category is clicked it changes to <code>http://site.preview/resources/#</code></p>
<p>Hope I explained this properly. Please find my code below.</p>
<p><strong>Home.php - blog</strong></p>
<pre><code><?php get_header('home'); ?>
<div class="banner">
<div class="in">
<img src="<?php echo get_stylesheet_directory_uri() . '/assets/images/blue-cover-with-illustrations.png' ?>">
<div class="banner__content">
<div class="in">
<h1>The Good Air Resources Center</h1>
<h2>Knowledge to figure out indoor air quality. Tips to breathe cleaner air</h2>
</div>
</div>
</div>
</div>
<section class="blog">
<div class="in">
<?php
$categories = get_categories(); ?>
<div class="categories">
<div class="in">
<h5>Categories</h5>
<ul id="category-menu">
<?php foreach ( $categories as $cat ) { ?>
<li id="cat-<?php echo $cat->term_id; ?>">
<a class="<?php echo $cat->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#">
<?php echo $cat->name; ?>
</a>
</li>
<?php } ?>
</ul>
</div>
</div>
<div class="posts">
<div class="in">
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'publish_date'
);
$post_query = new WP_Query($args);
if($post_query->have_posts() ) {
while($post_query->have_posts() ) {
$post_query->the_post();
?>
<div class="post">
<div class="in">
<div class="post__image">
<?php the_post_thumbnail(); ?>
</div>
<div class="post__title">
<h4>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h4>
</div>
<div class="post__content">
<?php the_excerpt(); ?>
</div>
<div class="post__readmore">
<a href="<?php the_permalink(); ?>" class="btn btn--brand btn--block">Read More ></a>
</div>
</div>
</div>
<?php } } ?>
</div>
</div>
<div id="loading-animation" style="display: none;">
<img src="<?php echo admin_url ( 'images/loading-publish.gif' ); ?>" />
</div>
</div>
</section>
<script>
function cat_ajax_get(catID) {
jQuery("a.ajax").removeClass("current");
jQuery("a.ajax").addClass("current");
jQuery("#loading-animation-2").show();
var ajaxurl = '/wp-admin/admin-ajax.php';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {
"action": "load-filter",
cat: catID
},
success: function (response) {
jQuery(".posts .in").html(response);
jQuery("#loading-animation").hide();
return false;
}
});
}
</script>
</article>
<?php get_footer('home'); ?>
</code></pre>
<p><strong>Functions.php</strong></p>
<pre><code>add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
$cat_id = $_POST[ 'cat' ];
$args = array (
'cat' => $cat_id,
'order' => 'DESC'
);
$posts = get_posts( $args );
global $post;
ob_start ();
foreach ( $posts as $post ) {
setup_postdata( $post ); ?>
<div class="post">
<div class="in">
<div class="post__image">
<?php the_post_thumbnail(); ?>
</div>
<div class="post__title">
<h4>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h4>
</div>
<div class="post__content">
<?php the_excerpt(); ?>
</div>
<div class="post__readmore">
<a href="<?php the_permalink(); ?>" class="btn btn--brand btn--block">Read More ></a>
</div>
</div>
</div>
<?php } wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();
echo $response;
die(1);
}
</code></pre>
<p>Thanks</p>
| 3 | 3,674 |
.sliderImage object has no method apply
|
<p>i am using jquery 1.7.2 in my image slider code and i am getting following error in my console,i dont understand why ???</p>
<p><strong>HTML code:</strong></p>
<pre><code> <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>iSlider</title>
<meta name="robots" content="index, follow, noarchive" />
<!-- CSS -->
<link rel="stylesheet" href="css/style.css" type="text/css" />
<link rel="stylesheet" href="css/iSlider.css" type="text/css" />
<!-- JS -->
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<!-- <script type="text/javascript" src="js/jquery.js"></script> -->
<script type="text/javascript" src="js/jquery.ui.touch-punch.js"></script>
<script type="text/javascript" src="js/jquery-css-transform.js"></script>
<script type="text/javascript" src="js/rotate3Di.js"></script>
<script type="text/javascript">
var imgFront=new Array();
var n=0;
var backimg=new Array();
var frontimg=new Array();
var imgArr = new Array();
var bgImg = new Array();
var arrBackImg = new Array();
var frontText = new Array();
var backText =new Array();
var eventChk="";
var i = 1;
var ua = navigator.userAgent;
var clickEvent = (ua.match(/iPad/i)) ? 'touchstart' : 'click';
var isTouchSupported = "ontouchend" in document
$(document).ready(function () {
$('#myImageFlow').on('click touchstart',".sliderImage", touchStart());
});
</script>
</head>
<body style="background-image:url('img/Mesh2.png');background-repeat:no-repeat; background-size: cover; width:'100%'">
<h1>iSlider</h1>
<!-- This is all the XHTML ImageFlow needs -->
<div id="myImageFlow" class="imageflow">
<div id="id1" alt='div1' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img1.jpg'); border:solid; border-color: black;">You've styled the div to have a set width of 100px. At a reasonable font size, that's too much text to fit in 100px. Without doing anything, </div>
<div id="id2" alt='div2' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img2.jpg'); border:solid; border-color: black;">this is 2</div>
<div id="id3" alt='div3' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img3.jpg'); border:solid; border-color: black;">this is 3</div>
<div id="id4" alt='div4' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img4.jpg'); border:solid; border-color: black;">this is 4</div>
<div id="id5" alt='div5' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden; background-image:url('img/img5.jpg'); border:solid; border-color: black;">this is 5</div>
<div id="id6" alt='div6' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img6.jpg'); border:solid; border-color: black;"> this is 6</div>
<div id="id7" alt='div7' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img7.jpg'); border:solid; border-color: black;"> this is 7</div>
<div id="id8" alt='div8' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img8.jpg'); border:solid; border-color: black;">this is 8</div>
<div id="id9" alt='div9' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img9.jpg'); border:solid; border-color: black;"> this is 9</div>
<div id="id10" alt='div10' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img10.jpg'); border:solid; border-color: black;">this is 10</div>
<div id="id11" alt='div11' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img11.jpg'); border:solid; border-color: black;">this is 11</div>
<div id="id12" alt='div12' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img12.jpg'); border:solid; border-color: black;">this is 12</div>
<div id="id13" alt='div13' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img13.jpg');border:solid; border-color: black;">this is 13</div>
<div id="id14" alt='div14' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img12.jpg'); border:solid; border-color: black;">this is 14</div>
<div id="id15" alt='div15' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img6.jpg'); border:solid; border-color: black;"> this is 15</div>
<div id="id16" alt='div16' class="sliderImage" width="300" height="360" onclick="" style="visibility:hidden;background-image:url('img/img7.jpg'); border:solid; border-color: black;"> this is 16</div>
</div>
</body>
</html>
</code></pre>
<p>Uncaught TypeError: Object .sliderImage has no method 'apply'</p>
| 3 | 2,550 |
Why android Facebook integration crash?
|
<p>I am trying to integrate Android application with facebook. I am following these tutorials:
<a href="https://developers.facebook.com/docs/android/getting-started" rel="nofollow">https://developers.facebook.com/docs/android/getting-started</a></p>
<p><a href="http://code.tutsplus.com/tutorials/quick-tip-add-facebook-login-to-your-android-app--cms-23837" rel="nofollow">http://code.tutsplus.com/tutorials/quick-tip-add-facebook-login-to-your-android-app--cms-23837</a> </p>
<p>But I am facing the following problems :</p>
<pre><code>01-05 12:52:45.325 463-463/socialmediaintegration.arifhasnat.com.facebooklogin E/AndroidRuntime: FATAL EXCEPTION: main
Process: socialmediaintegration.arifhasnat.com.facebooklogin, PID: 463
java.lang.ExceptionInInitializerError
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:839)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at socialmediaintegration.arifhasnat.com.facebooklogin.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5293)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:830)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:646)
at dalvik.system.NativeStart.main(Native Method)
Caused by: null
at com.facebook.internal.Validate.sdkInitialized(Validate.java:99)
at com.facebook.FacebookSdk.getCallbackRequestCodeOffset(FacebookSdk.java:735)
at com.facebook.internal.CallbackManagerImpl$RequestCodeOffset.toRequestCode(CallbackManagerImpl.java:109)
at com.facebook.login.widget.LoginButton.<clinit>(LoginButton.java:58)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:839)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at socialmediaintegration.arifhasnat.com.facebooklogin.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5293)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:830)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:646)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Here is my code:
MainActivity.java</p>
<pre><code>package socialmediaintegration.arifhasnat.com.facebooklogin;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MainActivity extends AppCompatActivity {
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
info = (TextView)findViewById(R.id.info);
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
info.setText(
"User ID: "
+ loginResult.getAccessToken().getUserId()
+ "\n" +
"Auth Token: "
+ loginResult.getAccessToken().getToken()
);
}
@Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
@Override
public void onError(FacebookException e) {
info.setText("Login attempt failed.");
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
</code></pre>
<p>menifest.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="socialmediaintegration.arifhasnat.com.facebooklogin" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<uses-permission android:name="android.permission.INTERNET"/>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar" >
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />
<provider android:authorities="com.facebook.app.FacebookContentProvider1234"
android:name="com.facebook.FacebookContentProvider"
android:exported="true" />
</application>
</manifest>
</code></pre>
<p>layout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="16dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/info"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="18sp"
/>
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
</code></pre>
<p>And gradle dependencies :</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "socialmediaintegration.arifhasnat.com.facebooklogin"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}
</code></pre>
| 3 | 4,233 |
File Lock Exception
|
<p>I am using neo4j grails plugin for embedded mode. I am getting file lock exception.i make sure,no other process is using this file. i have tried to give super user permission to file use chmod but it didn't work. so how can i resolve it</p>
<p>Exception stack follows -></p>
<h2>Caused by OverlappingFileLockException: null</h2>
<pre><code>>> 1154 | tryLock in java.nio.channels.FileChannel
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 113 | tryLock in org.neo4j.kernel.impl.nioneo.store.StoreFileChannel
| 35 | wrapFileChannelLock in org.neo4j.kernel.impl.nioneo.store.FileLock
| 93 | getOsSpecificFileLock in ''
| 92 | tryLock . in org.neo4j.kernel.DefaultFileSystemAbstraction
| 74 | checkLock in org.neo4j.kernel.StoreLocker
| 44 | start . . in org.neo4j.kernel.StoreLockerLifecycleAdapter
| 507 | start in org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance
| 115 | start . . in org.neo4j.kernel.lifecycle.LifeSupport
| 328 | run in org.neo4j.kernel.InternalAbstractGraphDatabase
| 56 | <init> . in org.neo4j.kernel.EmbeddedGraphDatabase
| 90 | newDatabase in org.neo4j.graphdb.factory.GraphDatabaseFactory$1
| 199 | newGraphDatabase in org.neo4j.graphdb.factory.GraphDatabaseBuilder
| 70 | newEmbeddedDatabase in org.neo4j.graphdb.factory.GraphDatabaseFactory
| 53 | create . in org.neo4j.jdbc.internal.embedded.EmbeddedDatabases$Type$3
| 91 | createDatabase in org.neo4j.jdbc.internal.embedded.EmbeddedDatabases
| 109 | createExecutor in ''
| 146 | createExecutor in org.neo4j.jdbc.Driver
| 131 | createExecutor in org.neo4j.jdbc.internal.Neo4jConnection
| 79 | <init> in ''
| 65 | doCreate in org.neo4j.jdbc.internal.Connections$4
| 80 | create in org.neo4j.jdbc.internal.Connections
| 42 | connect . in org.neo4j.jdbc.Driver
| 74 | execute in org.grails.datastore.gorm.neo4j.engine.JdbcCypherEngine
| 80 | setupIndexing in org.grails.datastore.gorm.neo4j.Neo4jDatastore
| 67 | afterPropertiesSet in ''
| 50 | getObject in org.grails.datastore.gorm.neo4j.bean.factory.Neo4jDatastoreFactoryBean
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . in java.lang.Thread
My Data Source is
dataSource {
pooled = true
driverClassName = "org.neo4j.jdbc.Driver"
// use impermanent graph db, this requires an additional dependency in BuildConfig.groovy:
// runtime(group:"org.neo4j", name:"neo4j-kernel", version:neo4jVerison, classifier:"tests")
url = "jdbc:neo4j:file:/home/alok/Documents/db5"
// uncomment for embedded usage
//url = "jdbc:neo4j:instance:test"
// use remote database
//url = "jdbc:neo4j://localhost:7474/"
// disabling autoCommit is crucial!
properties = [
defaultAutoCommit: false
]
// username = "sa"
// password = ""
}
</code></pre>
<p>Build config is</p>
<pre><code>grails.servlet.version = "3.0" // Change depending on target container compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.work.dir = "target/work"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"
grails.server.port.http = 6768
grails.project.fork = [
// configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
// compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the test-app JVM, uses the daemon by default
test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the run-app JVM
run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
// configure settings for the run-war JVM
war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
// configure settings for the Console UI JVM
console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]
]
grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
// inherit Grails' default dependencies
inherits("global") {
// specify dependency exclusions here; for example, uncomment this to disable ehcache:
// excludes 'ehcache'
}
log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
checksums true // Whether to verify checksums on resolve
legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility
repositories {
inherits true // Whether to inherit repository definitions from plugins
grailsPlugins()
grailsHome()
mavenLocal()
grailsCentral()
mavenCentral()
// uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
//mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/"
mavenRepo 'http://m2.neo4j.org/content/repositories/releases/'
}
neo4jVerison="2.0.3"
dependencies {
compile("org.neo4j:neo4j-community:$neo4jVerison")
// this is required if DataSource.groovy uses url = "jdbc:neo4j:mem"
//runtime(group:"org.neo4j", name:"neo4j-kernel", version:neo4jVerison, classifier:"tests")
// next four lines are required if you're using embedded/ha *and* you want the webadmin available
//compile(group:"org.neo4j.app", name:"neo4j-server", version:neo4jVerison)
// grails dependencies do not properly support maven classifiers, therefor we'll copy that
// dependency to lib directory
//runtime(group:"org.neo4j.app", name:"neo4j-server", version:neo4jVerison, classifier:"static-web")
//runtime('com.sun.jersey:jersey-server:1.9')
//runtime('com.sun.jersey:jersey-core:1.9')
// add graphviz capabilities
compile(group:"org.neo4j", name:"neo4j-graphviz", version: neo4jVerison)
runtime (group:"org.neo4j", name:"neo4j-shell", version: neo4jVerison)
// uncomment following line if type=rest is used in DataSource.groovy
//runtime "org.neo4j:neo4j-rest-graphdb:1.9"
test "org.spockframework:spock-grails-support:0.7-groovy-2.0"
// runtime(group:"org.neo4j", name:"neo4j-kernel", version:neo4jVerison, classifier:"tests")
}
plugins {
// plugins for the build system only
build ":tomcat:7.0.55"
compile ":neo4j:2.0.0-M02"
// plugins for the compile step
compile ":scaffolding:2.1.2"
compile ':cache:1.1.7'
compile ":asset-pipeline:1.9.6"
// plugins needed at runtime but not for compilation
//runtime ":hibernate4:4.3.5.5" // or ":hibernate:3.6.10.17"
runtime ":database-migration:1.4.0"
runtime ":jquery:1.11.1"
// Uncomment these to enable additional asset-pipeline capabilities
//compile ":sass-asset-pipeline:1.9.0"
//compile ":less-asset-pipeline:1.10.0"
//compile ":coffee-asset-pipeline:1.8.0"
//compile ":handlebars-asset-pipeline:1.3.0.3"
}
}
</code></pre>
| 3 | 3,058 |
PostgreSQL complex summation query
|
<p>I have the following tables:</p>
<pre><code>video (id, name)
keyframe (id, name, video_id) /*video_id has fk on video.id*/
detector (id, concepts)
score (detector_id, keyframe_id, score) /*detector_id has fk on detector .id and keyframe_id has fk on keyframe.id*/
</code></pre>
<p>In essence, a video has multiple keyframes associated with it, and each keyframe has been scored by all detectors. Each detector has a string of concepts it will score the keyframes on.</p>
<p>Now, I want to find, in a single query if possible, the following:</p>
<p>Given an array of detector id's (say, max 5), return the top 10 videos that have the best score on those detectors combined. Scoring them by averaging the keyframe scores per video per detector, and then summing the detector scores.</p>
<p>Example:
For a video with 3 associated keyframes with the following scores for 2 detectors:</p>
<pre><code>detector_id | keyframe_id | score
1 1 0.0281
1 2 0.0012
1 3 0.0269
2 1 0.1341
2 2 0.9726
2 3 0.7125
</code></pre>
<p>This would give a score of the video:</p>
<pre><code>sum(avg(0.0281, 0.0012, 0.0269), avg(0.1341, 0.9726, 0.7125))
</code></pre>
<p>Eventually I want the following result:</p>
<pre><code>video_id | score
1 0.417328
2 ...
</code></pre>
<p>It has to be something like this I think, but I'm not quite there yet:</p>
<pre><code>select
(select
(select sum(avg_score) summed_score
from
(select
avg(s.score) avg_score
from score s
where s.detector_id = ANY(array[1,2,3,4,5]) and s.keyframe_id = kf.id) x)
from keyframe kf
where kf.video_id = v.id) y
from video v
</code></pre>
<p>My score table is pretty big (100M rows), so I'd like it to be as fast as possible (all other options I tried take minutes to complete). I have a total of about 3000 videos, 500 detectors, and about 15 keyframes per video.</p>
<p>If it's not possible to do this in less than ~2s, then I am also open to ways of restructuring the database schema's. There will probably be no inserts/deletions in the database at all.</p>
<p><strong>EDIT</strong>:</p>
<p>Thanks to GabrielsMessanger I have an answer, here is the query plan:</p>
<pre><code>EXPLAIN (analyze, verbose)
SELECT
v_id, sum(fd_avg_score)
FROM (
SELECT
v.id as v_id, k.id as k_id, d.id as d_id,
avg(s.score) as fd_avg_score
FROM
video v
JOIN keyframe k ON k.video_id = v.id
JOIN score s ON s.keyframe_id = k.id
JOIN detector d ON d.id = s.detector_id
WHERE
d.id = ANY(ARRAY[1,2,3,4,5]) /*here goes detector's array*/
GROUP BY
v.id,
k.id,
d.id
) sub
GROUP BY
v_id
;
</code></pre>
<p>.</p>
<pre><code>"GroupAggregate (cost=1865513.09..1910370.09 rows=200 width=12) (actual time=52141.684..52908.198 rows=2991 loops=1)"
" Output: v.id, sum((avg(s.score)))"
" Group Key: v.id"
" -> GroupAggregate (cost=1865513.09..1893547.46 rows=1121375 width=20) (actual time=52141.623..52793.184 rows=1121375 loops=1)"
" Output: v.id, k.id, d.id, avg(s.score)"
" Group Key: v.id, k.id, d.id"
" -> Sort (cost=1865513.09..1868316.53 rows=1121375 width=20) (actual time=52141.613..52468.062 rows=1121375 loops=1)"
" Output: v.id, k.id, d.id, s.score"
" Sort Key: v.id, k.id, d.id"
" Sort Method: external merge Disk: 37232kB"
" -> Hash Join (cost=11821.18..1729834.13 rows=1121375 width=20) (actual time=120.706..51375.777 rows=1121375 loops=1)"
" Output: v.id, k.id, d.id, s.score"
" Hash Cond: (k.video_id = v.id)"
" -> Hash Join (cost=11736.89..1711527.49 rows=1121375 width=20) (actual time=119.862..51141.066 rows=1121375 loops=1)"
" Output: k.id, k.video_id, s.score, d.id"
" Hash Cond: (s.keyframe_id = k.id)"
" -> Nested Loop (cost=4186.70..1673925.96 rows=1121375 width=16) (actual time=50.878..50034.247 rows=1121375 loops=1)"
" Output: s.score, s.keyframe_id, d.id"
" -> Seq Scan on public.detector d (cost=0.00..11.08 rows=5 width=4) (actual time=0.011..0.079 rows=5 loops=1)"
" Output: d.id, d.concepts"
" Filter: (d.id = ANY ('{1,2,3,4,5}'::integer[]))"
" Rows Removed by Filter: 492"
" -> Bitmap Heap Scan on public.score s (cost=4186.70..332540.23 rows=224275 width=16) (actual time=56.040..9961.040 rows=224275 loops=5)"
" Output: s.detector_id, s.keyframe_id, s.score"
" Recheck Cond: (s.detector_id = d.id)"
" Rows Removed by Index Recheck: 34169904"
" Heap Blocks: exact=192845 lossy=928530"
" -> Bitmap Index Scan on score_index (cost=0.00..4130.63 rows=224275 width=0) (actual time=49.748..49.748 rows=224275 loops=5)"
" Index Cond: (s.detector_id = d.id)"
" -> Hash (cost=3869.75..3869.75 rows=224275 width=8) (actual time=68.924..68.924 rows=224275 loops=1)"
" Output: k.id, k.video_id"
" Buckets: 16384 Batches: 4 Memory Usage: 2205kB"
" -> Seq Scan on public.keyframe k (cost=0.00..3869.75 rows=224275 width=8) (actual time=0.003..33.662 rows=224275 loops=1)"
" Output: k.id, k.video_id"
" -> Hash (cost=46.91..46.91 rows=2991 width=4) (actual time=0.834..0.834 rows=2991 loops=1)"
" Output: v.id"
" Buckets: 1024 Batches: 1 Memory Usage: 106kB"
" -> Seq Scan on public.video v (cost=0.00..46.91 rows=2991 width=4) (actual time=0.005..0.417 rows=2991 loops=1)"
" Output: v.id"
"Planning time: 2.136 ms"
"Execution time: 52914.840 ms"
</code></pre>
| 3 | 3,330 |
Custom plugin for librdkafka registering oauthbearer_token_refresh_cb not being called
|
<p>I'm trying to write custom plugin for <code>librdkafka</code> which will provide custom implementation of <code>oauthbearer_token_refresh_cb</code>.</p>
<p>In our company we use kafka with custom OAUTHBEARER sasl mechanism, which is working fine in java/kotlin, also work fine in .Net. Next step is to implement same for <code>librdkafka</code> because we need it for Clickhouse DB's implementation of kafka connector which uses <code>librdkafka</code>.</p>
<p>I tried with following impelenation for plugin:</p>
<h3>custom-oauth.c</h3>
<pre><code>#include <librdkafka/rdkafka.h>
#include <stdio.h>
void oauth_refresh (rd_kafka_t *rk, const char *oauthbearer_config, void *opaque) {
char err_msg[2048];
const char *token;
long long expiry = 0;
printf("============== Initializing oauthbearer config: %s\n", oauthbearer_config);
token = "<custom logic implementation>";
rd_kafka_oauthbearer_set_token(rk, token, expiry, "", NULL, 0, err_msg, sizeof(err_msg));
printf("============== Oauthbearer token set: %s\n", token);
}
void conf_init(rd_kafka_conf_t *conf, const char *path, char *errstr, size_t errstr_size) {
printf("============== registering callback\n");
rd_kafka_conf_set_oauthbearer_token_refresh_cb(conf, oauth_refresh);
if (rd_kafka_last_error()) {
printf("============== got some error: %d\n", rd_kafka_last_error());
}
printf("============== callback registered\n");
}
</code></pre>
<p>Compile it with:</p>
<pre><code>gcc -c -fPIC custom-oauth.c -o oauth-cb.o
</code></pre>
<p>Make shared library:</p>
<pre><code>gcc -shared oauth-cb.o -lrdkafka -o lib-oauth-cb.so
</code></pre>
<p>Try it out with <code>kafkacat</code> by:</p>
<pre><code>kafkacat -L \
-X debug="all" \
-X log_level=0 \
-b my-broker-1:9094 \
-X security.protocol=SASL_SSL \
-X ssl.ca.location=/path-to-my-cer.pem \
-X sasl.mechanisms=OAUTHBEARER \
-X plugin.library.paths=lib-oauth-cb.so \
-X sasl.oauthbearer.config="my-custom-oauth-config"
</code></pre>
<p>Results in:</p>
<pre><code>============== registering callback
============== callback registered
% ERROR: No such configuration property: "plugin.library.paths" (plugin lib-oauth-cb.so)
</code></pre>
<p>If I comment-out all printf-s happening after <code>rd_kafka_conf_set_oauthbearer_token_refresh_cb</code> then I don't get <code>% ERROR: No such configuration property: "plugin.library.paths" (plugin lib-oauth-cb.so)</code></p>
<p>But then also doesn't work and my callback for setting oauth bearer token is never called.
This is output:</p>
<pre><code>============== registering callback
%7|1605365045.759|SASL|rdkafka#producer-1| [thrd:app]: Selected provider OAUTHBEARER (builtin) for SASL mechanism OAUTHBEARER
%7|1605365045.759|OPENSSL|rdkafka#producer-1| [thrd:app]: Using OpenSSL version OpenSSL 1.1.1g 21 Apr 2020 (0x1010107f, librdkafka built with 0x1010107f)
%7|1605365045.762|SSL|rdkafka#producer-1| [thrd:app]: Loading CA certificate(s) from file /path-to-my-cer.pem
%7|1605365045.763|WAKEUPFD|rdkafka#producer-1| [thrd:app]: sasl_ssl://my-broker-1:9094/bootstrap: Enabled low-latency ops queue wake-ups
%7|1605365045.763|BRKMAIN|rdkafka#producer-1| [thrd::0/internal]: :0/internal: Enter main broker thread
%7|1605365045.763|BROKER|rdkafka#producer-1| [thrd:app]: sasl_ssl://my-broker-1:9094/bootstrap: Added new broker with NodeId -1
%7|1605365045.763|BRKMAIN|rdkafka#producer-1| [thrd:sasl_ssl://my-broker-1:9094/bootstrap]: sasl_ssl://my-broker-1:9094/bootstrap: Enter main broker thread
%7|1605365045.763|CONNECT|rdkafka#producer-1| [thrd:app]: sasl_ssl://my-broker-1:9094/bootstrap: Selected for cluster connection: bootstrap servers added (broker has 0 connection attempt(s))
%7|1605365045.763|CONNECT|rdkafka#producer-1| [thrd:sasl_ssl://my-broker-1:9094/bootstrap]: sasl_ssl://my-broker-1:9094/bootstrap: Received CONNECT op
%7|1605365045.763|STATE|rdkafka#producer-1| [thrd:sasl_ssl://my-broker-1:9094/bootstrap]: sasl_ssl://my-broker-1:9094/bootstrap: Broker changed state INIT -> TRY_CONNECT
%7|1605365045.763|BROADCAST|rdkafka#producer-1| [thrd:sasl_ssl://my-broker-1:9094/bootstrap]: Broadcasting state change
%7|1605365045.763|INIT|rdkafka#producer-1| [thrd:app]: librdkafka v1.5.0 (0x10500ff) rdkafka#producer-1 initialized (builtin.features gzip,snappy,ssl,sasl,regex,lz4,sasl_gssapi,sasl_plain,sasl_scram,plugins,zstd,sasl_oauthbearer, CC CXX PKGCONFIG OSXLD LIBDL PLUGINS ZLIB SSL SASL_CYRUS ZSTD HDRHISTOGRAM LZ4_EXT SYSLOG SNAPPY SOCKEM SASL_SCRAM SASL_OAUTHBEARER CRC32C_HW, debug 0xfffff)
%7|1605365045.763|CONNECT|rdkafka#producer-1| [thrd:app]: Not selecting any broker for cluster connection: still suppressed for 49ms: application metadata request
%7|1605365046.763|CONNECT|rdkafka#producer-1| [thrd:main]: Cluster connection already in progress: no cluster connection
%7|1605365047.763|CONNECT|rdkafka#producer-1| [thrd:main]: Cluster connection already in progress: no cluster connection
%7|1605365048.763|CONNECT|rdkafka#producer-1| [thrd:main]: Cluster connection already in progress: no cluster connection
%7|1605365049.764|CONNECT|rdkafka#producer-1| [thrd:main]: Cluster connection already in progress: no cluster connection
%7|1605365050.766|CONNECT|rdkafka#producer-1| [thrd:main]: Cluster connection already in progress: no cluster connection
%7|1605365050.766|CONNECT|rdkafka#producer-1| [thrd:app]: Not selecting any broker for cluster connection: still suppressed for 49ms: application metadata request
% ERROR: Failed to acquire metadata: Local: Broker transport failure
</code></pre>
<h2>Notes:</h2>
<ul>
<li>this kafka cluster has 3 different listeners
<ul>
<li>port 9092 PLAINTEXT protocol (tried kafkacat and it works)</li>
<li>port 9093 SSL protocol (tried kafkacat and it works)</li>
<li>port 9094 SASL_SSL protocol with OAUTHBEARER as sasl mechanism</li>
</ul>
</li>
<li>I have installed <code>librdkafka</code> and <code>kafkacat</code> using <code>brew</code> on my Mac and as fas as I can see version of librdkafka is <code>1.5.0</code></li>
</ul>
<h1>Question</h1>
<ol>
<li><p>Why is my callback <code>oauth_refresh</code> never called (no <code>============== Initializing oauthbearer config</code>... printed on <code>stdout</code>)</p>
</li>
<li><p>Why do I get an error <code>No such configuration property: "plugin.library.paths" (plugin lib-oauth-cb.so)</code> if there is some <code>printf</code> after <code>rd_kafka_conf_set_oauthbearer_token_refresh_cb</code></p>
<ul>
<li>There won't be this error as long as <code>rd_kafka_conf_set_oauthbearer_token_refresh_cb</code> is called after <code>printf</code></li>
<li>Even multiple times setting does not result in this error:
<ul>
<li><code>printf</code></li>
<li><code>rd_kafka_conf_set_oauthbearer_token_refresh_cb</code></li>
<li><code>printf</code></li>
<li><code>rd_kafka_conf_set_oauthbearer_token_refresh_cb</code></li>
</ul>
</li>
<li>What is the side effect of <code>printf</code> to cause this error?</li>
<li>This part of question is less important, because I don't plan to keep those printf-s, part <code>1)</code> matters</li>
</ul>
</li>
</ol>
<h2>Goal</h2>
<ul>
<li>My goal is to have small pluggable lib of our OAUTHBEARER scheme which can be plugged in into anything which uses <code>librdkafka</code> (end goal is <a href="https://clickhouse.tech/docs/en/engines/table-engines/integrations/kafka/" rel="nofollow noreferrer">Clickhouse</a>'s kafka connector)</li>
<li>I used <code>kafkacat</code> just because it's easy tool to experiment with</li>
<li>Key point is plugability so that there is no need to recompile some app which uses librdkafka just to be able to use custom refresh oauth token logic.</li>
</ul>
<h1>Edit</h1>
<p>I've had several issues:</p>
<ul>
<li>signature of conf_init:
<ul>
<li>needs to be: <code>rd_kafka_resp_err_t conf_init(rd_kafka_conf_t *conf, const char *path, char *errstr, size_t errstr_size)</code></li>
<li>instead of: <code>void conf_init(rd_kafka_conf_t *conf, const char *path, char *errstr, size_t errstr_size)</code></li>
</ul>
</li>
<li>when setting oauthbearer token, expiry needs to be <code>nowMs + someTTL</code> instead <code>0</code> in my example</li>
<li>I ended up using <a href="https://github.com/edenhill/librdkafka/blob/master/examples/rdkafka_example.c" rel="nofollow noreferrer">rdkafka_example.c</a> instead of installed <code>kafkacat</code> since latest version of kafka cat that i installed with <code>brew</code> was <code>1.5.0</code>
<ul>
<li>when running against this older <code>kafkacat</code> I was getting following error <code>kafkacat(76875,0x11b279dc0) malloc: *** error for object 0x10bad7bd0: pointer being freed was not allocated kafkacat(76875,0x11b279dc0) malloc: *** set a breakpoint in malloc_error_break to debug </code></li>
</ul>
</li>
<li>I got it to work say in consumer mode <code>-C</code> but not in print metadata mode <code>-L</code> because with <code>-L</code> mode does not call <code>rd_kafka_poll</code> so my callback was never called.
<ul>
<li>I ended up adding <code>rd_kafka_poll(rk, 5000);</code> in <a href="https://github.com/edenhill/librdkafka/blob/master/examples/rdkafka_example.c" rel="nofollow noreferrer">rdkafka_example.c</a> when <code>-L</code> switch is enabled</li>
</ul>
</li>
</ul>
| 3 | 3,770 |
How many months someone was there in that year in Pandas?
|
<p>We consider this dataframe which represents contracts of workers. I would like to list how many months a worker worked for a certain year.</p>
<pre><code>df = pd.DataFrame{'id': {0: 19019,
1: 17160, 2: 21593, 3: 3146, 4: 21593, 5: 3146, 6: 22737, 7: 25311, 8: 25740,
9: 3289, 10: 26312, 11: 28028, 12: 17017, 13: 27742, 14: 26884,
15: 31174, 16: 31889, 17: 33319, 18: 35178, 19: 35464},
'start_date': {0: Timestamp('2016-06-01 00:00:00'),
1: Timestamp('2016-09-01 00:00:00'), 2: Timestamp('2016-11-01 00:00:00'),
3: Timestamp('2017-01-01 00:00:00'), 4: Timestamp('2017-03-01 00:00:00'),
5: Timestamp('2017-08-01 00:00:00'), 6: Timestamp('2018-09-01 00:00:00'),
7: Timestamp('2018-09-01 00:00:00'),8: Timestamp('2018-10-01 00:00:00'),
9: Timestamp('1999-11-01 00:00:00'),10: Timestamp('2018-10-01 00:00:00'),
11: Timestamp('2019-01-01 00:00:00'),12: Timestamp('2009-11-01 00:00:00'),
13: Timestamp('2019-09-01 00:00:00'),14: Timestamp('2020-03-01 00:00:00'),
15: Timestamp('2020-03-01 00:00:00'),16: Timestamp('2020-04-14 00:00:00'),
17: Timestamp('2020-10-01 00:00:00'),18: Timestamp('2021-03-01 00:00:00'),
19: Timestamp('2021-03-08 00:00:00')},
'end_date': {0: Timestamp('2017-01-31 00:00:00'),
1: Timestamp('2018-07-31 00:00:00'),2: Timestamp('2017-02-28 00:00:00'),
3: Timestamp('2017-07-31 00:00:00'),4: Timestamp('2017-12-31 00:00:00'),
5: Timestamp('2017-12-31 00:00:00'),6: Timestamp('2021-12-31 00:00:00'),
7: Timestamp('2019-08-16 00:00:00'),8: Timestamp('2019-11-30 00:00:00'),
9: Timestamp('2022-12-31 00:00:00'),10: Timestamp('2020-09-30 00:00:00'),
11: Timestamp('2021-02-28 00:00:00'),12: Timestamp('2022-10-31 00:00:00'),
13: Timestamp('2022-02-28 00:00:00'),14: Timestamp('2022-02-28 00:00:00'),
15: Timestamp('2022-02-28 00:00:00'),16: Timestamp('2021-06-30 00:00:00'),
17: Timestamp('2022-09-30 00:00:00'),18: Timestamp('2022-02-28 00:00:00'),
19: Timestamp('2022-03-07 00:00:00')}})
</code></pre>
<p>So if we consider 2020:</p>
<pre><code>year = 2020
after = df.index[df.start_date.dt.year >= year] # Started late in that year
before = df.index[df.end_date.dt.year <= year] # Left early in that year
df['after'] = df.iloc[after].start_date.dt.month
df['before'] = df.iloc[before].end_date.dt.month
df = df.fillna(0)
df['months'] = 12
df['months'] -= df['after']
df[df.before > 0]['months'] -= 12 - df['before']
df = df.drop(['before', 'after'], axis=1)
dm = df[(df.start_date.dt.year <= year) & (df.end_date.dt.year >= year)]
dm
</code></pre>
<p>I get the list of workers that worked in 2020 for n months:</p>
<pre><code> id start_date end_date months
13 22737 2018-09-01 2021-12-31 12.0
16 3289 1999-11-01 2022-12-31 12.0
17 26312 2018-10-01 2020-09-30 12.0
18 28028 2019-01-01 2021-02-28 12.0
19 17017 2009-11-01 2022-10-31 12.0
20 27742 2019-09-01 2022-02-28 12.0
21 26884 2020-03-01 2022-02-28 9.0
22 31174 2020-03-01 2022-02-28 9.0
23 31889 2020-04-14 2021-06-30 8.0
24 33319 2020-10-01 2022-09-30 2.0
</code></pre>
<p>Is there a better <em>pandaish</em> method to achieve the same?</p>
<p>(feel free to rename the question, I am sure it is terribly named)</p>
| 3 | 1,545 |
VS2019 not properly importing Qt Designer project
|
<p>I have looked everywhere for a solution to this, but I cannot find one. In VS2019, I have the Qt tools extension installed, and I have exported the C++ header file from Qt Designer including my project.
I then created a .pro file including:</p>
<pre><code>QT += widgets
QT += uitools
HEADERS += ui_xinterface.h
FORMS += xinterface.ui
SOURCES += main.cpp
</code></pre>
<p>I then imported this into VS2019, which created a project automatically. I then added this function to main.cpp, as per <a href="https://doc.qt.io/qt-5/designer-using-a-ui-file.html#the-uitools-approach" rel="nofollow noreferrer">this example</a> (note: main.cpp is originally an empty file):</p>
<pre><code>#include <QtUiTools>
#include "ui_xinterface.h"
static QWidget* loadUiFile(QWidget* parent)
{
QFile file(":/forms/xinterface.ui");
file.open(QIODevice::ReadOnly);
QUiLoader loader;
return loader.load(&file, parent);
}
</code></pre>
<p>This didn't build:</p>
<pre><code>Build started...
1>------ Build started: Project: ui_interface, Configuration: Debug x64 ------
1>main.cpp
1>Qt6EntryPointd.lib(qtentrypoint_win.cpp.obj) : error LNK2019: unresolved external symbol main referenced in function WinMain
1>debug\\ui_interface.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "ui_interface.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code></pre>
<p>And gave 9 errors:</p>
<pre><code>Severity Code Description Project File Line Suppression State
Error LNK1120 1 unresolved externals ui_interface C:\Users\User\Documents\EE\basic-app\debug\ui_interface.exe 1
Error LNK2019 unresolved external symbol main referenced in function WinMain ui_interface C:\Users\User\Documents\EE\basic-app\Qt6EntryPointd.lib(qtentrypoint_win.cpp.obj) 1
Error (active) E2422 defaulted default constructor cannot be constexpr because the corresponding implicitly declared default constructor would not be constexpr ui_interface C:\Qt\6.2.0\msvc2019_64\include\QtCore\qmetatype.h 444
Error (active) E0028 expression must have a constant value ui_interface C:\Qt\6.2.0\msvc2019_64\include\QtCore\qmetatype.h 2181
Error (active) E0028 expression must have a constant value ui_interface C:\Qt\6.2.0\msvc2019_64\include\QtCore\qmetatype.h 2261
Error (active) E2422 defaulted default constructor cannot be constexpr because the corresponding implicitly declared default constructor would not be constexpr ui_interface C:\Qt\6.2.0\msvc2019_64\include\QtCore\qmutex.h 150
Error (active) E2422 defaulted default constructor cannot be constexpr because the corresponding implicitly declared default constructor would not be constexpr ui_interface C:\Qt\6.2.0\msvc2019_64\include\QtCore\qmutex.h 205
Error (active) E2422 defaulted default constructor cannot be constexpr because the corresponding implicitly declared default constructor would not be constexpr ui_interface C:\Qt\6.2.0\msvc2019_64\include\QtCore\qproperty.h 255
Error (active) E2422 defaulted default constructor cannot be constexpr because the corresponding implicitly declared default constructor would not be constexpr ui_interface C:\Qt\6.2.0\msvc2019_64\include\QtCore\qrunnable.h 56*
</code></pre>
<p>These seem like linker errors but I have no idea how to fix them. The additional libraries [$(Qt_INCLUDEPATH_)] and directories [$(Qt_LIBPATH_)] seems to be linked automatically in project properties. I'm quite new to this, what am I missing?</p>
| 3 | 1,218 |
Python recursive function not returning
|
<p>I am trying to write a recursive function that returns the position of a word in a sorted word list, or return <code>None</code> when the word is not found. The following is the code:</p>
<pre><code>def partition(t,kw,upper,lower):
if ((upper-lower) > 1):
pivot = lower + (upper-lower)//2
print("pivot is now {}".format(pivot))
if (kw >= t[pivot]):
lower = pivot
print("searching on the right",upper,lower)
return(partition(t,kw,upper,lower))
elif (kw <= t[pivot-1]):
upper = pivot-1
print("searching on the left",upper,lower)
return(partition(t,kw,upper,lower))
else:
return None
#that means the keyword is between t[pivot-1] and t[pivot]
#which means it doesnt exist in the list
if (upper - lower) <= 1:
if (kw == t[upper]):
print("found element {} at upper bound {}".format(kw,upper))
return(upper)
elif (kw == t[lower]):
print("found element {} at lower bound {}".format(kw,lower))
return(lower)
else:
return None
def search(t, kw):
u = len(t)
partition(t,kw,u,0)
</code></pre>
<p>As you can see I returned the function whenever I called it(not returning is a common mistake in using recursive calls). At the same time, here's the sample array I was using:</p>
<pre><code>['', '', '150', '150', '1997,with', '36', '49', 'An', 'Annotated', 'Annotation', 'Bibliography', 'China', 'Chinese', 'Chinese', 'Classical', 'During', 'Dynasty', 'Hong', 'Hong', 'Hong', 'Hong', 'Hong', 'In', 'It', 'Kong', 'Kong', 'Kong', 'Kong,', 'Kong.', 'Mainland', 'Poets', 'Qing', 'They', 'Together,', 'Writings', 'a', 'a', 'a', 'a', 'a', 'active', 'activity,', 'addition', 'almost', 'and', 'and', 'and', 'and', 'and', 'and', 'annotations', 'anthologies', 'basic', 'been', 'before.', 'bibliographic', 'bibliographies,', 'by', 'carry', 'ci-poetry', 'ci-poetry', 'classical', 'collected', 'commentaries', 'compilation,', 'compilations', 'compiled', 'covered,', 'development', 'events', 'focused', 'form', 'form', 'formation,', 'from', 'from', 'has', 'help', 'hidden', 'in', 'in', 'in', 'in', 'includes', 'individual', 'information', 'information', 'introduces', 'invaluable', 'is', 'late', 'literary', 'literati', 'literature', 'literature.', 'membership,', 'most', 'never', 'not', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'offer', 'on', 'on', 'on', 'on', 'order', 'over', 'past', 'periods', 'pioneer', 'pity', 'poetic', 'poetry', 'poetry', 'poetry', 'poet’s', 'political', 'previous', 'previously', 'published', 'refuge', 'research', 'sequel', 'shi-', 'shi-', 'societies', 'societies', 'societies', 'societies.', 'societies.', 'splendor,', 'that', 'that', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'these', 'these', 'these', 'this', 'times', 'to', 'to', 'to', 'to', 'to', 'to', 'took', 'tools', 'topic', 'tradition.', 'turmoil', 'two', 'uncover', 'understand', 'understanding', 'unique', 'up', 'various', 'very', 'volume,', 'which', 'works,', 'worthwhile', 'would', 'years,']
</code></pre>
<p>I was searching for the word <code>"Qing"</code>, it should end up in the 31st position.
Right now it seems like the function could find the word I need, but couldn't return:</p>
<pre><code>the result is
pivot is now 92
searching on the left 91 0
pivot is now 45
searching on the left 44 0
pivot is now 22
searching on the right 44 22
pivot is now 33
searching on the left 32 22
pivot is now 27
searching on the right 32 27
pivot is now 29
searching on the right 32 29
pivot is now 30
searching on the right 32 30
pivot is now 31
searching on the right 32 31
found element Qing at lower bound 31
None
</code></pre>
<p>I tried searching for issues relating to recursive functions but didn't seem much related content. Most posts on SO are caused by not returning the recursive function, and I am really not sure what's wrong in here.</p>
| 3 | 1,573 |
Why when I modify a linked list inside a function am I getting a segmentation fault?
|
<p>I have written a helper function that was designed to add a node to a linked list. The location this was to be done with the following segment.</p>
<pre><code>tcb_add(running,temp);
</code></pre>
<p>This segment is supposed to add temp to running. Here is my code for the function.</p>
<pre><code>void tcb_add(tcb_t *first, tcb_t *second) { //fix
if (first == NULL) {
first = second;
} else {
while (first->next != NULL) {
first = first->next;
}
first->next = second;
}
}
</code></pre>
<p>If instead of using the line <code>tcb_add(running,temp);</code> I just say <code>running = temp</code> it works. But for other parts of my code, I would like to have the function since it was only that easy since <code>temp</code> was the first node being added. Any help would be very appreciated.</p>
<p>There is, of course, more code but I believe I isolated the problem.</p>
<p>Here is the output from Valgrind when I call <code>tcb_add(running,temp);</code>, but keep in mind when I instead say <code>running = temp</code> the segment works.</p>
<pre><code>==30628== Memcheck, a memory error detector
==30628== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==30628== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==30628== Command: ./test00
==30628==
==30628== Invalid read of size 8
==30628== at 0x400930: t_create (t_lib.c:42)
==30628== by 0x4007F9: main (test00.c:25)
==30628== Address 0x8 is not stack'd, malloc'd or (recently) free'd
==30628==
==30628==
==30628== Process terminating with default action of signal 11 (SIGSEGV)
==30628== Access not within mapped region at address 0x8
==30628== at 0x400930: t_create (t_lib.c:42)
==30628== by 0x4007F9: main (test00.c:25)
==30628== If you believe this happened as a result of a stack
==30628== overflow in your program's main thread (unlikely but
==30628== possible), you can try to increase the size of the
==30628== main thread stack using the --main-stacksize= flag.
==30628== The main thread stack size used in this run was 8388608.
==30628==
==30628== HEAP SUMMARY:
==30628== in use at exit: 67,432 bytes in 4 blocks
==30628== total heap usage: 4 allocs, 0 frees, 67,432 bytes allocated
==30628==
==30628== LEAK SUMMARY:
==30628== definitely lost: 24 bytes in 1 blocks
==30628== indirectly lost: 936 bytes in 1 blocks
==30628== possibly lost: 0 bytes in 0 blocks
==30628== still reachable: 66,472 bytes in 2 blocks
==30628== suppressed: 0 bytes in 0 blocks
==30628== Rerun with --leak-check=full to see details of leaked memory
==30628==
==30628== For counts of detected and suppressed errors, rerun with: -v
==30628== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
</code></pre>
<h2>Edit</h2>
<p>The variable running is defined as follows:</p>
<pre><code>tcb_t *running;
tcb_t *ready;
</code></pre>
<p>This is according to the struct:</p>
<pre><code>struct tcb_t {
int thread_id;
int thread_priority;
ucontext_t *thread_context;
struct tcb_t *next;
}; typedef struct tcb_t tcb_t;
</code></pre>
<p>As asked this is my t_create function:</p>
<pre><code>int t_create(void (*fct)(int), int id, int pri) {
size_t sz = 0x10000;
ucontext_t *uc;
uc = (ucontext_t *)malloc(sizeof(ucontext_t));
getcontext(uc);
uc->uc_stack.ss_sp = malloc(sz); /* new statement */
uc->uc_stack.ss_size = sz;
uc->uc_stack.ss_flags = 0;
uc->uc_link = running->thread_context;
makecontext(uc, (void (*)(void))fct, 1, id);
tcb_t *new_tcb = malloc(sizeof(tcb_t));
new_tcb->thread_context = uc;
new_tcb->thread_id = id;
new_tcb->thread_priority = pri;
new_tcb->next = NULL;
tcb_t *tmp = ready;
if (tmp == NULL) // I would like to replace this portion with tcb_add()
ready = new_tcb;
else {
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new_tcb;// To here
}
</code></pre>
<p>Also to further explain although the valgrind report mentions t_create this is where I believed the problem took place.</p>
<pre><code>void t_init() {
tcb_t *temp = tcb_create();
temp->thread_context = (ucontext_t *) malloc(sizeof(ucontext_t));
temp->thread_id = 0;
temp->thread_priority = 0;
temp->next = NULL;
getcontext(temp->thread_context);
tcb_add(running,temp); //DOES NOT WORK
//running = temp; //WORKS
ready = NULL;
}
</code></pre>
| 3 | 1,722 |
How do i make center email content is visible
|
<p>I am trying to create HTML email page where there should be fixed header,center and footer. I am facing difficulty to see center content to make center content is visible i have added so much br tag after navbar div. how do avoid this. How do i reduce distance between support.html line to All rights reserved How do i reduce header and footer height. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code> * {
font-family: 'Ubuntu';
font-size: 18px;
}
.footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
background-color: #3498DB;
color: white;
text-align: center;
}
.flex-container {
display: flex;
align-items: center;
justify-content: center;
}
p {
padding: 10px;
}
img {
padding-right: 5px;
}
.navbar {
position: fixed;
right: 0;
top: 0;
width: 100%;
background-color: #3498DB;
color: white;
text-align: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="navbar">
<h1><span><img width="30" height="30" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAdVBMVEX///8AAABLS0ujo6OWlpba2trQ0ND8/Pz39/fz8/P4+PhPT0/s7OzU1NQ7Ozvj4+OysrLExMRCQkISEhJpaWkmJiaDg4M1NTV7e3sZGRlZWVlgYGC9vb0aGhqIiIgqKiqbm5siIiJ1dXVoaGheXl6Ojo6pqamU9iTBAAAEaklEQVR4nO3c61riMBSF4XDQIooKHkB0EHX0/i9xZMQhK80JaPbO+Kzv30iH9FVoS9tgDGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGPsx/YxrKePIsJZr55mRYR9bZZVn0IKKVSPQgop3DY9kepqoCPsnRUZx9NE6W8oRmwBBd+HIsQ2UHJLMyoyFHTiGVZQeFOc6AOK7i1KE73A4sJbe7CHcZHRtvmBxYVmaY/2qyARgUM5oTm3B35pioxnXODKCApliC5QVIjbnbsiRATeG2EhEp8LjHfVAgoL8dxb90QPUFqIxHnHo/mA4kJzWY6IwMX2p+JCJF52OJYfqCAsRQwANYRmbq9KV+faEfi6e0BDWIIYBOoIzXPXxDBQSdgA8fihL8JAJaFp7rokxoBaQtO82Ct1ftQgCLx1HtUSmuZXV8Q4UE9oxg/2ii0PHiIBVBR2REwBNYVmdGOv3O+DBkDgm2cJTaEZweo9HvD8aaCu0JwdScwAKgsdon8Vw2X9gpSFzkp6NhSR8l4B2sIjiPg/gxsqdWH8kCtSJrAC4YFEBEb2phUIDyJmA6sQOsRFbNFtuCeNHg9VIdybiEdD8QO+OoT+M53BEJj4XFKJcC/iXsBqhA5xFVlyP2A9wmzieD9gRUKH+B5YCj9VZqx1RUKzyCCO4eRHzrNWJHzvYUPPMnh2J+vwoB7hsOfWJuIZuk3pfWc1wjaw11s7y7SB6X1nNcK1B+gSfcD4jmVTJUL3XtDvBtYyeJ58V2iru60O4UcAaBNDQP8maVcVwmtYYeR+E0d4MQeWWceevAYhAifmFP7dn44+jwbwfXrpHB4MIs9egfAJVvb08ydIbLe5NI63BkXmpekL20BjplHg1x0cSLwOPr+6EDFT7099QPdG5yBRW+gHxoi7e3DwxfwUGEFZGF5JfPH6gJlEXWFsFf1EvIsq9AqwUxXG30m+m5ndc+IZRE1halPR4AdGL8G3JcYUhRl7tIt7a4mZd3OZJOoJERg8KpkMFstZ/231FJpq4x4RuakJ8bBrfcQYeBx74j6sJURg/NNBqjhRSdgl0P10eYUP6gjxOkXiI2xG+MkDiSpCBKZOQ+SEZ3mAqCFEYPJUUlZ4KvLCekRBiBc3c64W5rQKEeWFCMy/bp/qHp53t/cUF+LV2+6A7kWBf0RpIV452u/+mVSvQPyexSksbODK0b73QKWCWZw32ymOskI8a33IrXrx3uynf/iaHCcqxBvYD79pNtyjPcDXFEdRYXGgwbm4fyfHSQphIslxN6+HA+LmnIegEOY7lRluE8zFnUsKYeZhmW8Wc8fsbU6PiwmXOG7J4He5G1fyOxXKAp33g4aw68mx7ea+YeWEJeZwuz17xhUTlpmH7+S7YCwlLPd1EZDnrgYhochfcFP7ryj1XV+TU5kmretz/L42CinUj0IKKdSvjPDnf5/39aCewjeGMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcb++/4A3qE/10C+aHIAAAAASUVORK5CYII=" alt="Error"></span></h1>
<p> A abcd abcde abcdabcd abc abcde abcdefgh </p>
</div>
<br><br><br><br><br><br><br><br>
<h2 style="text-align: center;">Invitation to join Project ((ProjectName))</h2><br>
((InviterFirstName)) ((InviterLastName)) has invited you as ((ProjectRole)) to the following project.<br>
Project Name: ((ProjectName))<br>
Project Number: ((ProjectNumber))<br><br><br>
Team HTML
<div class="footer">
<div class="flex-container">
<p style="text-align:left;"><span><img width="30" height="30" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAdVBMVEX///8AAABLS0ujo6OWlpba2trQ0ND8/Pz39/fz8/P4+PhPT0/s7OzU1NQ7Ozvj4+OysrLExMRCQkISEhJpaWkmJiaDg4M1NTV7e3sZGRlZWVlgYGC9vb0aGhqIiIgqKiqbm5siIiJ1dXVoaGheXl6Ojo6pqamU9iTBAAAEaklEQVR4nO3c61riMBSF4XDQIooKHkB0EHX0/i9xZMQhK80JaPbO+Kzv30iH9FVoS9tgDGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGPsx/YxrKePIsJZr55mRYR9bZZVn0IKKVSPQgop3DY9kepqoCPsnRUZx9NE6W8oRmwBBd+HIsQ2UHJLMyoyFHTiGVZQeFOc6AOK7i1KE73A4sJbe7CHcZHRtvmBxYVmaY/2qyARgUM5oTm3B35pioxnXODKCApliC5QVIjbnbsiRATeG2EhEp8LjHfVAgoL8dxb90QPUFqIxHnHo/mA4kJzWY6IwMX2p+JCJF52OJYfqCAsRQwANYRmbq9KV+faEfi6e0BDWIIYBOoIzXPXxDBQSdgA8fihL8JAJaFp7rokxoBaQtO82Ct1ftQgCLx1HtUSmuZXV8Q4UE9oxg/2ii0PHiIBVBR2REwBNYVmdGOv3O+DBkDgm2cJTaEZweo9HvD8aaCu0JwdScwAKgsdon8Vw2X9gpSFzkp6NhSR8l4B2sIjiPg/gxsqdWH8kCtSJrAC4YFEBEb2phUIDyJmA6sQOsRFbNFtuCeNHg9VIdybiEdD8QO+OoT+M53BEJj4XFKJcC/iXsBqhA5xFVlyP2A9wmzieD9gRUKH+B5YCj9VZqx1RUKzyCCO4eRHzrNWJHzvYUPPMnh2J+vwoB7hsOfWJuIZuk3pfWc1wjaw11s7y7SB6X1nNcK1B+gSfcD4jmVTJUL3XtDvBtYyeJ58V2iru60O4UcAaBNDQP8maVcVwmtYYeR+E0d4MQeWWceevAYhAifmFP7dn44+jwbwfXrpHB4MIs9egfAJVvb08ydIbLe5NI63BkXmpekL20BjplHg1x0cSLwOPr+6EDFT7099QPdG5yBRW+gHxoi7e3DwxfwUGEFZGF5JfPH6gJlEXWFsFf1EvIsq9AqwUxXG30m+m5ndc+IZRE1halPR4AdGL8G3JcYUhRl7tIt7a4mZd3OZJOoJERg8KpkMFstZ/231FJpq4x4RuakJ8bBrfcQYeBx74j6sJURg/NNBqjhRSdgl0P10eYUP6gjxOkXiI2xG+MkDiSpCBKZOQ+SEZ3mAqCFEYPJUUlZ4KvLCekRBiBc3c64W5rQKEeWFCMy/bp/qHp53t/cUF+LV2+6A7kWBf0RpIV452u/+mVSvQPyexSksbODK0b73QKWCWZw32ymOskI8a33IrXrx3uynf/iaHCcqxBvYD79pNtyjPcDXFEdRYXGgwbm4fyfHSQphIslxN6+HA+LmnIegEOY7lRluE8zFnUsKYeZhmW8Wc8fsbU6PiwmXOG7J4He5G1fyOxXKAp33g4aw68mx7ea+YeWEJeZwuz17xhUTlpmH7+S7YCwlLPd1EZDnrgYhochfcFP7ryj1XV+TU5kmretz/L42CinUj0IKKdSvjPDnf5/39aCewjeGMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcb++/4A3qE/10C+aHIAAAAASUVORK5CYII=" alt="Error"></span><a href="mailto:support@html.com" style="color:white;">support@html.com</a></p>
<p style="text-align:right;"><span><img width="30" height="30" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAdVBMVEX///8AAABLS0ujo6OWlpba2trQ0ND8/Pz39/fz8/P4+PhPT0/s7OzU1NQ7Ozvj4+OysrLExMRCQkISEhJpaWkmJiaDg4M1NTV7e3sZGRlZWVlgYGC9vb0aGhqIiIgqKiqbm5siIiJ1dXVoaGheXl6Ojo6pqamU9iTBAAAEaklEQVR4nO3c61riMBSF4XDQIooKHkB0EHX0/i9xZMQhK80JaPbO+Kzv30iH9FVoS9tgDGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGPsx/YxrKePIsJZr55mRYR9bZZVn0IKKVSPQgop3DY9kepqoCPsnRUZx9NE6W8oRmwBBd+HIsQ2UHJLMyoyFHTiGVZQeFOc6AOK7i1KE73A4sJbe7CHcZHRtvmBxYVmaY/2qyARgUM5oTm3B35pioxnXODKCApliC5QVIjbnbsiRATeG2EhEp8LjHfVAgoL8dxb90QPUFqIxHnHo/mA4kJzWY6IwMX2p+JCJF52OJYfqCAsRQwANYRmbq9KV+faEfi6e0BDWIIYBOoIzXPXxDBQSdgA8fihL8JAJaFp7rokxoBaQtO82Ct1ftQgCLx1HtUSmuZXV8Q4UE9oxg/2ii0PHiIBVBR2REwBNYVmdGOv3O+DBkDgm2cJTaEZweo9HvD8aaCu0JwdScwAKgsdon8Vw2X9gpSFzkp6NhSR8l4B2sIjiPg/gxsqdWH8kCtSJrAC4YFEBEb2phUIDyJmA6sQOsRFbNFtuCeNHg9VIdybiEdD8QO+OoT+M53BEJj4XFKJcC/iXsBqhA5xFVlyP2A9wmzieD9gRUKH+B5YCj9VZqx1RUKzyCCO4eRHzrNWJHzvYUPPMnh2J+vwoB7hsOfWJuIZuk3pfWc1wjaw11s7y7SB6X1nNcK1B+gSfcD4jmVTJUL3XtDvBtYyeJ58V2iru60O4UcAaBNDQP8maVcVwmtYYeR+E0d4MQeWWceevAYhAifmFP7dn44+jwbwfXrpHB4MIs9egfAJVvb08ydIbLe5NI63BkXmpekL20BjplHg1x0cSLwOPr+6EDFT7099QPdG5yBRW+gHxoi7e3DwxfwUGEFZGF5JfPH6gJlEXWFsFf1EvIsq9AqwUxXG30m+m5ndc+IZRE1halPR4AdGL8G3JcYUhRl7tIt7a4mZd3OZJOoJERg8KpkMFstZ/231FJpq4x4RuakJ8bBrfcQYeBx74j6sJURg/NNBqjhRSdgl0P10eYUP6gjxOkXiI2xG+MkDiSpCBKZOQ+SEZ3mAqCFEYPJUUlZ4KvLCekRBiBc3c64W5rQKEeWFCMy/bp/qHp53t/cUF+LV2+6A7kWBf0RpIV452u/+mVSvQPyexSksbODK0b73QKWCWZw32ymOskI8a33IrXrx3uynf/iaHCcqxBvYD79pNtyjPcDXFEdRYXGgwbm4fyfHSQphIslxN6+HA+LmnIegEOY7lRluE8zFnUsKYeZhmW8Wc8fsbU6PiwmXOG7J4He5G1fyOxXKAp33g4aw68mx7ea+YeWEJeZwuz17xhUTlpmH7+S7YCwlLPd1EZDnrgYhochfcFP7ryj1XV+TU5kmretz/L42CinUj0IKKdSvjPDnf5/39aCewjeGMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcb++/4A3qE/10C+aHIAAAAASUVORK5CYII=" alt="Error"></span>175B ABC ABCD AB 95138</p>
</div>
<p>© 2020 All rights reserved</p>
</div></code></pre>
</div>
</div>
</p>
| 3 | 5,255 |
clickListener not initializing correctly
|
<p>Sorry I am very new to Java and LibGDX however I'm having a problem.</p>
<p>I have two buttons in my Pong game. If score1 or score2 equals 5, the game ends. This is done by making the ball and paddles move off screen then a method called drawButtonRematch and drawButtonMenu are initialized which draw the two buttons "REMATCH" and "MAIN MENU".</p>
<p>I'm not sure why, but the clickListener for the rematch button only works WHILE you play the game (not when score1 or score2 = 5).</p>
<p>In simpler terms, while you're playing the game (not when the score = 5) the rematch button is non existent but the clickListener is. If you click where the button should be, it makes the game rematch. So if the user were to accidentally click that area they would reset the game.</p>
<p>Here is an image visualization:</p>
<p><a href="http://imgur.com/a/n8F4l" rel="nofollow">http://imgur.com/a/n8F4l</a></p>
<p>Here is my code. This is the button causing problems.</p>
<pre><code>private void drawButtonRematch(float dt){
final Texture texture = new Texture(Gdx.files.internal("Assets/buttonRematch.png"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Stage stage = new Stage();
stage.clear();
Image buttonRematch = new Image(texture);
buttonRematch.setX(640-(buttonRematch.getWidth()/2));
buttonRematch.setY(120);
buttonRematch.setWidth(300);
buttonRematch.setHeight(100);
Gdx.input.setInputProcessor(stage);
buttonRematch.addListener(new ClickListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button)
{
currentState = GameState.RESET;
return true;
}
});
</code></pre>
<p>Here is the Main Menu button which does work. Literally the same as drawButtonRematch</p>
<pre><code> private void drawButtonMenu(float dt) {
final Texture texture = new Texture(Gdx.files.internal("Assets/buttonMenu.png"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Stage stage = new Stage();
stage.clear();
// Menu
Image mainMenu = new Image(texture);
mainMenu.setX(640-(mainMenu.getWidth()/2));
mainMenu.setY(10);
mainMenu.setWidth(300);
mainMenu.setHeight(100);
Gdx.input.setInputProcessor(stage);
mainMenu.addListener(new ClickListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button)
{
currentState = GameState.MENU;
return true;
}
});
stage.addActor(mainMenu);
stage.draw();
}
</code></pre>
<p>Then finally in my game logic I have </p>
<pre><code> if(score1 == 5){
drawWin(dt);
paddle1.move(-1000, -1000);
paddle2.move(-1000, -1000);
ball.setVelocity(0, 0);
ball.move(640, 50);
drawButtonRematch(dt);
drawButtonMenu(dt);
}
else if (score2 == 5){
drawWin2(dt);
paddle1.move(-1000, -1000);
paddle2.move(-1000, -1000);
ball.setVelocity(0, 0);
ball.move(640, 50);
drawButtonRematch(dt);
drawButtonMenu(dt);
}
</code></pre>
<p>I'm sorry if this is the worst code you have seen in your life, I only started with Java on 1st August! Thanks for any help.</p>
| 3 | 1,232 |
Place marker on map - GeoTools 25-SNAPSHOT - Java 11
|
<p>I am using geotools 25-SNAPSHOT in my application. I have displayed a map in my application (raster).
Now I want to place a marker (image or simple colored dot) on a map at a specific latitude, longitude location without refresh.</p>
<p>In the following code the marker is placed at mouse click but on <code>addLayer()</code> the map is reloaded which is inappropriate.</p>
<pre><code>import java.awt.Color;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JToolBar;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.coverage.grid.io.GridCoverage2DReader;
import org.geotools.coverage.grid.io.GridFormatFinder;
import org.geotools.data.DataUtilities;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.SchemaException;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.map.FeatureLayer;
import org.geotools.map.GridCoverageLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.styling.StyleBuilder;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.event.MapMouseEvent;
import org.geotools.swing.tool.CursorTool;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
public class Test {
/**
* GeoTools Quickstart demo application. Prompts the user for a shapefile and
* displays its contents on the screen in a map frame
*/
public static void main(String[] args) throws Exception {
try {
JMapFrame mapFrame;
File file = new File("mapfile.tif");
GridFormatFinder.scanForPlugins();
AbstractGridFormat format = GridFormatFinder.findFormat(file);
GridCoverage2DReader reader = format.getReader(file);
GridCoverage2D coverage = (GridCoverage2D) reader.read(null);
// Create a map content and add our shapefile to it
MapContent map = new MapContent();
map.setTitle("Marker test");
StyleBuilder sb = new StyleBuilder();
Style baseStyle = sb.createStyle(sb.createRasterSymbolizer());
map.addLayer(new GridCoverageLayer(coverage, baseStyle));
mapFrame = new JMapFrame(map);
mapFrame.enableToolBar(true);
mapFrame.enableStatusBar(true);
//ToolBar
JToolBar toolBar = mapFrame.getToolBar();
Icon icon = new ImageIcon("icon.png");
JButton btn = new JButton(icon);
btn.setToolTipText("Add mining manually");
toolBar.addSeparator();
toolBar.add(btn);
//Action on mouse click for adding marker
btn.addActionListener(e -> mapFrame.getMapPane().setCursorTool(new CursorTool() {
@Override
public void onMouseClicked(MapMouseEvent ev) {
try {
DirectPosition2D p = ev.getWorldPos();
System.out.println(p.getX() + " -- " + p.getY());
Layer layer = getLayerPointByCoord(new Coordinate(p.getX(), p.getY()));
map.addLayer(layer);
} catch (Exception e) {
e.printStackTrace();
}
}
}));
mapFrame.setTitle("Aeron GIS Utility");
mapFrame.setSize(2030,830);
mapFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
static Layer getLayerPointByCoord(Coordinate coords) throws SchemaException {
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
Point point = geometryFactory.createPoint(coords);
SimpleFeatureType TYPE = DataUtilities.createType("test", "point", "the_geom:Point");
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder((SimpleFeatureType) TYPE);
featureBuilder.add(point);
SimpleFeature feature = featureBuilder.buildFeature("LineString_Sample");
DefaultFeatureCollection lineCollection = new DefaultFeatureCollection();
lineCollection.add(feature);
Style style = SLD.createPointStyle("Circle", Color.BLACK, Color.RED, 1f, 15f);
return new FeatureLayer(lineCollection, style);
}
}
</code></pre>
| 3 | 2,094 |
Output of VGG Model becomes constant after training and Loss/Accuracy are not improving
|
<p>I'm trying to implement a slightly smaller version of VGG16 and train it from scratch on a dataset of about 6000 images (5400 for training and 600 for validation). I chose a batch size of 30 so that it can neatly fit within the dataset, otherwise I would get his with IncompatibleShape error during training.</p>
<p>After going through 15-20 epochs, the EarlyStopping callback kicks in and stops the training.</p>
<p>I'm facing two issues with this model</p>
<ol>
<li>After this, when I pass in test images into the model, the output
seems to remain constant. The least I expect is that for imageA,
predicted output should be different from imageB. I'm unable to figure out why this is the case</li>
<li>Loss and Accuracy seem not to change much. I was expecting that the accuracy would go up at least to about 50% for the number of epochs, but it does not go above 23%. I have tried to include steps_per_epoch, ReduceLROnPlateau but they doesn't seem make any dent.</li>
</ol>
<p>Training Output:</p>
<pre><code>Epoch 1/50
180/180 [==============================] - 50s 278ms/step - loss: 1.6095 - categorical_accuracy: 0.1987 - val_loss: 1.6109 - val_categorical_accuracy: 0.1267
Epoch 00001: val_loss improved from inf to 1.61094, saving model to vgg16.h5
Epoch 2/50
180/180 [==============================] - 51s 285ms/step - loss: 1.6095 - categorical_accuracy: 0.2044 - val_loss: 1.6107 - val_categorical_accuracy: 0.2133
Epoch 00002: val_loss improved from 1.61094 to 1.61067, saving model to vgg16.h5
Epoch 3/50
180/180 [==============================] - 51s 285ms/step - loss: 1.6098 - categorical_accuracy: 0.1946 - val_loss: 1.6106 - val_categorical_accuracy: 0.1400
Epoch 00003: val_loss improved from 1.61067 to 1.61059, saving model to vgg16.h5
Epoch 4/50
180/180 [==============================] - 52s 286ms/step - loss: 1.6095 - categorical_accuracy: 0.1928 - val_loss: 1.6098 - val_categorical_accuracy: 0.2000
Epoch 00004: val_loss improved from 1.61059 to 1.60983, saving model to vgg16.h5
Epoch 00004: ReduceLROnPlateau reducing learning rate to 2.5000001187436283e-05.
Epoch 5/50
180/180 [==============================] - 52s 286ms/step - loss: 1.6093 - categorical_accuracy: 0.2033 - val_loss: 1.6103 - val_categorical_accuracy: 0.1467
Epoch 00005: val_loss did not improve from 1.60983
Epoch 6/50
180/180 [==============================] - 51s 286ms/step - loss: 1.6094 - categorical_accuracy: 0.1989 - val_loss: 1.6106 - val_categorical_accuracy: 0.1400
Epoch 00006: val_loss did not improve from 1.60983
Epoch 7/50
180/180 [==============================] - 51s 286ms/step - loss: 1.6094 - categorical_accuracy: 0.2069 - val_loss: 1.6098 - val_categorical_accuracy: 0.1733
Epoch 00007: val_loss improved from 1.60983 to 1.60978, saving model to vgg16.h5
Epoch 00007: ReduceLROnPlateau reducing learning rate to 1e-05.
Epoch 8/50
180/180 [==============================] - 52s 286ms/step - loss: 1.6093 - categorical_accuracy: 0.2076 - val_loss: 1.6103 - val_categorical_accuracy: 0.1600
Epoch 00008: val_loss did not improve from 1.60978
Epoch 9/50
180/180 [==============================] - 51s 286ms/step - loss: 1.6095 - categorical_accuracy: 0.2006 - val_loss: 1.6097 - val_categorical_accuracy: 0.2200
Epoch 00009: val_loss improved from 1.60978 to 1.60975, saving model to vgg16.h5
Epoch 10/50
180/180 [==============================] - 52s 287ms/step - loss: 1.6095 - categorical_accuracy: 0.2043 - val_loss: 1.6101 - val_categorical_accuracy: 0.1667
Epoch 00010: val_loss did not improve from 1.60975
Epoch 11/50
180/180 [==============================] - 51s 286ms/step - loss: 1.6094 - categorical_accuracy: 0.2009 - val_loss: 1.6102 - val_categorical_accuracy: 0.1800
Epoch 00011: val_loss did not improve from 1.60975
Epoch 12/50
180/180 [==============================] - 51s 286ms/step - loss: 1.6095 - categorical_accuracy: 0.2041 - val_loss: 1.6115 - val_categorical_accuracy: 0.1600
Epoch 00012: val_loss did not improve from 1.60975
Epoch 13/50
180/180 [==============================] - 52s 286ms/step - loss: 1.6095 - categorical_accuracy: 0.1989 - val_loss: 1.6108 - val_categorical_accuracy: 0.1867
Epoch 00013: val_loss did not improve from 1.60975
Epoch 14/50
180/180 [==============================] - 52s 286ms/step - loss: 1.6094 - categorical_accuracy: 0.2009 - val_loss: 1.6102 - val_categorical_accuracy: 0.1733
Epoch 00014: val_loss did not improve from 1.60975
Epoch 15/50
180/180 [==============================] - 51s 286ms/step - loss: 1.6093 - categorical_accuracy: 0.2074 - val_loss: 1.6113 - val_categorical_accuracy: 0.1467
Epoch 00015: val_loss did not improve from 1.60975
Epoch 16/50
180/180 [==============================] - 52s 286ms/step - loss: 1.6098 - categorical_accuracy: 0.1983 - val_loss: 1.6105 - val_categorical_accuracy: 0.1867
Epoch 00016: val_loss did not improve from 1.60975
Epoch 17/50
180/180 [==============================] - 52s 286ms/step - loss: 1.6095 - categorical_accuracy: 0.2056 - val_loss: 1.6119 - val_categorical_accuracy: 0.1667
Epoch 00017: val_loss did not improve from 1.60975
Epoch 18/50
180/180 [==============================] - 52s 286ms/step - loss: 1.6093 - categorical_accuracy: 0.1994 - val_loss: 1.6110 - val_categorical_accuracy: 0.1800
Epoch 00018: val_loss did not improve from 1.60975
Epoch 19/50
180/180 [==============================] - 51s 286ms/step - loss: 1.6095 - categorical_accuracy: 0.2026 - val_loss: 1.6103 - val_categorical_accuracy: 0.1667
Epoch 00019: val_loss did not improve from 1.60975
Restoring model weights from the end of the best epoch.
Epoch 00019: early stopping
</code></pre>
<p>Code used to get Predictions:</p>
<pre><code>predictions = []
actuals=[]
for i, (images, labels) in enumerate( test_datasource):
if i > 2:
break
pred = model_2(images)
print(labels.shape, pred.shape)
for j in range(len(labels)):
actuals.append( labels[j])
predictions.append(pred[j])
print(labels[j].numpy(), "\t", pred[j].numpy())
</code></pre>
<p>Output of the above code:</p>
<pre><code>(30, 5) (30, 5)
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
(30, 5) (30, 5)
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
(30, 5) (30, 5)
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 0. 1.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[1. 0. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 1. 0. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 0. 1. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
[0. 0. 1. 0. 0.] [0.19907779 0.20320047 0.1968051 0.20173152 0.19918515]
</code></pre>
<p>Here is the model summary:</p>
<pre><code>Model: "vgg16"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_3 (InputLayer) [(30, 224, 224, 3)] 0
_________________________________________________________________
conv_1_1 (Conv2D) (30, 224, 224, 32) 896
_________________________________________________________________
conv_1_2 (Conv2D) (30, 224, 224, 32) 9248
_________________________________________________________________
maxpool_1 (MaxPooling2D) (30, 112, 112, 32) 0
_________________________________________________________________
conv_2_1 (Conv2D) (30, 112, 112, 64) 18496
_________________________________________________________________
conv_2_2 (Conv2D) (30, 112, 112, 64) 36928
_________________________________________________________________
maxpool_2 (MaxPooling2D) (30, 56, 56, 64) 0
_________________________________________________________________
conv_3_1 (Conv2D) (30, 56, 56, 128) 73856
_________________________________________________________________
conv_3_2 (Conv2D) (30, 56, 56, 128) 147584
_________________________________________________________________
conv_3_3 (Conv2D) (30, 56, 56, 128) 147584
_________________________________________________________________
maxpool_3 (MaxPooling2D) (30, 28, 28, 128) 0
_________________________________________________________________
conv_4_1 (Conv2D) (30, 28, 28, 256) 295168
_________________________________________________________________
conv_4_2 (Conv2D) (30, 28, 28, 256) 590080
_________________________________________________________________
conv_4_3 (Conv2D) (30, 28, 28, 256) 590080
_________________________________________________________________
maxpool_4 (MaxPooling2D) (30, 14, 14, 256) 0
_________________________________________________________________
conv_5_1 (Conv2D) (30, 14, 14, 256) 590080
_________________________________________________________________
conv_5_2 (Conv2D) (30, 14, 14, 256) 590080
_________________________________________________________________
conv_5_3 (Conv2D) (30, 14, 14, 256) 590080
_________________________________________________________________
maxpool_5 (MaxPooling2D) (30, 7, 7, 256) 0
_________________________________________________________________
flatten (Flatten) (30, 12544) 0
_________________________________________________________________
fc_1 (Dense) (30, 4096) 51384320
_________________________________________________________________
dropout_1 (Dropout) (30, 4096) 0
_________________________________________________________________
fc_2 (Dense) (30, 4096) 16781312
_________________________________________________________________
dropout_2 (Dropout) (30, 4096) 0
_________________________________________________________________
output (Dense) (30, 5) 20485
=================================================================
Total params: 71,866,277
Trainable params: 71,866,277
Non-trainable params: 0
</code></pre>
<p>The code is here in Google Colab: <a href="https://colab.research.google.com/drive/1AWe87Zb3MvF90j3RS7sv3OiSgR86q4j_" rel="nofollow noreferrer">https://colab.research.google.com/drive/1AWe87Zb3MvF90j3RS7sv3OiSgR86q4j_</a></p>
<p>I tried two versions of VGG-16, one with half the depth of filters than the original and the second with quarter of the depth of filters.</p>
| 3 | 7,647 |
The list in recyclerview is getting duplicated when navigating to other fragment with MVVM
|
<p>The list content in recyclerview is getting duplicated when navigating to other fragment and getting back to the fragment.</p>
<p>When a user clicks on item and navigate back to the same fragment the recyclerview is getting duplicated</p>
<p>ViewModel:</p>
<pre><code> private var listMutableLiveData: MutableLiveData<ArrayList<OffersModelClass>> =
MutableLiveData()
var arrayListMainUI: ArrayList<OffersModelClass> = ArrayList()
val listLiveData: LiveData<ArrayList<OffersModelClass>>
get() = listMutableLiveData
fun loadData(reload: Boolean) {
if (reload) {
databaseReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (data in snapshot.children) {
val model = data.getValue(OffersModelClass::class.java)
//Getting the offer ID to load its images
val imageID: String = model?.imageID.toString()
val fileRef11 = FirebaseStorage.getInstance().reference.child(
"offers/$imageID.jpg"
)
fileRef11.downloadUrl.addOnSuccessListener { uri ->
//Assigning the image uri and converting it to string
model?.ImageUri = uri.toString()
//Assigning the new time format
model?.Time = model?.Time?.let { calculateTimeAge(it) }
//Adding the data to arraylist as whole to observe it from the fragment
arrayListMainUI.add(model as OffersModelClass)
listMutableLiveData.postValue(arrayListMainUI)
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
</code></pre>
<p>Fragment:</p>
<pre><code> recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.setHasFixedSize(true)
viewModel = ViewModelProvider(requireActivity()).get(ViewModel::class.java)
if (user != null) {
// User is signed in
viewModel.loadData(true)
}
viewModel.listLiveData.observe(viewLifecycleOwner, { arrayList ->
offerAdapter = OfferAdapter(arrayList)
recyclerView.adapter = offerAdapter
offerAdapter.notifyDataSetChanged()
})
</code></pre>
| 3 | 1,167 |
Is there a technical reason why it would be better for the COM DLL to delete the passed in temporary JSON when it is finished with it?
|
<h2>Context</h2>
<ol>
<li><p>My parent MFC project creates a JSON file:</p>
<pre><code>CImportFromCLMExplorerDlg::CreateMSATranslationsJson(strTempJson);
</code></pre>
</li>
<li><p>This temporary file is passed into a C# COM DLL as a parameter for it to use:</p>
<pre><code>theApp.MSAToolsInterface().ImportHistoryFromCLMExplorer(
theApp.GetLanguageCode(dlgImportCLM.GetLanguageToImport()),
dlgImportCLM.GetCalendarDBPath(),
theApp.GetAssignHistoryXMLPath(),
strTempJson);
</code></pre>
</li>
<li><p>Finally, I delete the temporary file after the above COM DLL method returns:</p>
<pre><code>::DeleteFile(strTempJson);
</code></pre>
</li>
</ol>
<h2>My question</h2>
<p>It is technically a better approach to get the COM DLL to delete this file once it has finished using it? Or is it perfectly fine (it appears to be) to delete it after in the parent project?</p>
<p>I am not asking for opinions but asking if there is technical reason why it would be better for the COM DLL to delete the passed in temporary JSON when it is finished with it.</p>
<h2>The JSON File</h2>
<p>The comments allude to the possibility of using an <code>ISteam</code> and not passing a literal file. At the moment I am creating the JSON file like this:</p>
<pre><code>bool CImportFromCLMExplorerDlg::CreateMSATranslationsJson(const CString strPathJson)
{
CkString strOut, strValue;
CkJsonObject json;
bool success;
LanguageMSA eLang = theApp.GetProgramLanguage();
// Note: The methods return false if "out of memory"
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_BIBLE_READING));
success = json.AddStringAt(-1, "BibleReading", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_BIBLE_READING_MAIN));
success = json.AddStringAt(-1, "BibleReadingMain", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_BIBLE_READING_AUX));
success = json.AddStringAt(-1, "BibleReadingAux", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_INITIAL_CALL));
success = json.AddStringAt(-1, "InitialCall", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_INITIAL_CALL_MAIN));
success = json.AddStringAt(-1, "InitialCallMain", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_INITIAL_CALL_AUX));
success = json.AddStringAt(-1, "InitialCallAux", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_RETURN_VISIT));
success = json.AddStringAt(-1, "ReturnVisit", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_RETURN_MAIN));
success = json.AddStringAt(-1, "ReturnVisitMain", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_RETURN_AUX));
success = json.AddStringAt(-1, "ReturnVisitAux", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_BIBLE_STUDY));
success = json.AddStringAt(-1, "BibleStudy", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_STUDY_MAIN));
success = json.AddStringAt(-1, "BibleStudyMain", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_STUDY_AUX));
success = json.AddStringAt(-1, "BibleStudyAux", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_TALK));
success = json.AddStringAt(-1, "Talk", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_TALK_MAIN));
success = json.AddStringAt(-1, "TalkMain", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_TALK_AUX));
success = json.AddStringAt(-1, "TalkAux", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_HISTORY_ASSISTANT));
success = json.AddStringAt(-1, "Assistant", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_QA));
success = json.AddStringAt(-1, "QuestionsAndAnswers", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_DISC_VIDEO));
success = json.AddStringAt(-1, "DiscussionWithVideo", strValue);
success = json.AddStringAt(-1, "SampleConversation", "Sample Conversation");
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_INITIAL_CALL_VIDEO));
success = json.AddStringAt(-1, "InitialCallVideo", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_RETURN_VISIT_VIDEO));
success = json.AddStringAt(-1, "ReturnVisitVideo", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_CMB_METHOD_VIDEO));
success = json.AddStringAt(-1, "Video", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_THEME_PRESENTATIONS));
success = json.AddStringAt(-1, "Presentations", strValue);
strValue.setStringU(SMMETHOD3(eLang, IDS_STR_THEME_SPIRITUAL_GEMS));
success = json.AddStringAt(-1, "SpiritualGems", strValue);
json.put_EmitCompact(false);
strOut.append(json.emit());
strOut.append("\r\n");
CkString strPathJsonEx;
strPathJsonEx.setStringU(strPathJson);
return strOut.saveToFile(strPathJsonEx, "utf-8");
}
</code></pre>
<p>It uses the <a href="https://www.chilkatsoft.com/refdoc/vcCkJsonObjectRef.html" rel="nofollow noreferrer"><code>CkJsonObject</code></a> and <a href="https://www.chilkatsoft.com/refdoc/vcCkStringRef.html#method138" rel="nofollow noreferrer"><code>CkString</code></a> classes. I am not sure if it is possible to turn that into an object that can be passed to the DLL. For the record this is how I read in the JSON in the COM DLL at the moment:</p>
<pre><code>private MSATranslations GetMSATranslations(string strPath)
{
using (var reader = new StreamReader(strPath, Encoding.UTF8))
return JsonConvert.DeserializeObject<MSATranslations>(reader.ReadToEnd());
}
</code></pre>
| 3 | 2,484 |
nHibernate disables my log4net logs
|
<p>So, we had a little ETL app that had some issues with updates. Which were nicely solved in an afternoon sprint with nHibernate. But this app relied upon log4net to push logging output to a few different destinations based upon command line switches. Once we got nHibernate wrapped into the app, it ETL'd flawlessly. But the logging functions failed completely. From the debugger's point of view, any of our loggers have all log4net's levels disabled.</p>
<p>Here's the log4net config: </p>
<pre><code><log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="import-" />
<staticLogFileName value="false" />
<appendToFile value="false" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="5" />
<datePattern value="yyyyMMdd-HHmm&quot;.log&quot;" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level - %message%newline" />
</layout>
</appender>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level : %message%newline" />
</layout>
</appender>
<appender name="Email" type="log4net.Appender.SmtpAppender">
<to value="wwb@example.com" />
<from value="PeepsImporter@example.com" />
<subject value="Cte Importer Error" />
<smtpHost value="smtp.example.com" />
<bufferSize value="512" />
<lossy value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date %-5level : %message%newline%newline%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
</root>
<logger name="Console">
<level value="INFO" />
<appender-ref ref="Console" />
</logger>
<logger name="File">
<level value="INFO" />
<appender-ref ref="RollingFile" />
</logger>
<logger name="DebugConsole">
<level value="DEBUG" />
<appender-ref ref="Console" />
</logger>
<logger name="DebugFile">
<level value="DEBUG" />
<appender-ref ref="RollingFile" />
</logger>
<logger name="EmailErrors">
<level value="ERROR" />
<appender-ref ref="Email" />
</logger>
</log4net>
</code></pre>
<p>Not sure what other code would help, but I'm happy to post anything else from this app. </p>
| 3 | 1,107 |
SVG fill animation returns to initial state
|
<p>I'm using keyframes to change SVG path fill from visible to none-visible.</p>
<p>It working, but when animation ends the path return to his initial color (black), and I want it to remain white.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#secondletter {
animation-name: col;
animation-duration: 2s;
animation-timing-function: ease-in;
}
#thirdletter {
animation-name: col;
animation-duration: 2s;
animation-timing-function: ease-in-out;
}
#fourthletter {
animation-name: col;
animation-duration: 2s;
animation-timing-function: ease-in-out;
}
@keyframes col {
0% {fill:black}
100% {fill:#fff}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 1366 768" style="enable-background:new 0 0 1366 768;" xml:space="preserve">
<g>
<path d="M297,293l18.2,68.6c4.2,14.8,7.3,29.4,10.1,43.4h0.8c2.8-14,7.3-28.6,12-43.1l22.4-68.9H381l21,67.8
c4.8,15.7,9,30.2,12,44.2h0.8c2.2-14,5.9-28.3,10.4-44.2l19.3-67.8h24.4l-44,135.2h-22.4l-20.4-64.7c-4.8-15.1-8.7-28.6-12-44.5
h-0.6c-3.4,16.2-7.6,30.5-12.3,44.8l-21.8,64.4H313L272.1,293H297z"/>
<path id="secondletter" d="M507.3,365c0.6,33.3,21.6,47,46.5,47c17.6,0,28.6-3.1,37.5-7l4.2,17.6c-8.4,3.9-23.5,8.7-45.1,8.7
c-41.7,0-66.6-27.7-66.6-68.3c0-41.2,24.1-73.1,63.8-73.1c44,0,55.7,38.6,55.7,63.6c0,5-0.6,9-1.1,11.5H507.3z M579.5,347.3
c0.3-15.4-6.4-39.8-34.2-39.8c-24.9,0-35.8,22.7-37.8,39.8H579.5z"/>
<path d="M643.4,293l18.2,68.6c4.2,14.8,7.3,29.4,10.1,43.4h0.8c2.8-14,7.3-28.6,12-43.1l22.4-68.9h20.4l21,67.8
c4.8,15.7,9,30.2,12,44.2h0.8c2.2-14,5.9-28.3,10.4-44.2l19.3-67.8h24.4l-44,135.2h-22.4l-20.4-64.7c-4.8-15.1-8.7-28.6-12-44.5
h-0.6c-3.4,16.2-7.6,30.5-12.3,44.8l-21.8,64.4h-22.4L618.5,293H643.4z"/>
<path id="thirdletter" d="M853.7,365c0.6,33.3,21.6,47,46.5,47c17.6,0,28.6-3.1,37.5-7l4.2,17.6c-8.4,3.9-23.5,8.7-45.1,8.7
c-41.7,0-66.6-27.7-66.6-68.3c0-41.2,24.1-73.1,63.8-73.1c44,0,55.7,38.6,55.7,63.6c0,5-0.6,9-1.1,11.5H853.7z M925.9,347.3
c0.3-15.4-6.4-39.8-34.2-39.8c-24.9,0-35.8,22.7-37.8,39.8H925.9z"/>
<path id="fourthletter" d="M980.2,229.5h24.4v85.1h0.6c8.7-15.1,24.4-24.6,46.2-24.6c33.6,0,57.4,28,57.4,68.9c0,48.4-31.1,72.5-61,72.5
c-19.6,0-35.3-7.6-45.6-25.2h-0.6l-1.1,22.1h-21.3c0.6-9.2,1.1-23,1.1-34.7V229.5z M1004.6,373.9c0,3.1,0.3,6.2,1.1,9
c4.8,17.4,19.3,28.8,37,28.8c26,0,41.2-21,41.2-52.1c0-27.2-14-50.4-40.6-50.4c-16.5,0-32.2,11.5-37.2,30.2
c-0.6,3.1-1.4,6.2-1.4,10.1V373.9z"/>
</g>
</svg></code></pre>
</div>
</div>
</p>
<p>How can I keep the animation color even when it ends?</p>
| 3 | 1,782 |
Remove selected item from a DropDownList always removes the item on top
|
<p>I have two asp.net pages and the <code>summary.aspx</code> will be called from the first asp.net page by using <code>Response.Redirect("summary.aspx")</code>. </p>
<p>Ticket is a custom class with 4 attributes (<code>String name, int age, int seat, int price</code>), their getter and setters and a <code>ToString</code> method.</p>
<p><code>Session["tickets"]</code> stores the objects of Ticket class</p>
<p>My Problem is that I have a dropdownlist called <code>drop_remove</code> and a button called <code>btn_remove</code>. When I click the button, it should remove the selected item and remove the corresponding object from <code>List<Ticket> tickets</code>. However, it always remove the top item from the dropdownlist. I am new to asp.net, please help.</p>
<pre><code>public partial class summary : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Ticket> tickets = (List<Ticket>)Session["tickets"];
if (Session["eventName"].ToString() != null)
{
label_event.Text = Session["eventName"].ToString();
}
if (tickets != null)
{
displayTickets(tickets);
}
if (Session["tickets"] == null)
{
tickets = new List<Ticket>();
}
else
{
tickets = (List<Ticket>)Session["tickets"];
drop_remove.Items.Clear();
foreach (Ticket a in tickets)
{
drop_remove.Items.Add(a.name.ToString());
}
}
}
protected void moreTicekts_Click(object sender, EventArgs e)
{
Response.Redirect("default.aspx");
}
private void displayTickets(List<Ticket> tickets)
{
TextBox1.Text = "";
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.Append(Environment.NewLine);
foreach (Ticket a in tickets)
{
builder.Append(a.ToString() + Environment.NewLine);
}
TextBox1.Text += builder.ToString();
}
protected void btn_remove_Click(object sender, EventArgs e)
{
List<Ticket> tickets = (List<Ticket>)Session["tickets"];
for (int i = 0; i < tickets.Count; i++)
{
if (tickets[i].name.Equals(drop_remove.SelectedItem.ToString()))
{
drop_remove.Items.Remove(drop_remove.SelectedItem);
tickets.RemoveAt(i);
break;
}
}
Session["tickets"] = null;
Session["tickets"] = tickets;
}
}
</code></pre>
| 3 | 1,172 |
Brainfuck interpreter problems
|
<p>I'm new to C. Currently I'm trying to write a Brainfuck interpreter. I have tried this so far.</p>
<pre><code>#include <unistd.h>
#include <stdlib.h>
char *line;
int curr_pos;
void interprete(char *coms)
{
int a;
int curr_loop;
a = -1;
curr_loop = 0;
while (line[++a])
line[a] = 0;
a = -1;
while (coms[++a])
{
if (coms[a] == '+')
line[curr_pos]++;
else if (coms[a] == '-')
line[curr_pos]--;
else if (coms[a] == '>')
curr_pos++;
else if (coms[a] == '<')
curr_pos--;
else if (coms[a] == '.')
write(1, &line[curr_pos], 1);
else if (coms[a] == '[')
{
if (line[curr_pos])
curr_pos++;
else
{
curr_loop = 1;
while (curr_loop)
{
++a;
if (coms[a] == '[')
curr_loop++;
else if (coms[a] == ']')
curr_loop--;
}
}
}
else if (coms[a] == ']')
{
if (line[curr_pos])
{
curr_loop = 1;
while (curr_loop)
{
--a;
if (coms[a] == '[')
curr_loop--;
else if (coms[a] == ']')
curr_loop++;
}
}
else
curr_pos++;
}
}
}
int main(int ac, char **av)
{
if (ac == 2)
{
curr_pos = 0;
line = malloc(sizeof(char) * 4096);
interprete(av[1]);
}
write(1, "\n", 1);
}
</code></pre>
<p>It works only without loops ("[" and "]").When I try:</p>
<pre><code>++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
</code></pre>
<p>It gives me the output </p>
<pre><code>^B^A^H^H^K^B^Q^K^N^H^@^C^@
</code></pre>
<p>Expected output:</p>
<pre><code>Hello World!
</code></pre>
| 3 | 1,394 |
Angular 2 submit JSON within JSON
|
<p>I am trying to use an import function where a user can import raw JSON and then it posts to the server.</p>
<p>for example if a user pastes this json:</p>
<pre><code>{
"name": "testing",
"design": [
{
"name": "test",
"comments": [
{
"short": "123",
"long": "1234567890"
}
],
"maxMark": 0
}
]
}
</code></pre>
<p>Then i want all of that to get sent the server.
Not sure the best of way handling such a task though.</p>
<p>Right now i have a simple form:</p>
<pre><code><modal #importModal [keyboard]="false" [backdrop]="'static'">
<modal-header [show-close]="false">
<h4 class="modal-title">Importing a module</h4>
</modal-header>
<modal-body>
<form name="importForm" [ngFormModel]="importForm" (ngSubmit)="importForm.valid" novalidate>
<textarea class="form-control" rows="20" #data='ngForm' [ngFormControl]="importForm.controls['data']"></textarea>
</form>
<pre>{{importForm.value | json }}</pre>
</modal-body>
<modal-footer>
<button type="button" class="btn btn-danger" (click)="importModal.dismiss()"><i class="fa fa-close"></i> Close</button>
<button type="button" class="btn btn-primary" type="submit" [disabled]="!importForm.valid" (click)="importModal.dismiss() && submitImport(importForm.value)"><i class="fa fa-floppy-o"></i> Submit</button>
</modal-footer>
</modal>
</code></pre>
<p>But the value of the form is showing as:</p>
<pre><code> "data": "{\n \"name\": \"testing\",\n \"design\": [\n {\n \"name\": \"test\",\n \"comments\": [\n {\n \"short\": \"123\",\n \"long\": \"1234567890\"\n }\n ],\n \"maxMark\": 0\n }\n ]\n}"
</code></pre>
<p>Do i have to stringify it then strip it or ? What's the best of converting that back into JSON?</p>
| 3 | 1,221 |
error defining operator == and operator > using binary search tree
|
<p>i am working on a program that reads in a text file that the user inputs, creates a text file that the user inputs, names the text file that the user wants, and then sorts the text file sorting words above the user entered in threshold and displays the words and how many times it was found to the output file the user specify's. i have most of the code finished but im getting a compiler error heres the sample output, error and code</p>
<p>sample output</p>
<p>Enter name of input command file; press return.
history.in
Enter name of output file; press return.
history.out
Enter name of test run; press return.
sample
Enter the minimum size word to be considered.
5
Sample results (found in user specified output file):
sample
abacus 4
abstract 1
adding 1
addition 2
advances 1
after 3</p>
<p>where the word is the word found in the text file, and the number next to it is how many times it was found.</p>
<p>The compiler errors are:</p>
<pre><code>C:\Users\kevin jack\Desktop\prog-4>g++ -o try main.cpp
main.cpp:(.text+0x329) undefined reference to `StrType::PrintToFile(bool, std::basic_ofstream<char, std::char_traits<char> >&)'
:main.cpp:(.text+0x608): undefined reference to `StrType::GetStringFile(bool, InType, std::basic_ifstream<char, std::char_traits<char> >&)'
main.cpp:(.text+0x639): undefined reference to `StrType::LenghtIs()'
main.cpp:(.text+0x6d8): undefined reference to `StrType::GetStringFile(bool, InType, std::basic_ifstream<char, std::char_traits<char> >&)'
collect2: ld returned 1 exit status
</code></pre>
<p>i have no idea what this means if anyone knows please inform me here is my code</p>
<p>main.cpp</p>
<pre><code>//main.cpp
#include <fstream>
#include "StrType.h"
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
struct WordType
{
public:
StrType word;
int count;
};
struct TreeNode
{
WordType info;
TreeNode* left;
TreeNode* right;
};
class ListType
{
public:
ListType();
void InsertOrIncrement (StrType string);
void Print(std::ofstream&) const;
private:
TreeNode* root;
};
ListType::ListType()
{
root=NULL;
}
void Process(TreeNode*& tree, StrType s)
{
if(tree == NULL)
{
tree = new TreeNode;
tree->info.word = s;
tree->info.count = 1;
tree->left = NULL;
tree->right = NULL;
}
else if (tree->info.word == s)
tree->info.count++;
else if (s < tree->info.word)
Process(tree->left, s);
else
Process(tree->right, s);
}
void ListType::InsertOrIncrement(StrType s)
{
Process(root, s);
}
void Print (TreeNode* tree, std::ofstream& outFile)
{
if (tree!= NULL)
{
Print(tree->left, outFile);
tree->info.word.PrintToFile(true, outFile);
outFile <<" "<< tree->info.count;
Print(tree->right, outFile);
}
}
void ListType::Print(std::ofstream& outFile) const
{
::Print(root, outFile);
}
int main()
{
using namespace std;
ListType list;
string inFileName;
string outFileName;
string outputLabel;
ifstream inFile;
ofstream outFile;
StrType string;
int minimumLenght;
cout<<"enter in imput file name."<<endl;
cin>>inFileName;
inFile.open(inFileName.c_str());
cout<<"enter name of output file."<<endl;
cin>>outFileName;
outFile.open(outFileName.c_str());
cout<<"enter name of test run."<<endl;
cin>>outputLabel;
outFile<< outputLabel << endl;
cout<<"enter the min word size."<<endl;
cin>>minimumLenght;
string.GetStringFile(true, ALPHA_NUM, inFile);
while(inFile)
{
if(string.LenghtIs() >= minimumLenght)
list.InsertOrIncrement(string);
string.GetStringFile(true, ALPHA_NUM, inFile);
}
list.Print(outFile);
outFile.close();
inFile.close();
return 0;
}
</code></pre>
<p>StrType.h</p>
<pre><code>//StrType.h
#include <fstream>
#include <iostream>
const int MAX_CHARS=100;
enum InType{ALPHA_NUM, ALPHA, NON_WHITE, NOT_NEW};
class StrType
{
public:
void MakeEmpty();
void GetString(bool skip, InType charsAllowed);
void GetStringFile(bool skip, InType charsAllowed,
std::ifstream& inFile);
void PrintToScreen(bool newLine);
void PrintToFile(bool newLine, std::ofstream& outFile);
int LenghtIs();
void CopyString(StrType& newString);
bool operator==(const StrType& other) const;
bool operator<(const StrType& other) const;
private:
char letters[MAX_CHARS + 1];
};
bool StrType::operator==(const StrType& other) const
{
return (strcmp(letters, other.letters) == 0);
}
bool StrType::operator<(const StrType& other) const
{
return (strcmp(letters, other.letters) < 0);
}
void StrType::MakeEmpty()
{
letters[0] ='\0';
}
</code></pre>
<p>what i was trying to overload the == and > operator. i am stating it in class StrType and defining it just below it but im not sure if im defining it correctly or even in the right spot! any help would be greatly appreciated</p>
| 3 | 2,357 |
How can I get a dynamic display of my jTable content
|
<p>I would like to display my jTable dynamically in function of my jComboBox selected item.</p>
<p>By default, my jTable is completed by an ArrayList (completed with a database SELECT) and there is no problem.</p>
<p>But when I switch my jComoboBox selection to "Tour 2", I would like my jTable to be updated with new rows completed by another request to the database, for example listeMatch = <code>objMatch.getAllMatch(2,2);</code> instead of <code>listeMatch = objMatch.getAllMatch(2,1);</code> .</p>
<p>How can I do this please ?</p>
<pre><code>
import couche.donnees.MatchDAO;
import couche.metier.Match;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class FrameArbreSimple extends JFrame {
public ArrayList<Match> listeMatch = new ArrayList<>();
public MatchDAO objMatch = new MatchDAO();
public String[] columnNames = {
"ID", "Joueur 1", "Joueur 2", "Tournoi", "Court", "Score J1", "Score J2", "Date", "Heure"
};
public DefaultTableModel model = new DefaultTableModel(){
public boolean isCellEditable(int row, int column){
return false;
}
};
public FrameArbreSimple() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox<>();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
model.setColumnIdentifiers(columnNames);
try {
listeMatch = objMatch.getAllMatch(2,1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(null);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Tour 1", "Tour 2", "Tour 3", "Tour 4", "Tour 5" }));
jPanel1.add(jComboBox1);
jComboBox1.setBounds(720, 110, 130, 40);
jComboBox1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (jComboBox1.getSelectedItem().toString().equals("Tour 1")){
try {
listeMatch = objMatch.getAllMatch(2,1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
} else if (jComboBox1.getSelectedItem().toString().equals("Tour 2")){
try {
listeMatch = objMatch.getAllMatch(2,2);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
});
Object[] o = new Object[9];
for (Match match : listeMatch) {
o[0] = match.getIdmatch();
o[1] = match.getIdequipe1();
o[2] = match.getIdequipe2();
o[3] = match.getIdtournoi();
o[4] = match.getIdcourt();
o[5] = match.getScore1();
o[6] = match.getScore2();
o[7] = match.getDate();
o[8] = match.getHeure();
model.addRow(o);
}
jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel1.setText("Arborescence du tournoi");
jPanel1.add(jLabel1);
jLabel1.setBounds(320, 30, 340, 70);
jTable1.setModel(model);
jScrollPane1.setViewportView(jTable1);
jPanel1.add(jScrollPane1);
jScrollPane1.setBounds(40, 170, 810, 400);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
}
</code></pre>
| 3 | 2,367 |
Convert an Array To a Nested JSON
|
<p>I am struggling the last days with an unresolved problem for me. I am stuck on this problem for long time that's why I took the decision to ask for your help.</p>
<p>I'm reading an Excel file and got the following array which I am now trying to convert it to a nested JSON to get accepted from the mongoDB but unfortunately I have difficulties to get there.</p>
<pre class="lang-js prettyprint-override"><code>var arr = ["number,isnewLanguage,label,numberOfChoices,languages/language,questions/mainText/language,questions/subText/language,questions/choices/language,questions/fields/langugage",
"1,false,label1,5,English,MAinText1,SubText1,choices1,false",
"2,false,label2,5,English,MAinText2,SubText2,choices2,false",
"3,true,label1,false,Italian,MainTextItalian1,SubTextItalian1,choicesItalian1,false",
"4,true,label2,false,Italian,MAinTextItalian2,SubTextItalian2,choicesItalian2,false"
]
</code></pre>
<p>I would like to end up with the following structure. Here is a fiddle with my work <a href="https://jsfiddle.net/argusDob/3py6fd8m/2/" rel="nofollow noreferrer">https://jsfiddle.net/argusDob/3py6fd8m/2/</a></p>
<pre class="lang-js prettyprint-override"><code>var json = [{
number: 1,
label1: "label1",
numberOfChoices: 5,
languages: [{
language: "English",
questions: [{
mainText: "MainText1",
subText: "subText1",
choices: "choices1",
fields: "false"
}]
},
{
language: "Italian",
questions: [{
mainText: "MainTextItalian1",
subText: "subTextItlaian1",
choices: "choicesItalian1",
fields: "false"
}]
}
]
},
{
number: 2,
label1: "label2",
numberOfChoices: 5,
languages: [{
language: "English",
questions: [{
mainText: "MainText2",
subText: "subText2",
choices: "choices2",
fields: "false"
}]
},
{
language: "Italian",
questions: [{
mainText: "MainTextItalian2",
subText: "subTextItlaian2",
choices: "choicesItalian2",
fields: "false"
}]
}
]
}
]
</code></pre>
<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 arr = ["number,isnewLanguage,label,numberOfChoices,languages/language,questions/mainText/language,questions/subText/language,questions/choices/language,questions/fields/langugage",
"1,false,label1,5,English,MAinText1,SubText1,choices1,false",
"2,false,label2,5,English,MAinText2,SubText2,choices2,false",
"3,true,label1,false,Italian,MainTextItalian1,SubTextItalian1,choicesItalian1,false",
"4,true,label2,false,Italian,MAinTextItalian2,SubTextItalian2,choicesItalian2,false"
]
var attrs = arr.splice(0, 1);
var test = [];
var result = arr.map(function(row, idx) {
var myObj = {};
var array = [];
var therows = row.split(",").slice(1);
console.log(therows[0]);
therows.forEach(function(value, i) {
var myKeys = attrs[0].split(",").slice(1)
var theKeys = myKeys[i]
if (theKeys.split('/').length === 1) {
myObj[theKeys] = value;
}
//languages
var theLanguagesKey = theKeys.split("/")[0]
if (theKeys.split("/").length == 2) {
if (!myObj["languages"]) {
var theNewLanguage = {}
myObj["languages"] = [];
theNewLanguage[theKeys.split('/')[1]] = value;
myObj["languages"].push(theNewLanguage);
}
}
//questions
if (theKeys.split("/").length == 3) {
if (!myObj["questions"]) {
var theNewQuestions = {}
myObj["questions"] = [];
theNewQuestions[theKeys.split('/')[1]] = value;
myObj["questions"].push(theNewQuestions);
} else {
for (var i = 0; i < myObj["questions"].length; i++) {
myObj["questions"][i][theKeys.split('/')[1]] = value;
}
}
}
})
test.push(myObj)
})
console.log(test)</code></pre>
</div>
</div>
</p>
| 3 | 1,963 |
Android broadcast gps turned on update location
|
<p>Well even having a lot of reading here, i can't figure out the issue. It looks like i never get gps turned on event.</p>
<p>After some checking in debug, the flag isGps is correct. But as a result, user alert works nice but not update location. I just want to add a marker when gps is turned on and it looks like something is not correctly synchronised here.</p>
<p><strong>And that even with high accuraty location.</strong></p>
<p>I use this code from my fragment.</p>
<pre><code>public class MapDialogFragment extends DialogFragment
implements OnMapReadyCallback, GoogleMap.OnMarkerDragListener {
.....
private BroadcastReceiver mGpsSwitchStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
boolean isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGPS){
// never goes here WHEN GPS TURNED ON !!! WHY ?? MAKES ME CRAZY
// + how get current location here ? is updateMyLocation call ok ?
updateMyLocation();
}
else{
// user alert
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.message_location_error_gps_off), Toast.LENGTH_LONG).show();
}
}
}
};
@Override
public void onResume() {
super.onResume();
getContext().registerReceiver(mGpsSwitchStateReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
@Override
public void onPause() {
super.onPause();
getContext().unregisterReceiver(mGpsSwitchStateReceiver);
}
private void updateMyLocation(){
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful() && task.getResult() != null) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = (Location) task.getResult();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
latitude = mLastKnownLocation.getLatitude();
longitude = mLastKnownLocation.getLongitude();
// add marker
buildMarkerFromLocation();
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
}
}
});
}
...
}
</code></pre>
<p>So here is my logic :</p>
<ol>
<li>Check if GPS is turned on</li>
<li>If it is send mFusedLocationProviderClient.getLastLocation() request</li>
<li>Get the result but always get no result when GPS is just turned on</li>
</ol>
<p>So basically, how to provide a default location without hard code one ? </p>
<p>Here is more information about google api page :</p>
<p>The getLastLocation() method returns a Task that you can use to get a Location object with the latitude and longitude coordinates of a geographic location. The location object may be null in the following situations:</p>
<ol>
<li><p>Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.</p></li>
<li><p>The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.</p></li>
<li><p>Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see Receiving Location Updates.</p></li>
</ol>
<p>Hope i will solve this with your help. Should be something obvious but i dunno what is going wrong...</p>
| 3 | 1,883 |
Mongoose-MongoDb : doc.pull inconsistent when multiple pull
|
<p>node v7.7.1
mongodb: 2.2.33,
mongoose: 4.13.7</p>
<p>Hello all,</p>
<p>i'm having this unexpected behaviour when trying to update a document with multiple pull request based on matching criterias. here is what i mean</p>
<p>my document schma looks like this</p>
<pre><code>{
"_id": "5a1c0c37d1c8b6323860dfd0",
"ID": "1511781786844",
"main": {
"_id": "5a3c37bfc065e86a5c593967",
"plan": [
{
"field1": 1,
"field2": 1,
"_id": "5a3c30dfa479bb4b5887e56e",
"child": []
},
{
"field1": 1,
"field2": 2,
"_id": "5a3c30e1a479bb4b5887e5c",
"child": []
},
{
"field1": 1,
"field2": 3,
"_id": "5a3c37bfc065e86a5c593968",
"child": []
},
{
"field1": 1,
"field2": 4,
"_id": "5a3c37bfc065e86a5c593655",
"child": []
},
{
"field1": 1,
"field2": 5,
"_id": "5a3c30dfa479bb4b5887e56f",
"child": []
},
{
"field1": 1,
"field2": 6,
"_id": "5a3c30e1a479bb4b6887e545",
"child": []
},
{
"field1": 1,
"field2": 7,
"_id": "5a3c37bfc065e86a5c5939658",
"child": []
},
{
"field1": 2,
"field2": 2,
"_id": "5a3c37bfc065e86a5c593963",
"child": []
},
]
},
...
....
}
</code></pre>
<p>and this is my code to update the document:</p>
<pre><code>Schema.findOne({ID: data.ID})
.then(function(doc) {
var array = doc.main.plan;
for (i = 0; i < array.length; i++) {
if ( array[i].field1=== 1 )) {
var id = array[i]._id;
console.log('pulling');
doc.pull( { _id: id });
}
}
doc.save().then(function(doc) {
console.log('saving');
// console.log(doc);
if (doc && doc.docID) {
return { success: true };
} else {
return { success: false, error: 'unknownError'}
}
})
}
</code></pre>
<p>now the issue is let's say my array has 7 objects that matches the test (array[i].theField === parseInt(updFields.theField)), when i run this and check the logs i see that it will basically pull half of the objects and do a save.</p>
<p>so i would get
pulling
pulling
pulling
pulling
save.</p>
<p>and then i have to run the code for the remaining 3 objects in the array and get
pulling
pulling
saving</p>
<p>so i have to run it a third time to completely clear the array.</p>
<p>need help get this working</p>
<p>thank you</p>
| 3 | 1,776 |
How to avoid fetching double data from sqlite in a spinner?
|
<p>I'm trying to fetch data from sqlite to set them into a spinner. The user creates rows of travel dates and set them into the database (COLUMN_DATE_DEPART).
In the first spinner I'd like to get the list of the years existing in the COLUMN_DATE_DEPART.
In the second one, I'd like to get the list of months of the year selected in the first spinner.</p>
<p>The problem is as followed: In the first spinner i get the years as expected. In the second spinner i get the months but in double so that if the user created two travels on the 1st and the 31st of January, I'll have the month January twice rather than once.</p>
<p>My question is: What did i miss ?</p>
<p>Find attached my code.</p>
<p><strong>Fragment Activity Java</strong></p>
<pre><code>List<String> an = helper.ListeAnneeTrajet(et_iduser);
final ArrayAdapter<String> adapterA= new ArrayAdapter<>(this.getActivity(), R.layout.spinner_item, an);
adapterA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
annee.setAdapter(adapterA);
annee.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
List<String> mo = helper.ListeMoisTrajet(et_iduser, annee.getSelectedItem().toString().trim());
ArrayAdapter<String> adapterB = new ArrayAdapter<>(getActivity(), R.layout.spinner_item, mo);
adapterA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mois.setAdapter(adapterB);
mois.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
</code></pre>
<p><strong>DatabaseHelper</strong></p>
<pre><code>public List<String> ListeAnneeTrajet(String et_iduser) {
List<String> an = new ArrayList<>();
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME3 + " WHERE (" + COLUMN_ID_CHAUFFEUR + " = '" + et_iduser + "' AND " + COLUMN_DATE_DEPART + " >= DATE('NOW')) GROUP BY SUBSTR(" + COLUMN_DATE_DEPART + ",1,4) ORDER BY " + COLUMN_DATE_DEPART + " ASC";
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
an.add(cursor.getString(cursor.getColumnIndex(COLUMN_DATE_DEPART)).substring(0,4));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return an;
}
public List<String> ListeMoisTrajet(String et_iduser, String et_annee) {
List<String> mo = new ArrayList<>();
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME3 + " WHERE (" + COLUMN_ID_CHAUFFEUR + " = '" + et_iduser + "' AND " + COLUMN_DATE_DEPART + " >= DATE('NOW') AND SUBSTR(" + COLUMN_DATE_DEPART + ",1,4) = '" + et_annee + "') GROUP BY SUBSTR(" + COLUMN_DATE_DEPART + ",6,7) ORDER BY " + COLUMN_DATE_DEPART + " ASC";
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
mo.add(cursor.getString(cursor.getColumnIndex(COLUMN_DATE_DEPART)).substring(5,7));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return mo;
}
</code></pre>
| 3 | 2,014 |
When I run SQL query from RIDE it gives error
|
<p>I am having this problem,</p>
<p>When I send an SQL query as an argument it gives error
when I use the same query directly in my java program it works fine.</p>
<p>MY SQL query when I send as an argument is as follow</p>
<pre><code>Select RATINGPERIOD from INVESTMENT.I1INVE Where INVESTMENTID = 100
rs = stmt.executeQuery(sqlQery); // Select RATINGPERIOD from INVESTMENT.I1INVE Where INVESTMENTID = 100
</code></pre>
<p>and when I use it directly into my java program is as follow</p>
<pre><code>try
{
// Load the driver
Class.forName("com.ibm.db2.jcc.DB2Driver");
System.out.println("**** Loaded the JDBC driver");
// Create the connection using the IBM Data Server Driver for JDBC and SQLJ
con = DriverManager.getConnection (url, user, password);
// Create the Statement
stmt = con.createStatement();
System.out.println("**** Created JDBC Statement object");
// Execute a query and generate a ResultSet instance
rs = stmt.executeQuery("Select RATINGPERIOD from INVESTMENT.I1INVE where INVESTMENTID = 100");
while (rs.next()) {
delay = rs.getString("RATINGPERIOD");
System.out.println("size of list ="+delay);
}
}
Error log
com.ibm.db2.jcc.am.SqlException: [jcc][10103][10941][3.62.57] Method executeQuery cannot be used for update. ERRORCODE=-4476, SQLSTATE=null
at com.ibm.db2.jcc.am.fd.a(fd.java:660)
at com.ibm.db2.jcc.am.fd.a(fd.java:60)
at com.ibm.db2.jcc.am.fd.a(fd.java:120)
at com.ibm.db2.jcc.am.jn.a(jn.java:4129)
at com.ibm.db2.jcc.am.jn.a(jn.java:2875)
at com.ibm.db2.jcc.am.jn.a(jn.java:679)
at com.ibm.db2.jcc.am.jn.executeQuery(jn.java:663)
at com.profitsoftware.testing.utils.keywords.date.DatabaseSQL.sqlQuery(DatabaseSQL.java:46)
at com.profitsoftware.testing.utils.keywords.date.DatabaseSQLKeywords.executeSqlQuery(DatabaseSQLKeywords.java:18)com.
</code></pre>
<p>ok some more information, I have assigned sql query to a string in Java program and then compared it to the query(String) I was getting as argument in my java program and it gives false. which explain maybe when query is passed from RIDE to Java programm it changes somehow. any idea what happens there ?</p>
<p>Thanks in advance and sorry if it sounds a stupid question, I a new to this programming world.</p>
<p>oK, It started to work, actually I was missing something there, so type. My logic itself was good but it was typo that created the problem</p>
<p>--Sara</p>
| 3 | 1,204 |
Benchmarktools' belapsed not working on symbol
|
<h1>Introduction</h1>
<hr>
<p>I have a directory with the following structure</p>
<pre><code>--> Report
--> Problems
--> PE_001
--> Julia
PE_001.naive.jl
PE_001.jl
--> Benchmarks
test_001.txt
test_002.txt
--> Results
--> PE_002
.
.
.
--> PE_XXX
--> Benchmark
</code></pre>
<p>I am attempting to iterate over all the Julia files and benchmark them against the benchmarking data located under the top directory <code>Benchmark</code>. I do not want to have to <code>cd</code> into each directory and run <code>@ belapsed</code> from the julia commandline to time every function individually.</p>
<p>To solve this problem I wrote the following code that is supposed to be located under <code>benchmarks</code> in the hierachy above. However I made it slightly simpler for illustrative purposes.</p>
<h1>Attempt at solution</h1>
<hr>
<p><strong>EDIT</strong>: The code below does NOT follow the hierarchy outlined above. To quickly reproduce the error, the code below has been written in such a way that all the files can be placed in the same directory. </p>
<p><strong><em>benchmark.jl</em></strong></p>
<pre><code>include("PE_002.jl")
using BenchmarkTools
function get_file_path(PE=1)
current_folder = pwd()
PE_folder = "/PE_" * lpad(string(PE),3,"0")
dirname(pwd()) * "/Problems" * PE_folder * "/Julia"
end
function include_files(PE_dir)
for filename in readdir(PE_dir)
if !startswith(filename, "benchmark")
filepath = PE_dir * "/" * filename
@everywhere include($filepath)
end
end
end
function benchmark_files(PE_dir)
for filename in readdir(PE_dir)
if !startswith(filename, "benchmark")
f = getfield(Main, Symbol(filename[1:end-3]))
# Produces an error
println(@belapsed f())
end
end
end
# Works
println(@belapsed PE_002())
PE_dir = pwd()
include_files(PE_dir)
benchmark_files(PE_dir)
</code></pre>
<p><strong>PE_002.jl</strong></p>
<pre><code>function PE_002(limit = 4*10^6)
a, b = 0, 2
while b < limit
a, b = b, 4 * b + a
end
div(a + b - 2, 4)
end
</code></pre>
<p><strong><em>PE_002_naive.jl</em></strong></p>
<pre><code>function PE_002_naive(limit=4 * 10^6, F_1=1, F_2=2)
total = 0
while F_2 < limit
if F_2 % 2 == 0
total += F_2
end
F_1, F_2 = F_2, F_1 + F_2
end
total
end
</code></pre>
<p><strong>test_001.txt</strong></p>
<pre><code>0*10**(2**0)
4*10**(2**0)
4*10**(2**1)
4*10**(2**2)
4*10**(2**3)
4*10**(2**4)
4*10**(2**5)
4*10**(2**6)
</code></pre>
<hr>
<h1>Question</h1>
<p>Interestingly enough including the file <code>PE_002</code> and then running <code>@ belapsed</code> works, however obtaining the filename from the directory, turning it into a symbol, then trying to time it with <code>@belapsed</code> fails. </p>
<p>I know <code>@elapsed works</code>, however, due to garbage collection it is not nearly accurate enough for my needs. </p>
<p><strong>Is there a simple way to benchmark all files in a remote directory using BenchmarkTools or similar tools as accurate?</strong></p>
<p>All I need is a single number representing mean / average running time from each file. </p>
<p>EDIT 2: Per request I have included the full error message below</p>
<pre><code>~/P/M/Julia-belaps ❯❯❯ julia benchmark.jl
9.495495495495496e-9
ERROR: LoadError: UndefVarError: f not defined
Stacktrace:
[1] ##core#665() at /home/oisov/.julia/v0.6/BenchmarkTools/src/execution.jl:290
[2] ##sample#666(::BenchmarkTools.Parameters) at /home/oisov/.julia/v0.6/BenchmarkTools/src/execution.jl:296
[3] #_run#6(::Bool, ::String, ::Array{Any,1}, ::Function, ::BenchmarkTools.Benchmark{Symbol("##benchmark#664")}, ::BenchmarkTools.Parameters) at /home/oisov/.julia/v0.6/BenchmarkTools/src/execution.jl:324
[4] (::BenchmarkTools.#kw##_run)(::Array{Any,1}, ::BenchmarkTools.#_run, ::BenchmarkTools.Benchmark{Symbol("##benchmark#664")}, ::BenchmarkTools.Parameters) at ./<missing>:0
[5] anonymous at ./<missing>:?
[6] #run_result#16(::Array{Any,1}, ::Function, ::BenchmarkTools.Benchmark{Symbol("##benchmark#664")}, ::BenchmarkTools.Parameters) at /home/oisov/.julia/v0.6/BenchmarkTools/src/execution.jl:40
[7] (::BenchmarkTools.#kw##run_result)(::Array{Any,1}, ::BenchmarkTools.#run_result, ::BenchmarkTools.Benchmark{Symbol("##benchmark#664")}, ::BenchmarkTools.Parameters) at ./<missing>:0
[8] #run#17(::Array{Any,1}, ::Function, ::BenchmarkTools.Benchmark{Symbol("##benchmark#664")}, ::BenchmarkTools.Parameters) at /home/oisov/.julia/v0.6/BenchmarkTools/src/execution.jl:43
[9] (::Base.#kw##run)(::Array{Any,1}, ::Base.#run, ::BenchmarkTools.Benchmark{Symbol("##benchmark#664")}, ::BenchmarkTools.Parameters) at ./<missing>:0 (repeats 2 times)
[10] macro expansion at /home/oisov/.julia/v0.6/BenchmarkTools/src/execution.jl:208 [inlined]
[11] benchmark_files(::String) at /home/oisov/Programming/Misc/Julia-belaps/benchmark.jl:26
[12] include_from_node1(::String) at ./loading.jl:569
[13] include(::String) at ./sysimg.jl:14
[14] process_options(::Base.JLOptions) at ./client.jl:305
[15] _start() at ./client.jl:371
while loading /home/oisov/Programming/Misc/Julia-belaps/benchmark.jl, in expression starting on line 36
</code></pre>
| 3 | 2,178 |
dplyr: comparing values within a variable dependent on another variable
|
<p>How can I compare values within a variable dependent on another variable with dplyr?</p>
<p>The df is based on choice data (long format) from a survey. It has one variable that indicates a participants <em>id</em>, another that indicates the choice <em>inst</em>ance and one that indicates which <em>alt</em>ernative was chosen.
In my data I have the feeling that a lot of people tend to get bored of the task and therefore stick to one alternative for every instance. I would therefore like to identify people who always selected the same option from a certain instance onwards till the end.</p>
<p>Here is an example df:</p>
<pre><code>set.seed(0)
df <- tibble(
id = rep(1:5,each=12),
inst = rep(1:12,5),
alt = sample(1:3, size =60, replace=T),
)
</code></pre>
<p>That looks like the following:</p>
<pre><code> id inst alt
1 1 1 3
2 1 2 1
3 1 3 2
4 1 4 2
5 1 5 3
6 1 6 1
7 1 7 3
8 1 8 3
9 1 9 2
10 1 10 2
11 1 11 1 <-
12 1 12 1 <-
13 2 1 1
14 2 2 3
...
</code></pre>
<p>I would like to create two new variables <em>count</em> and <em>count_alt</em>. The new variable <em>count</em> should indicate how often the same value appeared in <em>alt</em> based on <em>id</em> and <em>inst</em>, only counting values from the end of <em>id</em>. So for participant (id==1) the <em>count</em> variable should be 2, since alternative 1 was chosen in the last two instances (11 & 12). <em>The count_alt</em> would take the value 1 (always the same as inst == 12)</p>
<p>The new df schould look like the following</p>
<pre><code> id inst alt count count_alt
1 1 1 3 2 1
2 1 2 1 2 1
3 1 3 2 2 1
4 1 4 2 2 1
5 1 5 3 2 1
6 1 6 1 2 1
7 1 7 3 2 1
8 1 8 3 2 1
9 1 9 2 2 1
10 1 10 2 2 1
11 1 11 1 2 1
12 1 12 1 2 1
...
</code></pre>
<p>I would prefer to solve this with dplyr and not with a loop since I want to incooperate it into further data wrangling steps. </p>
| 3 | 1,161 |
Firebase: Attempting to populate an ArrayList with addListenerForSingleValueEvents, it only adds one child
|
<pre><code>DatabaseReference ref = mFirebaseDatabaseReference.child("questions");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String dQuestion;
ArrayList<Question> alQuestions = new ArrayList<Question>();
for(DataSnapshot questionSnapshot : dataSnapshot.getChildren()){
dQuestion = questionSnapshot.child("question").getValue(String.class);
Question q = new Question(dQuestion);
alQuestions.add(q);
}
randoms[0] = (int) Math.random() * alQuestions.size();
randoms[1] = (int) Math.random() * alQuestions.size();
randoms[2] = (int) Math.random() * alQuestions.size();
randoms[3] = (int) Math.random() * alQuestions.size();
randoms[4] = (int) Math.random() * alQuestions.size();
String q1, q2, q3, q4, q5;
q1 = alQuestions.get(randoms[0]).getQuestion();
q2 = alQuestions.get(randoms[1]).getQuestion();
q3 = alQuestions.get(randoms[2]).getQuestion();
q4 = alQuestions.get(randoms[3]).getQuestion();
q5 = alQuestions.get(randoms[4]).getQuestion();
tvQuestion1.setText(q1);
tvQuestion2.setText(q2);
tvQuestion3.setText(q3);
tvQuestion4.setText(q4);
tvQuestion5.setText(q5);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
</code></pre>
<p>As you can see, I've added a listener to the database reference and within the foreach loop, I'm trying to iterate all the specified children and populate the ArrayList which I'm later trying to refer to when I want to get some of the values from it.</p>
<p>The problem is, this code, as it is, only puts one element in the ArrayList, over and over, or just once, not sure, but only the very first entry from the specified database location gets in the ArrayList and is displayed where I want it.</p>
<p>How do I get all the children inside the ArrayList?</p>
<p>EDIT:</p>
<p>Database structure</p>
<pre><code>survey-6d90daddclose
questions
-KdG_f4dckyHRBVLrYj2
date:
"Sat Feb 18 09:18:34 EST 2017"
question:
"Will it work properly this time?"
-KdG_sNbmmIFiJGOWHTz
date:
"Sat Feb 18 09:19:29 EST 2017"
question:
"Will it work properly this time?"
-KdGd1Nl-tifclI_Gd4e
date:
"Sat Feb 18 09:33:16 EST 2017"
question:
"Username: null"
-KdHTJZ2IHvgtWpLQIyQ
date:
"Sat Feb 18 13:26:04 EST 2017"
question:
"Username: null"
-KdLIycLs-Qv5zscKYIV
date:
"Sun Feb 19 07:19:32 EST 2017"
question:
"Q1"
-KdLIzjSr3o-h8ewH5CL
date:
"Sun Feb 19 07:19:36 EST 2017"
question:
"Q2"
-KdLJ1VhcUZQlqU2hoxA
date:
"Sun Feb 19 07:19:48 EST 2017"
question:
"Q3"
-KdLJ3XxTLeOEH83fzzw
date:
"Sun Feb 19 07:19:56 EST 2017"
question:
"Q4"
-KdLJ4ci6p7OLdPl4AS2
date:
"Sun Feb 19 07:20:00 EST 2017"
question:
"Q5"
-KdLJ5Wz5Bk-X_U0cRwQ
date:
"Sun Feb 19 07:20:04 EST 2017"
question:
"Q6"
-KdLJ6jdYaNWnr8_PfEk
date:
"Sun Feb 19 07:20:09 EST 2017"
question:
"Q7"
-KdLJ7i5EzAEr6HLr__-
date:
"Sun Feb 19 07:20:13 EST 2017"
question:
"Q8"
</code></pre>
<p>Question class</p>
<pre><code>public class Question {
private String date;
private String question;
private String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public Question() {
}
public Question(String date, String question, String username) {
this.date = date;
this.question = question;
this.username = username;
}
public Question(String question) {
this.question = question;
}
public String getDate() {
return date;
}
public String getQuestion() {
return question;
}
public void setDate(String date) {
this.date = date;
}
public void setQuestion(String question) {
this.question = question;
}
}
</code></pre>
| 3 | 1,948 |
DIV Row & HRs Extend Beyond Container (Bootstrap)
|
<p>Hey I have a DIV and a HR pushing out of their Container. I've tried several different fixes, but nothing seems to work. I've placed everything in a Fiddle so you can take a look at what I'm talking about. Any help would be appreciated.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0;
padding: 0;
}
.img {
float: left;
width: 100px;
height: 100px;
position: relative;
top: 0;
left: 0;
}
.copy {
position: relative;
float: left;
margin-left: 10px;
}
.leadMargin {
margin-left: 10px;
postion: relative;
}
.hr {
clear: both;
border: 3px solid #f5f5f5;
margin-top: 110px;
margin-right: 100px;
position: relative;
}
.noMargin {
margin: 0;
}
.position-relative {
position: relative;
}
.position-absolute {
position: absolute;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<body>
<div class="container-fluid">
<h1 class="">Post Block</h1>
<hr>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-5">
<img src="http://www.placehold.it/400X200" class="img-responsive" alt="placeholder image" />
<p class="lead">Responsive Design</p>
<p>Bacon ipsum dolor amet beef ribs turkey ut et cillum, capicola culpa turducken t-bone. Adipisicing officia pork loin, nulla andouille in eu capicola. Landjaeger pork chop sed kielbasa boudin aliqua. Salami pork ground round, jerky fatback ut eiusmod.
Nisi ball tip do pig shankle turducken. Velit nisi t-bone pork tail corned beef salami pancetta cupidatat sirloin eu sint jowl. Qui cow voluptate pastrami.</p>
</div>
<div class="col-sm-5 col-md-5">
<div class="container-fluid">
<div class="row">
<img src="http://www.placehold.it/100x100" class="img " alt="lady with senior lady" />
<div class="col-sm-5 col-md-5 ">
<p class="lead noMargin">New Collection of Shortcodes</p>
<p>Landjaeger pork chop sed kielbasa boudin aliqua. Salami pork ground round, jerky fatback ut eiusmod. Nisi ball tip do pig shankle turducken.</p>
</div>
<hr class="hr">
</div>
<div class="row position-relative">
<img src="http://www.placehold.it/100x100" class="img" alt="lady with senior lady" />
<div class="col-sm-5 col-md-5">
<p class="lead noMargin">New Collection of Shortcodes</p>
<p>Landjaeger pork chop sed kielbasa boudin aliqua. Salami pork ground round, jerky fatback ut eiusmod. Nisi ball tip do pig shankle turducken.</p>
</div>
<hr class="hr">
</div>
<div class="row"> <img src="http://www.placehold.it/100x100" class="img" alt="lady with senior lady" />
<div class="col-sm-5 col-md-5">
<p class="lead noMargin">New Collection of Shortcodes</p>
<p>Landjaeger pork chop sed kielbasa boudin aliqua. Salami pork ground round, jerky fatback ut eiusmod. Nisi ball tip do pig shankle turducken.</p>
</div>
<hr class="hr">
</div>
</div>
</div>
</div>
</div>
</body></code></pre>
</div>
</div>
</p>
<p>Thanks in advance.
Kyle</p>
| 3 | 1,732 |
Spectogram of a .wav file returns wrong results
|
<p>I am currently trying to plot the frequency domain of a .wav file which then i can use the values of, to train a neural network to predict which sound is playing.</p>
<p>I already read the bytes of the .wav file using this bit of code, starting from the 44th byte , which is the start of the data chunk:</p>
<pre><code>entireFileData= Files.readAllBytes(Paths.get(filepath));
byte[] data_raw= Arrays.copyOfRange(entireFileData,44,entireFileData.length);
double[] dataNew=new double[(int)myDataSize/2];
int new_length=data_raw.length/2;
double val;
myData = new byte[(int)myDataSize];
for(int i=0;i<new_length;i+=2) {
val =((data_raw[i]*0xff)<<8)| (data_raw[i+1]*0xff);
dataNew[i]=(double) val;
}
</code></pre>
<p>Then i used fourier transform on the byte array</p>
<pre><code>ApacheFFT apacheFFT=new ApacheFFT();
apacheFFT.forward(dataNew,(float)44100,w);
Spectrum s = apacheFFT.getMagnitudeSpectrum(); //I used the getMagnitudeSpectrum method to be able to plot
double[] freq=s.array(); //the graph
double[] array=new double[freq.length]
</code></pre>
<p>Here is the createSpectrum method:</p>
<pre><code>public static Spectrum createMagnitudeSpectrum(Complex[] data, float samplingrate, WindowFunction windowFunction) {
int bins = data.length / 2;
double normalizationFactor = data.length * windowFunction.normalization(data.length);
double[] magnitudeSpectrum = new double[bins];
magnitudeSpectrum[0] = Math.sqrt(Math.pow(data[0].getReal(), 2) + Math.pow(data[0].getImaginary(), 2)) / normalizationFactor;
for (int i = 1; i < bins; i++) {
magnitudeSpectrum[i] = (2 * data[i].abs()) / normalizationFactor;
}
return new Spectrum(Type.MAGNITUDE, magnitudeSpectrum, FFTUtil.binCenterFrequencies(data.length, samplingrate));
}
</code></pre>
<p>This is the Forward Fourier Transform i used, from the AppacheFFT package:</p>
<pre><code>public void forward(double[] data, float samplingrate, WindowFunction window) {
this.windowFunction = window;
this.samplingrate = samplingrate;
int actual_length = 8192;
int valid_length = FFTUtil.nextPowerOf2(actual_length);
double[] reshaped = new double[valid_length];
for (int i = 0; i < reshaped.length; i++) {
if (i < actual_length) {
reshaped[i] = data[i] * this.windowFunction.value(i, valid_length);
} else {
reshaped[i] = 0;
}
}
/* Perform FFT using FastFourierTransformer library. */
FastFourierTransformer transformer = new FastFourierTransformer(DftNormalization.STANDARD);
this.data = transformer.transform(reshaped, TransformType.FORWARD);
/* Reset the calculated properties. */
this.powerSpectrum = null;
this.magnitudeSpectrum = null;
}
</code></pre>
<p>I then plotted the values to a graph using LineGraphSeries like so:</p>
<pre><code>for(int i=0;i<freq.length;i++)
{
dataPoints[i]=new DataPoint(i,freq[i]);
}
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(dataPoints);
graph.addSeries(series);
</code></pre>
<p>So to test myself i used audacity's plot spectrum tool to see the difference, and it is quite a difference between my result and audacity's:</p>
<p>I am not allowed to post pictures so <a href="https://i.stack.imgur.com/BLfBT.png" rel="nofollow noreferrer">here's</a> a link to the comparison.</p>
<p>As you can see it's not even near the one in audacity. I have actually observed that my signal is mirrored from the half.</p>
<p>I tried multiple ways of reading the .wav file, multiple ways of plotting the file to the graph.
I can't really fathom what could have went wrong here.</p>
<p>Also i'm sorry if i made any formatting mistakes.</p>
<p>Any opinions on this?</p>
<p>Edit: Okay, i actually did it , it was the way i read the bytes, i didnt mask it, and bytes are signed so it would give me wrong values, but now it only works on one frequency, for example if i have a 3Khz sine wave file, it shows tehe 3Khz freq, if i have 10Khz it shows 10, but if i have both of the frequencies in one file, it only shows the 3Khz one</p>
| 3 | 1,570 |
Glue does not work from the Docker Container
|
<p>I am trying to run a simple Glue Job that takes the content from AWS S3 and dumps it into AWS Aurora Postgresql. While the job runs fine from the AWS Console, it just refuses to work while trying to run it out of a Docker Container on an EC2 instance. I have unchecked the "Require SSL" option while creating the Glue Connection. Despite that it is looking for some SSL certificate. I have kept the Aurora instance publicly accessible. Does anyone know what the problem is? Has anyone faced a similar issue?</p>
<pre><code>20/10/24 10:20:17 ERROR Driver: Connection error:
org.postgresql.util.PSQLException: Could not open SSL root certificate file .
at org.postgresql.Driver$ConnectThread.getResult(Driver.java:401)
at org.postgresql.Driver.connect(Driver.java:259)
at com.amazonaws.services.glue.util.JDBCWrapper$$anonfun$8.apply(JDBCUtils.scala:895)
at com.amazonaws.services.glue.util.JDBCWrapper$$anonfun$8.apply(JDBCUtils.scala:891)
at com.amazonaws.services.glue.util.JDBCWrapper$.com$amazonaws$services$glue$util$JDBCWrapper$$catchSSLException(JDBCUtils.scala:852)
at com.amazonaws.services.glue.util.JDBCWrapper$.connectWithSSLAttempt(JDBCUtils.scala:847)
at com.amazonaws.services.glue.util.JDBCWrapper$.connectionProperties(JDBCUtils.scala:890)
at com.amazonaws.services.glue.util.JDBCWrapper.connectionProperties$lzycompute(JDBCUtils.scala:670)
at com.amazonaws.services.glue.util.JDBCWrapper.connectionProperties(JDBCUtils.scala:670)
at com.amazonaws.services.glue.util.JDBCWrapper.writeDF(JDBCUtils.scala:814)
at com.amazonaws.services.glue.sinks.PostgresDataSink.writeDynamicFrame(PostgresDataSink.scala:40)
at com.amazonaws.services.glue.DataSink.pyWriteDynamicFrame(DataSink.scala:52)
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 py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:282)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:238)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at org.postgresql.ssl.jdbc4.LibPQFactory.<init>(LibPQFactory.java:124)
at org.postgresql.ssl.MakeSSL.convert(MakeSSL.java:42)
at org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:359)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:148)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
at org.postgresql.Driver.makeConnection(Driver.java:450)
at org.postgresql.Driver.access$100(Driver.java:60)
at org.postgresql.Driver$ConnectThread.run(Driver.java:360)
... 1 more
20/10/24 10:20:20 INFO JDBCWrapper$: INFO: using ssl properties: Map(loginTimeout -> 10, sslmode -> require)
</code></pre>
| 3 | 1,319 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.