title stringlengths 13 150 | body stringlengths 749 64.2k | label int64 0 3 | token_count int64 1.02k 28.5k |
|---|---|---|---|
How can I install the libwebsocket library in Ubuntu? | <p>I am trying to install the libwebsocket in my ubuntu .</p>
<p>so I downloaded the project <a href="https://github.com/warmcat/libwebsockets">https://github.com/warmcat/libwebsockets</a>
unzipped it and I followed the installation instruction.</p>
<p>I type the command cmake FH and get the following messages.</p>
<pre><code> You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:State or Province Name (full name) [Some-State]:Locality Name (eg, city) []:Organization Name (eg, company) [Internet Widgits Pty Ltd]:Organizational Unit Name (eg, section) []:Common Name (e.g. server FQDN or YOUR name) []:Email Address []:SUCCSESFULLY generated SSL certificate
Generating API documentation
-- Looking for RPMTools... - rpmbuild NOT FOUND
---------------------------------------------------------------------
Settings: (For more help do cmake -LH <srcpath>
---------------------------------------------------------------------
LWS_WITH_SSL = ON (SSL Support)
LWS_SSL_CLIENT_USE_OS_CA_CERTS = 1
LWS_USE_CYASSL = OFF (CyaSSL replacement for OpenSSL)
LWS_WITHOUT_BUILTIN_GETIFADDRS = OFF
LWS_WITHOUT_CLIENT = OFF
LWS_WITHOUT_SERVER = OFF
LWS_LINK_TESTAPPS_DYNAMIC = OFF
LWS_WITHOUT_TESTAPPS = OFF
LWS_WITHOUT_TEST_SERVER = OFF
LWS_WITHOUT_TEST_SERVER_EXTPOLL = OFF
LWS_WITHOUT_TEST_PING = OFF
LWS_WITHOUT_TEST_CLIENT = OFF
LWS_WITHOUT_TEST_FRAGGLE = OFF
LWS_WITHOUT_DEBUG = OFF
LWS_WITHOUT_EXTENSIONS = OFF
LWS_WITH_LATENCY = OFF
LWS_WITHOUT_DAEMONIZE = OFF
LWS_USE_LIBEV =
LWS_IPV6 = OFF
LWS_WITH_HTTP2 = OFF
---------------------------------------------------------------------
-- Configuring done
-- Generating done
-- Build files have been written to: /home/maroua/libwebsocket/libwebsockets-master
-- Cache values
// Choose the type of build, options are: None(CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.
CMAKE_BUILD_TYPE:STRING=
// Install path prefix, prepended onto install directories.
CMAKE_INSTALL_PREFIX:PATH=/usr/local
// Libwebsockets include directories
LIBWEBSOCKETS_INCLUDE_DIRS:PATH=/home/maroua/libwebsocket/libwebsockets-master/lib;/home/maroua/libwebsocket/libwebsockets-master
// Libwebsocket libraries
LIBWEBSOCKETS_LIBRARIES:STRING=websocket;websockets_shared
// Libwebsocket shared library
LIBWEBSOCKETS_LIBRARIES_SHARED:STRING=websockets_shared
// Libwebsocket static library
LIBWEBSOCKETS_LIBRARIES_STATIC:STRING=websocket
// Path to the CyaSSL include directory
LWS_CYASSL_INCLUDE_DIRS:PATH=
// Path to the CyaSSL library
LWS_CYASSL_LIB:PATH=
// Installation directory for executables
LWS_INSTALL_BIN_DIR:PATH=bin
// Installation directory for CMake files
LWS_INSTALL_CMAKE_DIR:PATH=lib/cmake/libwebsockets
// Installation directory for example files
LWS_INSTALL_EXAMPLES_DIR:PATH=bin
// Installation directory for header files
LWS_INSTALL_INCLUDE_DIR:PATH=include
// Installation directory for libraries
LWS_INSTALL_LIB_DIR:PATH=lib
// Compile with support for ipv6
LWS_IPV6:BOOL=OFF
// Link the test apps to the shared version of the library. Default is to link statically
LWS_LINK_TESTAPPS_DYNAMIC:BOOL=OFF
// Server SSL certificate directory
LWS_OPENSSL_CLIENT_CERTS:PATH=../share
// SSL support should make use of OS installed CA root certs
LWS_SSL_CLIENT_USE_OS_CA_CERTS:BOOL=ON
// Use CyaSSL replacement for OpenSSL. When settings this, you also need to specify LWS_CYASSL_LIB and LWS_CYASSL_INCLUDE_DIRS
LWS_USE_CYASSL:BOOL=OFF
// Search the system for ZLib instead of using the included one (on Windows)
LWS_USE_EXTERNAL_ZLIB:BOOL=OFF
// Don't use BSD getifaddrs implementation from libwebsockets if it is missing (this will result in a compilation error) ... Default is your libc provides it. On some systems such as uclibc it doesn't exist.
LWS_WITHOUT_BUILTIN_GETIFADDRS:BOOL=OFF
// Don't build the client part of the library
LWS_WITHOUT_CLIENT:BOOL=OFF
// Don't build the daemonization api
LWS_WITHOUT_DAEMONIZE:BOOL=OFF
// Don't compile debug related code
LWS_WITHOUT_DEBUG:BOOL=OFF
// Don't compile with extensions
LWS_WITHOUT_EXTENSIONS:BOOL=OFF
// Don't build the server part of the library
LWS_WITHOUT_SERVER:BOOL=OFF
// Don't build the libwebsocket-test-apps
LWS_WITHOUT_TESTAPPS:BOOL=OFF
// Don't build the client test application
LWS_WITHOUT_TEST_CLIENT:BOOL=OFF
// Don't build the ping test application
LWS_WITHOUT_TEST_FRAGGLE:BOOL=OFF
// Don't build the ping test application
LWS_WITHOUT_TEST_PING:BOOL=OFF
// Don't build the test server
LWS_WITHOUT_TEST_SERVER:BOOL=OFF
// Don't build the test server version that uses external poll
LWS_WITHOUT_TEST_SERVER_EXTPOLL:BOOL=OFF
// Compile with support for http2
LWS_WITH_HTTP2:BOOL=OFF
// Build latency measuring code into the library
LWS_WITH_LATENCY:BOOL=OFF
// Compile with support for libev
LWS_WITH_LIBEV:BOOL=OFF
// Include SSL support (default OpenSSL, CyaSSL if LWS_USE_CYASSL is set)
LWS_WITH_SSL:BOOL=ON
// The RPM builder tool
RPMTools_RPMBUILD_EXECUTABLE:FILEPATH=RPMTools_RPMBUILD_EXECUTABLE-NOTFOUND
</code></pre>
<p>I tried to compile a C program that uses libwebsocket.h, it tells me that it does not exist.
Can any one show me the right way to install this lib.
Thanks for any help .</p> | 0 | 1,929 |
Future exception was never retrieved | <p>I have a scraper (based on Python 3.4.2 and asyncio/aiohttp libs) and bunch of links (> 10K) to retrive some small amount of data.
Part of scraper code:</p>
<pre><code>@asyncio.coroutine
def prepare(self, links):
semaphore = asyncio.Semaphore(self.limit_concurrent)
tasks = []
result = []
tasks = [self.request_data(link, semaphore) for link in links]
for task in asyncio.as_completed(tasks):
response = yield from task
if response:
result.append(response)
task.close()
return result
@asyncio.coroutine
def request_data(self, link, semaphore):
...
with (yield from semaphore):
while True:
counter += 1
if counter >= self.retry:
break
with aiohttp.Timeout(self.timeout):
try:
response = yield from self.session.get(url, headers=self.headers)
body = yield from response.read()
break
except asyncio.TimeoutError as err:
logging.warning('Timeout error getting {0}'.format(url))
return None
except Exception:
return None
...
</code></pre>
<p>Whan it trying to make requests to malformed URL's I get messages like this:</p>
<pre><code>Future exception was never retrieved
future: <Future finished exception=gaierror(11004, 'getaddrinfo failed')>
Traceback (most recent call last):
File "H:\Python_3_4_2\lib\concurrent\futures\thread.py", line 54, in run
result = self.fn(*self.args, **self.kwargs)
File "H:\Python_3_4_2\lib\socket.py", line 530, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed
</code></pre>
<p>The error occures when trying to yield response from session.get. As I understand the exception was never consumed by asyncio and so it wasn't "babble up".</p>
<p>First I tryed to simply wrap request by try/except:</p>
<pre><code>try:
response = yield from self.session.get(url, headers=self.headers)
except Exception:
return None
</code></pre>
<p>This doesn't work.</p>
<p>Then I <a href="https://wingware.com/psupport/python-manual/3.4/library/asyncio-dev.html#detect-exceptions-not-consumed" rel="noreferrer">read here</a> about chaining coroutines to catch exception but this didn't work for me either. I still get those messages and script crashes after certain amount of time.</p>
<p>So my question - how I can handle this exception in proper way?</p> | 0 | 1,035 |
System.ArgumentException and System.ComponentModel.Win32Exception when getting process information | <p>When i try to write process' information to console i get System.ArgumentException and System.ComponentModel.Win32Exception. What causes this? How can i stop having those?</p>
<pre><code> Process processListe = Process.GetProcesses();
for (int i = 0; i < processListe.Count(); i++)
{
try
{
string companyName = processListe[i].MainModule.FileVersionInfo.CompanyName;
string fileVersion = processListe[i].MainModule.FileVersionInfo.FileVersion;
Console.WriteLine(companyName + " " + fileVersion);
}
catch (Exception) { }
}
</code></pre>
<p>Errors happen in "string companyName = processListe[i].MainModule.FileVersionInfo.CompanyName;" line.</p>
<p>Error messages:</p>
<pre><code> System.ArgumentException: Illegal characters in path.
at System.Security.Permissions.FileIOPermission.HasIllegalCharacters(String[] str)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.Path.GetFullPath(String path)
at System.Diagnostics.FileVersionInfo.GetFullPathWithAssert(String fileName)
at System.Diagnostics.FileVersionInfo.GetVersionInfo(String fileName)
at System.Diagnostics.ProcessModule.get_FileVersionInfo()
A first chance exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll
System.ComponentModel.Win32Exception (0x80004005): Unable to enumerate the process modules.
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32 processId)
at System.Diagnostics.Process.get_MainModule()
</code></pre>
<p>Lastly i've made an information output of those process which makes me get errors:</p>
<pre><code> Exception: Illegal characters in path.
Proess Name: winlogon Company Name: Aestan Software Version: 1.6.1.33
Detail: System.ArgumentException: Illegal characters in path.
at System.Security.Permissions.FileIOPermission.HasIllegalCharacters(String[] str)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.Path.GetFullPath(String path)
at System.Diagnostics.FileVersionInfo.GetFullPathWithAssert(String fileName)
at System.Diagnostics.FileVersionInfo.GetVersionInfo(String fileName)
at System.Diagnostics.ProcessModule.get_FileVersionInfo()
Exception: Illegal characters in path.
Proess Name: csrss Company Name: Microsoft Corporation Version: 2009.0100.1600.01 ((KJ_RTM).100402-1540 )
Detail: System.ArgumentException: Illegal characters in path.
at System.Security.Permissions.FileIOPermission.HasIllegalCharacters(String[] str)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.Path.GetFullPath(String path)
at System.Diagnostics.FileVersionInfo.GetFullPathWithAssert(String fileName)
at System.Diagnostics.FileVersionInfo.GetVersionInfo(String fileName)
at System.Diagnostics.ProcessModule.get_FileVersionInfo()
Exception: Unable to enumerate the process modules.
Proess Name: System Company Name: BitTorrent, Inc. Version: 7.5.0.25682
Detail: System.ComponentModel.Win32Exception (0x80004005): Unable to enumerate the process modules.
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32 processId)
at System.Diagnostics.Process.get_MainModule()
Exception: Access is denied
Proess Name: Cheat Engine Company Name: Version: 5.6.1.10
Detail: System.ComponentModel.Win32Exception (0x80004005): Access is denied
at System.Diagnostics.ProcessManager.OpenProcess(Int32 processId, Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.get_HasExited()
</code></pre> | 0 | 1,585 |
Java Applet Error - IllegalArgumentException "adding container's parent to itself" | <p>I have to create an applet. The code I have written is as follows.</p>
<pre><code>import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class feedback extends JApplet
implements ActionListener
{
private JTextField login;
private JTextField email;
private JTextField comments;
private final String SUBMIT="SUBMIT";
private final String CLEAR="CLEAR";
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(CLEAR.equals(command))
{login.setText(" ");
email.setText(" ");
comments.setText(" ");}
else if(SUBMIT.equals(command))
{
login.setText(" ");
email.setText(" ");
comments.setText(" ");
}
}
public void start()
{
Container contentPane = getContentPane();
JScrollPane sPane = new JScrollPane();
JPanel pContPanel = new JPanel();
pContPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(3, 4, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10,10,10,10), 20, 20);
JLabel title = new JLabel("FEEDBACK");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3;
pContPanel.add(title, gbc);
JPanel panel1 = new JPanel();
JLabel prompt = new JLabel("LOGIN");
panel1.add(prompt, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
pContPanel.add(panel1, gbc);
login = new JTextField(15);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 2;
pContPanel.add(login, gbc);
JPanel panel2=new JPanel();
JLabel print = new JLabel("EMAIL");
panel2.add(panel2);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;
pContPanel.add(panel2, gbc);
email = new JTextField(30);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 2;
pContPanel.add(email, gbc);
JPanel panel3=new JPanel();
JLabel ask = new JLabel("COMMENTS");
panel3.add(panel3);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
pContPanel.add(panel3, gbc);
comments = new JTextField(50);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.gridwidth = 2;
pContPanel.add(comments, gbc);
JButton bSUBMIT = new JButton(SUBMIT);
bSUBMIT.addActionListener(this);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 1;
pContPanel.add(bSUBMIT, gbc);
JButton bCLEAR = new JButton(CLEAR);
bCLEAR.addActionListener(this);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 4;
pContPanel.add(bCLEAR, gbc);
sPane.setViewportView(pContPanel);
contentPane.add(sPane, BorderLayout.CENTER);
}
}
</code></pre>
<p>It is being compiled with NO syntax errors.
But, when I run it using an applet viewer(in BlueJ), it says, </p>
<p>exception: java.lang.IllegalArgumentException : adding container's parent to itself.</p>
<p>Can you please help me figure out where is the mistake in my code and in what way can I rectify it?
Thank you.</p> | 0 | 1,849 |
How to make clicking a menu button toggle show/hide of a menu sidebar component | <p>I have this three component app.js, header.js and menu.js. I'm trying to code when you click on menu button which is in header component it toggles (show/hide) menu component (menu-sidebar). Is it possible to make such communication in react with two components without jQuery? I tried with this tutorial but didn't succeed <a href="https://www.codementor.io/chrisharrington/how-to-build-a-sliding-menu-using-react-js-and-less-css-du107mpij" rel="noreferrer">https://www.codementor.io/chrisharrington/how-to-build-a-sliding-menu-using-react-js-and-less-css-du107mpij</a></p>
<p><strong>app.js</strong>:</p>
<pre><code>import React, { Component } from 'react';
// components
import Header from './components/header';
import Menu from './components/menu';
class App extends Component {
render() {
return (
<div className="App">
<Header />
<Menu />
</div>
);
}
}
export default App;
</code></pre>
<p><strong>header.js</strong>:</p>
<pre><code>import React, { Component } from 'react';
class Header extends Component {
render() {
return (
<header id="header">
<h1><a href="/">Lorem</a></h1>
<nav className="links">
<ul>
<li><a href="/">Lorem</a></li>
<li><a href="/">Ipsum</a></li>
<li><a href="/">Feugiat</a></li>
<li><a href="/">Tempus</a></li>
<li><a href="/">Adipiscing</a></li>
</ul>
</nav>
<nav className="main">
<ul>
<li className="search">
search
</li>
<li className="menu">
<a className="fa-bars" href="#menu">Menu</a>
</li>
</ul>
</nav>
</header>
);
}
}
export default Header;
</code></pre>
<p><strong>menu.js</strong>:</p>
<pre><code>import React, { Component } from 'react';
class Menu extends Component {
render() {
return (
<section id="menu">
<section>
<form className="search" method="get" action="#">
<input type="text" name="query" placeholder="Search" />
</form>
</section>
{/* Links */}
<section>
<ul className="links">
<li>
<a href="/">
<h3>Lorem ipsum</h3>
<p>Feugiat tempus veroeros dolor</p>
</a>
</li>
<li>
<a href="/">
<h3>Dolor sit amet</h3>
<p>Sed vitae justo condimentum</p>
</a>
</li>
<li>
<a href="/">
<h3>Feugiat veroeros</h3>
<p>Phasellus sed ultricies mi congue</p>
</a>
</li>
<li>
<a href="/">
<h3>Etiam sed consequat</h3>
<p>Porta lectus amet ultricies</p>
</a>
</li>
</ul>
</section>
</section>
);
}
}
export default Menu;
</code></pre> | 0 | 2,394 |
Mysqli and Php with session login form keep fail | <p>When I hit my submit button to login nothing happens. I am just getting the same page, and not even an error. The connection to db should be fine. I have been looking at the code for 10 hours now, and I cannot figure out why. Does anybody have an idea?</p>
<p>dbconfic.inc.php:</p>
<pre><code><?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "testdb";
// connection:
$mysqli = new mysqli($db_host, $db_user, $db_pass , $db_name);
// tjek conenction:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
// vi kører utf-8 på connection:
$mysqli->set_charset("utf-8");
?>
</code></pre>
<p>index.php:</p>
<pre><code> <?php
include('login.php'); // Include Login Script
if(isset($_SESSION['username']))
{
header('Location: home.php');
}
exit();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Form with Session</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1>PHP Login Form with Session</h1>
<div class="loginBox">
<h3>Login Form</h3>
<br><br>
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" value="Login" />
</form>
<div class="error"><?php echo $error;?></div>
</div>
</body>
</html>
</code></pre>
<p>login.php:</p>
<pre><code><?php
session_start();
include("dbconfic.inc.php"); //Establishing connection with our database
$error = ""; //Variable for storing our errors.
if(isset($_POST["submit"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
//Check username and password from database
$sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: home.php"); // Redirecting To Other Page
}else
{
$error = "Incorrect username or password.";
}
}
}
?>
</code></pre>
<p>home.php:</p>
<pre><code> <?php
include("check.php");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
<br><br><br>
<a href="logout.php" style="font-size:18px">Logout?</a>
</body>
</html>
</code></pre>
<p>check.php:</p>
<pre><code><?php
include('dbconfic.inc.php');
session_start();
$user_check=$_SESSION['username'];
$sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user=$row['username'];
if(!isset($user_check))
{
header("Location: index.php");
}
?>
</code></pre>
<p>logout.php</p>
<pre><code><?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
</code></pre> | 0 | 1,695 |
jsdom: dispatchEvent/addEventListener doesn't seem to work | <p><strong>Summary:</strong></p>
<p>I am attempting to test a React component that listens to native DOM events in its <code>componentWillMount</code>. </p>
<p>I'm finding that jsdom (<code>@8.4.0</code>) doesn't work as expected when it comes to dispatching events and adding event listeners.</p>
<p>The simplest bit of code I can extract:</p>
<pre><code>window.addEventListener('click', () => {
throw new Error("success")
})
const event = new Event('click')
document.dispatchEvent(event)
throw new Error('failure')
</code></pre>
<p>This throws "failure".</p>
<hr>
<p><strong>Context:</strong></p>
<p>At risk of the above being an <a href="https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">XY problem</a>, I want to provide more context.</p>
<p>Here is an extracted/simplified version of the component I'm trying to test. <a href="http://www.webpackbin.com/NktFmumgb" rel="noreferrer">You can see it working on Webpackbin.</a></p>
<pre><code>import React from 'react'
export default class Example extends React.Component {
constructor() {
super()
this._onDocumentClick = this._onDocumentClick.bind(this)
}
componentWillMount() {
this.setState({ clicked: false })
window.addEventListener('click', this._onDocumentClick)
}
_onDocumentClick() {
const clicked = this.state.clicked || false
this.setState({ clicked: !clicked })
}
render() {
return <p>{JSON.stringify(this.state.clicked)}</p>
}
}
</code></pre>
<p>Here is the test I'm trying to write.</p>
<pre><code>import React from 'react'
import ReactDOM from 'react-dom'
import { mount } from 'enzyme'
import Example from '../src/example'
describe('test', () => {
it('test', () => {
const wrapper = mount(<Example />)
const event = new Event('click')
document.dispatchEvent(event)
// at this point, I expect the component to re-render,
// with updated state.
expect(wrapper.text()).to.match(/true/)
})
})
</code></pre>
<p>Just for completeness, here is my <code>test_helper.js</code> which initializes jsdom:</p>
<pre><code>import { jsdom } from 'jsdom'
import chai from 'chai'
const doc = jsdom('<!doctype html><html><body></body></html>')
const win = doc.defaultView
global.document = doc
global.window = win
Object.keys(window).forEach((key) => {
if (!(key in global)) {
global[key] = window[key]
}
})
</code></pre>
<hr>
<p><strong>Reproduction case:</strong></p>
<p>I have a repro case here: <a href="https://github.com/jbinto/repro-jsdom-events-not-firing" rel="noreferrer">https://github.com/jbinto/repro-jsdom-events-not-firing</a></p>
<p><code>
git clone https://github.com/jbinto/repro-jsdom-events-not-firing.git
cd repro-jsdom-events-not-firing
npm install
npm test
</code></p> | 0 | 1,051 |
Eclipse 4.2, Mac OS X 10.8 (ML), and Java 6 | <p>I'm trying to run Eclipse 4.2 (latest from website: eclipse-SDK-4.2-macosx-cocoa-x86_64) on Mac OS X 10.8 (Mountain Lion).</p>
<p>I have Java 7 installed, but I keep getting prompted to install Java 6. When I choose to forgo the install by clicking "Not Now", Eclipse exits.</p>
<pre><code>$ java -version
java version "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b06)
Java HotSpot(TM) 64-Bit Server VM (build 23.1-b03, mixed mode)
$ whereis java
/usr/bin/java
</code></pre>
<p>Any ideas on how to get Eclipse to work with the latest version of Java? README is lacking any useful information (and even claims Eclipse was tested with Java 7 on some platforms).</p>
<hr>
<p>UPDATE:
Running <code>sudo /Applications/.Eclipse/Eclipse.app/Contents/MacOS/eclipse</code> works fine. After running under sudo and then switching back to lowly me with <code>/Applications/.Eclipse/Eclipse.app/Contents/MacOS/eclipse</code> results in a lock file error (permission denied).</p>
<p>It appears I have two problems:</p>
<ul>
<li><p>Running through icon click results in "Need Java 6"</p></li>
<li><p>Running from command line results in "Permission Denied"</p></li>
</ul>
<hr>
<p>UPDATE: It appears to be more junk from Cupertino:</p>
<p>Apple Radar: 12082976</p>
<p>Here's the text that Apple wants to hide from the world:</p>
<p>I purchased a new Mac Book Pro. I immediately upgraded to Mountain Lion. I installed Java 7 from Sun [Oracle]:</p>
<p>$ java -version
java version "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b06)
Java HotSpot(TM) 64-Bit Server VM (build 23.1-b03, mixed mode)</p>
<p>$ whereis java
/usr/bin/java</p>
<p>$ /usr/libexec/java_home
/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home</p>
<p>When I attempt to run the Java Preferences (in /Applications/Utilities) and Eclipse, I get prompted to install Java (see attachment).</p>
<p>This outdated article was no help (adding environment.plist): <a href="https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html" rel="nofollow noreferrer">https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html</a>. I thought the problem might be $JAVA_HOME was not set, but I was wrong.</p>
<p>I think I got more useful information from Stack Overflow rather than the vendor (Apple), but its still not solved. <a href="https://apple.stackexchange.com/questions/58203/mountain-lion-with-java-7-only">https://apple.stackexchange.com/questions/58203/mountain-lion-with-java-7-only</a> and <a href="https://apple.stackexchange.com/questions/57986/multiple-java-versions-support-on-os-x-and-java-home-location">https://apple.stackexchange.com/questions/57986/multiple-java-versions-support-on-os-x-and-java-home-location</a>.</p>
<p>Please fix this. I spends thousands on Apple hardware and hundreds on Apple software, and this sort of thing is not acceptable. I have personally wasted hours on this issue, as have others. How can the Apple QA department miss another gapping hole?</p> | 0 | 1,047 |
android - sharedpreferences return null value | <p>I'm trying to use sharedpreferences to check whether the user logged in before they start using the app. I save the username in shredpreferences when user log in.</p>
<p>Login.java</p>
<pre><code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button btnLogin = (Button) findViewById(R.id.buttonlogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View adapt) {
EditText usernameEditText = (EditText) findViewById(R.id.EditUserName);
userName = usernameEditText.getText().toString();
EditText passwordEditText = (EditText) findViewById(R.id.EditPassword);
userPassword = passwordEditText.getText().toString();
if (userName.matches("") && userPassword.matches("")) {
toast("Please enter Username and Password");
return;
} else if (userName.matches("") || userName.equals("")) {
toast("Please enter Username");
return;
} else if (userPassword.matches("") || userPassword.equals("")) {
toast("Please enter Password");
return;
} else {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MEM1", userName);
editor.commit();
new DownloadFilesTask().execute();
}
}
});
}
private void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
}
protected void onPostExecute(Void result) {
toast("user logged in");
startActivity(new Intent(Login.this, MainActivity.class));
finish();
}
@Override
protected Void doInBackground(Void... params) {
return null;
}
}
}
</code></pre>
<p>and I tried to check the username value before I start my mainactivity.</p>
<pre><code>SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String username =sharedPreferences.getString("MEM1", "");
if(username.equalsIgnoreCase("")||username.length()==0)
{
toast("username is null");
startActivity(new Intent(MainActivity.this, Login.class));
finish();
}
</code></pre>
<p>but the username is always null. Please help. Thanks</p> | 0 | 1,265 |
WCF: The remote server returned an error: (413) Request Entity Too Large | <p>I have a wcf service</p>
<p>there is a method which gets base64 string to upload a file my file's size 100kb it may be larger in time</p>
<p>i got the error message: The remote server returned an error: (413) Request Entity Too Large
while try to get HttpWebResponse</p>
<p>this is my wcf service web.config</p>
<pre><code><system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpTransportSecurity" allowCookies="false" maxReceivedMessageSize="104857600">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" />
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="FHServices.FHSmartService" behaviorConfiguration="ServiceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="FieldHoundServices.IFHSmartService" behaviorConfiguration="web">
</endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost/FHServices/FHSmartService.svc/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</code></pre>
<p>what is my mistake?</p>
<hr />
<h3>solved</h3>
<p>i found my mistake
i remove these codes</p>
<pre><code><security mode="Transport">
<transport clientCredentialType="None" />
</security>
</code></pre>
<p>i think transport mode for https and we have no ssl so we dont need transport mode. anyway after i remove it, everything seems ok now</p> | 0 | 1,105 |
No suitable driver found for "jdbc:oracle:thin:@**** "oracle/jdbc/driver/OracleDriver"; | <p>here is my java code </p>
<pre><code>public static Map<String,String> propertyFileReader() {
Map<String, String> map=new HashMap<String, String>();
Properties prop = new Properties();
try {
InputStream inputStream = Util.class.getClassLoader().getResourceAsStream("jdbc.properties");
prop.load(inputStream);
final String DB_DRIVER= prop.getProperty("DB_DRIVER");
final String DB_CONNECTION = prop.getProperty("DB_CONNECTION2");
final String DB_USER = prop.getProperty("DB_USER");
final String DB_PASSWORD = prop.getProperty("DB_PASSWORD");
map.put("DB_DRIVER",DB_DRIVER);
map.put("DB_CONNECTION",DB_CONNECTION);
map.put("DB_USER",DB_USER);
map.put("DB_PASSWORD",DB_PASSWORD);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
private static Connection getDBConnection() {
Map<String , String > map=new HashMap<String, String>();
map=propertyFileReader();
String DB_DRIVER=map.get("DB_DRIVER");
String DB_CONNECTION= map.get("DB_CONNECTION");
String DB_USER=map.get("DB_USER");
String DB_PASSWORD=map.get("DB_PASSWORD");
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_CONNECTION,DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
</code></pre>
<p>here is my properties file</p>
<pre><code>DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
DB_CONNECTION2 = "jdbc:oracle:thin:@10.2.5.23:1521:dbslic";
DB_USER = "TSR_MOBILE";
DB_PASSWORD = "TSR_MOBILE";
</code></pre>
<p>and i added ojdbc6.jar to my buildpath [tried with ojdbc14.jar also] </p>
<p>but there is a error says like below</p>
<pre><code>No suitable driver found for "jdbc:oracle:thin:@10.2.5.23:1521:dbslic";
"oracle/jdbc/driver/OracleDriver";
No suitable driver found for "jdbc:oracle:thin:@10.2.5.23:1521:dbslic";
[ERROR] Exception occurred while trying to invoke service method loginBlock
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:212)
at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:117)
at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:114)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:181)
at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:146)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at mainService.TSR_WEB_SERVICE.loginBlock(TSR_WEB_SERVICE.java:416)
... 25 more
</code></pre>
<p>please help me to sort out this issue</p> | 0 | 1,803 |
Django 1.7 app config ImportError: No module named appname.apps | <p>I'm trying to setup a custom application configuration for one of my Django app called 'articles' following the documentation at <a href="https://docs.djangoproject.com/en/dev/ref/applications/" rel="noreferrer">https://docs.djangoproject.com/en/dev/ref/applications/</a>, but I keep getting <code>ImportError: No module named articles.apps</code> when execute <code>./manage.py check</code> (or any other management command such as <code>./manage.py runserver</code>)</p>
<p>This is a tree of the project</p>
<pre><code>projectname
├── apps
│ ├── articles
│ │ ├── admin.py
│ │ ├── apps.py
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── 0001_initial.py
│ │ │ └── __init__.py
│ │ ├── models.py
│ │ ├── templates
│ │ │ └── articles
│ │ ├── templatetags
│ │ │ ├── articles_tags.py
│ │ │ └── __init__.py
│ │ ├── tests.py
│ │ ├── urls.py
│ │ └── views.py
│ ├── __init__.py
</code></pre>
<p>installed app in <strong>settings.py</strong>:</p>
<pre class="lang-py prettyprint-override"><code>INSTALLED_APPS = (
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'grappelli.dashboard',
'mptt',
'sekizai',
'pytils',
'sorl.thumbnail',
'sefaro.apps.utils',
'sefaro.apps.seo',
'sefaro.apps.staticpages',
'sefaro.apps.statictext',
'sefaro.apps.usersettings',
'sefaro.apps.navigation',
'sefaro.apps.slideshow',
'sefaro.apps.articles',
)
</code></pre>
<p>Contents of <code>articles/__init__.py</code>:</p>
<pre><code># articles/__init__.py
default_app_config = 'articles.apps.ArticlesConfig'
</code></pre>
<p>Contents of <code>articles/apps.py</code>:</p>
<pre><code># -*- coding: utf-8 -*-
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class ArticlesConfig(AppConfig):
name = 'articles'
verbose_name = _(u'Articles')
</code></pre>
<p>And I have <code>'projectname.apps.articles'</code> in my <code>INSTALLED_APPS</code></p>
<p>Just to ensure that I really have all these files and haven't messed up with paths</p>
<pre><code>>>> from projectname.apps.articles.apps import ArticlesConfig
>>> ArticlesConfig
<class 'projectname.apps.articles.apps.ArticlesConfig'>
</code></pre>
<p>Everything imports just fine...</p>
<p>But:</p>
<pre><code>(vagrant)vagrant@vagrant-ubuntu-trusty-32:~/django$ ./manage.py check
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/vagrant/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/vagrant/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/home/vagrant/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/vagrant/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/home/vagrant/local/lib/python2.7/site-packages/django/apps/config.py", line 112, in create
mod = import_module(mod_path)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named articles.apps
</code></pre> | 0 | 1,435 |
Unable to stop Streaming in tweepy after one minute | <p>I am trying to stream twitter data for a period of time of say 5 minutes, using the Stream.filter() method. I am storing the retrieved tweets in a JSON file. The problem is I am unable to stop the filter() method from within the program. I need to stop the execution manually. I tried stopping the data based on system time using the time package. I was able to stop writing tweets to the JSON file but the stream method is still going on, but It was not able to continue to the next line of code.
I am using IPython notebook to write and execute the code.
Here's the code:</p>
<pre><code>auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
from tweepy import Stream
from tweepy.streaming import StreamListener
class MyListener(StreamListener):
def __init__(self, start_time, time_limit=60):
self.time = start_time
self.limit = time_limit
def on_data(self, data):
while (time.time() - self.time) < self.limit:
try:
saveFile = open('abcd.json', 'a')
saveFile.write(data)
saveFile.write('\n')
saveFile.close()
return True
except BaseException as e:
print 'failed ondata,', str(e)
time.sleep(5)
return True
def on_status(self, status):
if (time.time() - self.time) >= self.limit:
print 'time is over'
return false
def on_error(self, status):
if (time.time() - self.time) >= self.limit:
print 'time is over'
return false
else:
print(status)
return True
start_time = time.time()
stream_data = Stream(auth, MyListener(start_time,20))
stream_data.filter(track=['name1','name2',...list ...,'name n'])#list of the strings I want to track
</code></pre>
<p>These links are similar but I does not answer my question directly</p>
<p><a href="https://stackoverflow.com/questions/28701962/tweepy-stream-data-for-x-minutes">Tweepy: Stream data for X minutes?</a></p>
<p><a href="https://stackoverflow.com/questions/24663403/stopping-tweepy-steam-after-a-duration-parameter-lines-seconds-tweets-etc">Stopping Tweepy steam after a duration parameter (# lines, seconds, #Tweets, etc)</a></p>
<p><a href="https://stackoverflow.com/questions/20863486/tweepy-streaming-stop-collecting-tweets-at-x-amount">Tweepy Streaming - Stop collecting tweets at x amount</a></p>
<p>I used this link as my reference,
<a href="http://stats.seandolinar.com/collecting-twitter-data-using-a-python-stream-listener/" rel="noreferrer">http://stats.seandolinar.com/collecting-twitter-data-using-a-python-stream-listener/</a></p> | 0 | 1,075 |
C# Deserialize JSON to List | <p>I have come across a problem I don't understand when trying to deserialize a JSON string (containing multiple objects) into a List. Here is the JSON.</p>
<pre class="lang-json prettyprint-override"><code>[
{
"id":2,
"name":"Race 1",
"raceDateTime":"2017-09-02T14:27:39.654",
"raceStartTime":"2017-09-02T14:27:39.654",
"description":"string",
"maxEntries":0,
"currentEntries":0,
"status":0
},
{
"id":3,
"name":"Race 2",
"raceDateTime":"2017-09-02T14:27:39.654",
"raceStartTime":"2017-09-02T14:27:39.654",
"description":"string",
"maxEntries":0,
"currentEntries":0,
"status":0
},
{
"id":4,
"name":"Race 3",
"raceDateTime":"2017-09-02T14:27:39.654",
"raceStartTime":"2017-09-02T14:27:39.654",
"description":"string",
"maxEntries":0,
"currentEntries":0,
"status":0
},
{
"id":5,
"name":"Race 4",
"raceDateTime":"2017-09-02T14:27:39.654",
"raceStartTime":"2017-09-02T14:27:39.654",
"description":"string",
"maxEntries":0,
"currentEntries":0,
"status":0
}
]
</code></pre>
<p>I then have the JSON parameters matching my Model.</p>
<pre class="lang-cs prettyprint-override"><code>public class RaceModel
{
public int id { get; set; }
public string name { get; set; }
public DateTime raceDateTime { get; set; }
public DateTime raceStartTime { get; set; }
public string description { get; set; }
public int maxEntries { get; set; }
public int currentEntries { get; set; }
public int status { get; set; }
}
public class RaceList
{
public List<RaceList> racelist { get; set; }
}
</code></pre>
<p>And my code to get the JSON from the REST API request is below:</p>
<pre class="lang-cs prettyprint-override"><code>string APIServer = Application.Current.Properties["APIServer"].ToString();
string Token = Application.Current.Properties["Token"].ToString();
var client = new RestClient(APIServer);
var request = new RestRequest("api/race", Method.GET);
request.AddHeader("Content-type", "application/json");
request.AddHeader("Authorization", "Bearer " + Token);
var response = client.Execute(request) as RestResponse;
var raceobject = JsonConvert.DeserializeObject<RaceList>(response.Content);
</code></pre>
<p>But I get this error (Using Newtonsoft.JSON)</p>
<pre><code>Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TechsportiseApp.API.Models.RaceList' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
</code></pre>
<p>I'd like to have a list/collection of objects I can then iterate through and work with.</p>
<p>Can anyone advise what I've done wrong?</p> | 0 | 1,218 |
How does one use Pytorch (+ cuda) with an A100 GPU? | <p>I was trying to use my current code with an A100 gpu but I get this error:</p>
<pre><code>---> backend='nccl'
/home/miranda9/miniconda3/envs/metalearningpy1.7.1c10.2/lib/python3.8/site-packages/torch/cuda/__init__.py:104: UserWarning:
A100-SXM4-40GB with CUDA capability sm_80 is not compatible with the current PyTorch installation.
The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_61 sm_70 sm_75 compute_37.
If you want to use the A100-SXM4-40GB GPU with PyTorch, please check the instructions at https://pytorch.org/get-started/locally/
</code></pre>
<p>which is reather confusing because it points to the usual pytorch installation but doesn't tell me which combination of pytorch version + cuda version to use for my specific hardware (A100). What is the right way to install pytorch for an A100?</p>
<hr />
<p>These are some versions I've tried:</p>
<pre><code># conda install -y pytorch==1.8.0 torchvision cudatoolkit=10.2 -c pytorch
# conda install -y pytorch torchvision cudatoolkit=10.2 -c pytorch
#conda install -y pytorch==1.7.1 torchvision torchaudio cudatoolkit=10.2 -c pytorch -c conda-forge
# conda install -y pytorch==1.6.0 torchvision cudatoolkit=10.2 -c pytorch
#conda install -y pytorch==1.7.1 torchvision torchaudio cudatoolkit=11.1 -c pytorch -c conda-forge
# conda install pytorch torchvision torchaudio cudatoolkit=11.0 -c pytorch
# conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c conda-forge
# conda install -y pytorch torchvision cudatoolkit=9.2 -c pytorch # For Nano, CC
# conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c conda-forge
</code></pre>
<hr />
<p>note that this can be subtle because I've had this error with this machine + pytorch version in the past:</p>
<p><a href="https://stackoverflow.com/questions/66807131/how-to-solve-the-famous-unhandled-cuda-error-nccl-version-2-7-8-error">How to solve the famous `unhandled cuda error, NCCL version 2.7.8` error?</a></p>
<hr />
<h1>Bonus 1:</h1>
<p>I still have errors:</p>
<pre><code>ncclSystemError: System call (socket, malloc, munmap, etc) failed.
Traceback (most recent call last):
File "/home/miranda9/diversity-for-predictive-success-of-meta-learning/div_src/diversity_src/experiment_mains/main_dist_maml_l2l.py", line 1423, in <module>
main()
File "/home/miranda9/diversity-for-predictive-success-of-meta-learning/div_src/diversity_src/experiment_mains/main_dist_maml_l2l.py", line 1365, in main
train(args=args)
File "/home/miranda9/diversity-for-predictive-success-of-meta-learning/div_src/diversity_src/experiment_mains/main_dist_maml_l2l.py", line 1385, in train
args.opt = move_opt_to_cherry_opt_and_sync_params(args) if is_running_parallel(args.rank) else args.opt
File "/home/miranda9/ultimate-utils/ultimate-utils-proj-src/uutils/torch_uu/distributed.py", line 456, in move_opt_to_cherry_opt_and_sync_params
args.opt = cherry.optim.Distributed(args.model.parameters(), opt=args.opt, sync=syn)
File "/home/miranda9/miniconda3/envs/meta_learning_a100/lib/python3.9/site-packages/cherry/optim.py", line 62, in __init__
self.sync_parameters()
File "/home/miranda9/miniconda3/envs/meta_learning_a100/lib/python3.9/site-packages/cherry/optim.py", line 78, in sync_parameters
dist.broadcast(p.data, src=root)
File "/home/miranda9/miniconda3/envs/meta_learning_a100/lib/python3.9/site-packages/torch/distributed/distributed_c10d.py", line 1090, in broadcast
work = default_pg.broadcast([tensor], opts)
RuntimeError: NCCL error in: ../torch/lib/c10d/ProcessGroupNCCL.cpp:911, unhandled system error, NCCL version 2.7.8
</code></pre>
<p>one of the answers suggested to have nvcca & pytorch.version.cuda to match but they do not:</p>
<pre><code>(meta_learning_a100) [miranda9@hal-dgx ~]$ python -c "import torch;print(torch.version.cuda)"
11.1
(meta_learning_a100) [miranda9@hal-dgx ~]$ nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2020 NVIDIA Corporation
Built on Wed_Jul_22_19:09:09_PDT_2020
Cuda compilation tools, release 11.0, V11.0.221
Build cuda_11.0_bu.TC445_37.28845127_0
</code></pre>
<p>How do I match them? I this the error? Can someone display their pip, conda and nvcca version to see what set up works?</p>
<p>More error messages:</p>
<pre><code>hal-dgx:21797:21797 [0] NCCL INFO Bootstrap : Using [0]enp226s0:141.142.153.83<0> [1]virbr0:192.168.122.1<0>
hal-dgx:21797:21797 [0] NCCL INFO NET/Plugin : No plugin found (libnccl-net.so), using internal implementation
hal-dgx:21797:21797 [0] NCCL INFO NET/IB : Using [0]mlx5_0:1/IB [1]mlx5_1:1/IB [2]mlx5_2:1/IB [3]mlx5_3:1/IB [4]mlx5_4:1/IB [5]mlx5_5:1/IB [6]mlx5_6:1/IB [7]mlx5_7:1/IB ; OOB enp226s0:141.142.153.83<0>
hal-dgx:21797:21797 [0] NCCL INFO Using network IB
NCCL version 2.7.8+cuda11.1
hal-dgx:21805:21805 [2] NCCL INFO Bootstrap : Using [0]enp226s0:141.142.153.83<0> [1]virbr0:192.168.122.1<0>
hal-dgx:21799:21799 [1] NCCL INFO Bootstrap : Using [0]enp226s0:141.142.153.83<0> [1]virbr0:192.168.122.1<0>
hal-dgx:21805:21805 [2] NCCL INFO NET/Plugin : No plugin found (libnccl-net.so), using internal implementation
hal-dgx:21799:21799 [1] NCCL INFO NET/Plugin : No plugin found (libnccl-net.so), using internal implementation
hal-dgx:21811:21811 [3] NCCL INFO Bootstrap : Using [0]enp226s0:141.142.153.83<0> [1]virbr0:192.168.122.1<0>
hal-dgx:21811:21811 [3] NCCL INFO NET/Plugin : No plugin found (libnccl-net.so), using internal implementation
hal-dgx:21811:21811 [3] NCCL INFO NET/IB : Using [0]mlx5_0:1/IB [1]mlx5_1:1/IB [2]mlx5_2:1/IB [3]mlx5_3:1/IB [4]mlx5_4:1/IB [5]mlx5_5:1/IB [6]mlx5_6:1/IB [7]mlx5_7:1/IB ; OOB enp226s0:141.142.153.83<0>
hal-dgx:21811:21811 [3] NCCL INFO Using network IB
hal-dgx:21799:21799 [1] NCCL INFO NET/IB : Using [0]mlx5_0:1/IB [1]mlx5_1:1/IB [2]mlx5_2:1/IB [3]mlx5_3:1/IB [4]mlx5_4:1/IB [5]mlx5_5:1/IB [6]mlx5_6:1/IB [7]mlx5_7:1/IB ; OOB enp226s0:141.142.153.83<0>
hal-dgx:21805:21805 [2] NCCL INFO NET/IB : Using [0]mlx5_0:1/IB [1]mlx5_1:1/IB [2]mlx5_2:1/IB [3]mlx5_3:1/IB [4]mlx5_4:1/IB [5]mlx5_5:1/IB [6]mlx5_6:1/IB [7]mlx5_7:1/IB ; OOB enp226s0:141.142.153.83<0>
hal-dgx:21799:21799 [1] NCCL INFO Using network IB
hal-dgx:21805:21805 [2] NCCL INFO Using network IB
hal-dgx:21797:27906 [0] misc/ibvwrap.cc:280 NCCL WARN Call to ibv_create_qp failed
hal-dgx:21797:27906 [0] NCCL INFO transport/net_ib.cc:360 -> 2
hal-dgx:21797:27906 [0] NCCL INFO transport/net_ib.cc:437 -> 2
hal-dgx:21797:27906 [0] NCCL INFO include/net.h:21 -> 2
hal-dgx:21797:27906 [0] NCCL INFO include/net.h:51 -> 2
hal-dgx:21797:27906 [0] NCCL INFO init.cc:300 -> 2
hal-dgx:21797:27906 [0] NCCL INFO init.cc:566 -> 2
hal-dgx:21797:27906 [0] NCCL INFO init.cc:840 -> 2
hal-dgx:21797:27906 [0] NCCL INFO group.cc:73 -> 2 [Async thread]
hal-dgx:21811:27929 [3] misc/ibvwrap.cc:280 NCCL WARN Call to ibv_create_qp failed
hal-dgx:21811:27929 [3] NCCL INFO transport/net_ib.cc:360 -> 2
hal-dgx:21811:27929 [3] NCCL INFO transport/net_ib.cc:437 -> 2
hal-dgx:21811:27929 [3] NCCL INFO include/net.h:21 -> 2
hal-dgx:21811:27929 [3] NCCL INFO include/net.h:51 -> 2
hal-dgx:21811:27929 [3] NCCL INFO init.cc:300 -> 2
hal-dgx:21811:27929 [3] NCCL INFO init.cc:566 -> 2
hal-dgx:21811:27929 [3] NCCL INFO init.cc:840 -> 2
hal-dgx:21811:27929 [3] NCCL INFO group.cc:73 -> 2 [Async thread]
</code></pre>
<p>after putting</p>
<pre><code>import os
os.environ["NCCL_DEBUG"] = "INFO"
</code></pre> | 0 | 3,436 |
How to scroll a React page when it loads? | <p>I want to pass a value as the hash in the url (myapp.com#somevalue) and have the page scroll to that item when the page loads - exactly the behavior of using a hash fragment since the beginning of the internet. I tried using scrollIntoView but that fails on iOS. Then I tried just unsetting/setting window.location.hash but there seems to be a race condition. It only works when the delay is more than 600ms.</p>
<p>I would like a more solid solution and don't want to introduce an unnecessary delay. When the delay is too short, it appears to scroll to the desired item but then scrolls to the top of the page. You won't see the effect on this demo but it happens in my actual app <a href="https://codesandbox.io/s/pjok544nrx" rel="noreferrer">https://codesandbox.io/s/pjok544nrx</a> line 75</p>
<pre><code> componentDidMount() {
let self = this;
let updateSearchControl = hash => {
let selectedOption = self.state.searchOptions.filter(
option => option.value === hash
)[0];
if (selectedOption) {
// this doesn't work with Safari on iOS
// document.getElementById(hash).scrollIntoView(true);
// this works if delay is 900 but not 500 ms
setTimeout(() => {
// unset and set the hash to trigger scrolling to target
window.location.hash = null;
window.location.hash = hash;
// scroll back by the height of the Search box
window.scrollBy(
0,
-document.getElementsByClassName("heading")[0].clientHeight
);
}, 900);
} else if (hash) {
this.searchRef.current.select.focus();
}
};
// Get the hash
// I want this to work as a Google Apps Script too which runs in
// an iframe and has a special way to get the hash
if (!!window["google"]) {
let updateHash = location => {
updateSearchControl(location.hash);
};
eval("google.script.url.getLocation(updateHash)");
} else {
let hash = window.location.hash.slice(1);
updateSearchControl(hash);
}
}
</code></pre>
<p>EDIT: I tracked down the line of React that re-renders the page and consequently resets the scroll position after it already scrolled where I told it to go in componentDidMount(). It's <a href="https://github.com/facebook/react/blob/21d5f7d32d5becf5c8e986ff0202059be643dc15/packages/react-dom/src/shared/CSSPropertyOperations.js#L82" rel="noreferrer">this one</a>.
<code>style[styleName] = styleValue;</code> At the time the page is re-rendered it is setting the width style property of the inputbox component of the react-select box component. The stack trace right before it does this looks like</p>
<pre><code>(anonymous) @ VM38319:1
setValueForStyles @ react-dom.development.js:6426
updateDOMProperties @ react-dom.development.js:7587
updateProperties @ react-dom.development.js:7953
commitUpdate @ react-dom.development.js:8797
commitWork @ react-dom.development.js:17915
commitAllHostEffects @ react-dom.development.js:18634
callCallback @ react-dom.development.js:149
invokeGuardedCallbackDev @ react-dom.development.js:199
invokeGuardedCallback @ react-dom.development.js:256
commitRoot @ react-dom.development.js:18867
(anonymous) @ react-dom.development.js:20372
unstable_runWithPriority @ scheduler.development.js:255
completeRoot @ react-dom.development.js:20371
performWorkOnRoot @ react-dom.development.js:20300
performWork @ react-dom.development.js:20208
performSyncWork @ react-dom.development.js:20182
requestWork @ react-dom.development.js:20051
scheduleWork @ react-dom.development.js:19865
scheduleRootUpdate @ react-dom.development.js:20526
updateContainerAtExpirationTime @ react-dom.development.js:20554
updateContainer @ react-dom.development.js:20611
ReactRoot.render @ react-dom.development.js:20907
(anonymous) @ react-dom.development.js:21044
unbatchedUpdates @ react-dom.development.js:20413
legacyRenderSubtreeIntoContainer @ react-dom.development.js:21040
render @ react-dom.development.js:21109
(anonymous) @ questionsPageIndex.jsx:10
./src/client/questionsPageIndex.jsx @ index.html:673
__webpack_require__ @ index.html:32
(anonymous) @ index.html:96
(anonymous) @ index.html:99
</code></pre>
<p>I don't know where to move my instruction to scroll the page. It has to happen after these styles are set which is happening after componentDidMount().</p>
<p>EDIT: I need to better clarify exactly what I need this to do. Apologies for not doing that before.</p>
<h3>Must haves</h3>
<p>This has to work on all common desktop and mobile devices.</p>
<p>When the page loads there could be three situations depending on what query is provided in the url after the #: </p>
<ul>
<li>1) no query was provided - nothing happens</li>
<li>2) a valid query was provided - the page scrolls instantly to the desired anchor and the page's title changes to the label of the option</li>
<li>3) an invalid query was provided - the query is entered into the search box, the search box is focused and the menu opens with options limited by the provided query as if they had been typed in. The cursor is located in the search box at the end of the query so the user can modify the query.</li>
</ul>
<p>A valid query is one that matches the value of one of the options. An invalid query is one that doesn't.</p>
<p>The browser back and forward buttons should move the scroll position accordingly.</p>
<p>Any time an option is chosen from the Search box the page should scroll instantly to that anchor, the query should clear returning to the placeholder "Search...", the url should update, and the document's title should change to the option's label.</p>
<h3>Optional but would be great</h3>
<p>After making a selection the menu closes and the query goes back to "Search...", and either</p>
<ul>
<li>the Search box retains the focus so the user can begin typing another query. The next time it is <strong>clicked</strong>, the menu opens, and the Searchbox query from before the selection, the menu's filter and the menu scroll position are restored (most preferred), or</li>
<li>the Search box loses focus. The next time it is <strong>focused</strong>, the menu opens, and the Search box query from before the selection, the menu's filter and the menu scroll position are restored (preferred), or</li>
<li>the Search box retains the focus so the user can begin typing another query. The prior query and menu scroll position are lost.</li>
</ul> | 0 | 2,119 |
Android ExpandableListView with Checkbox, Controlling checked state | <p>Friends,</p>
<p>I am trying to write a application which use checkbox in ExpandableListView, I got a problem here which is maintaining checkbox state of the application, I got the example from <a href="http://mylifewithandroid.blogspot.com/2010/02/expandable-lists-and-check-boxes.html" rel="noreferrer">here</a> , my problem is maintaining checked state of the checkboxes, whenever I check one of the checkboxes and Expand the List, the checkboxes do not have the checked state where they supposed to have. I have try to maintain by adding ArrayList to store the position of the store and reload the position in getChildView() but still not achieve what I want to do. here is my code </p>
<pre><code>public class ElistCBox extends ExpandableListActivity {
private static final String LOG_TAG = "ElistCBox";
ArrayList<String > chkState = new ArrayList<String>();
static final String colors[] = {"grey","blue","yellow","red"};
static final String shades[][] ={ { "lightgrey","#D3D3D3","dimgray","#696969", "sgi >gray 92","#EAEAEA"},
{ "dodgerblue 2","#1C86EE","steelblue >2","#5CACEE","powderblue","#B0E0E6"},
{ "yellow 1","#FFFF00", "gold 1","#FFD700","darkgoldenrod 1"," #FFB90F" },
{"indianred 1","#FF6A6A", "firebrick 1","#FF3030", "maroon","#800000" } };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter(
this,
createGroupList(),
R.layout.group_row, new String[] { "colorName" },
new int[] { R.id.childname }, createChildList(),
R.layout.child_row,
new String[] { "shadeName", "rgb" },
new int[] { R.id.childname, R.id.rgb }
) {
@Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
final CheckBox chkColor = (CheckBox)v.findViewById(R.id.check1);
if(chkState.contains(groupPosition+","+childPosition)){
chkColor.setChecked(true);
}else{
chkColor.setChecked(false);
}
chkColor.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.e("Checkbox Onclick Listener", Integer.toString(groupPosition) + " - " + Integer.toString(childPosition));
}
});
chkColor.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("Checkbox check change Listener", Integer.toString(groupPosition) + " - " + Integer.toString(childPosition));
if(chkColor.isChecked()){
chkState.add(groupPosition+","+childPosition);
} else {
chkState.remove(groupPosition+","+childPosition);
}
}
});
return super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
}
};
setListAdapter( expListAdapter );
}
public void onContentChanged () {
super.onContentChanged();
Log.e( LOG_TAG, "onContentChanged" );
}
public boolean onChildClick(
ExpandableListView parent,
View v,
int groupPosition,
int childPosition,
long id) {
Log.e( LOG_TAG, "onChildClick: "+childPosition );
CheckBox cb = (CheckBox)v.findViewById( R.id.check1 );
if( cb != null )
cb.toggle();
return false;
}
public void onGroupExpand (int groupPosition) {
Log.e( LOG_TAG,"onGroupExpand: "+groupPosition );
}
private List createGroupList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < colors.length ; ++i ) {
HashMap m = new HashMap();
m.put( "colorName",colors[i] );
result.add( m );
}
return (List)result;
}
private List createChildList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < shades.length ; ++i ) {
ArrayList secList = new ArrayList();
for( int n = 0 ; n < shades[i].length; n += 2 ) {
HashMap child = new HashMap();
child.put( "shadeName", shades[i][n] );
child.put( "rgb", shades[i][n+1] ); secList.add( child );
}
result.add( secList );
}
return result;
}
}
</code></pre> | 0 | 2,322 |
still error Android: Unable to start activity ComponentInfo{/com.}: android.view.InflateException: Binary XML file line Error inflating class fragment | <p>I created first version of my application using Google Maps Android v1 API. But now When I released my application for second version, Google map stopped working. I think it's because of it's deprecated.</p>
<p>So now I'm trying to create sample Android application to use Google Map using this <a href="https://developers.google.com/maps/documentation/android/start#getting_the_google_maps_android_api_v2" rel="nofollow noreferrer"><strong>link</strong></a>.</p>
<p>First I was trying with this <strong><a href="https://stackoverflow.com/questions/15757106/android-unable-to-start-activity-componentinfo-com-android-view-inflateexce#">code</a></strong> </p>
<p>But as I suggested to use SupportMapFragment with FragmentActivity, I changed my xml code to</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginRight="150dp" />
</RelativeLayout>
</code></pre>
<p>and imported FragmentActivity instead of Activity, and now I'm getting error</p>
<pre><code> FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testmap/com.example.testmap.MainActivity}: android.view.InflateException: Binary XML file line #16: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #16: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:587)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:209)
at android.app.Activity.setContentView(Activity.java:1657)
at com.example.testmap.MainActivity.onCreate(MainActivity.java:12)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
... 11 more
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.SupportMapFragment: make sure class name exists, is public, and has an empty constructor that is public
at android.support.v4.app.Fragment.instantiate(Fragment.java:401)
at android.support.v4.app.Fragment.instantiate(Fragment.java:369)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:272)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
... 20 more
Caused by: java.lang.ClassNotFoundException: com.google.android.gms.maps.SupportMapFragment in loader dalvik.system.PathClassLoader[/data/app/com.example.testmap-2.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.support.v4.app.Fragment.instantiate(Fragment.java:391)
</code></pre> | 0 | 1,531 |
Elasticsearch Java API Index Document | <ol>
<li><p>Downloaded .90.6, Unpacked, moved Elastic Search to /usr/share/elasticsearch (with chmod 777 -R permissions on centosx64 6.4), renamed cluster to <em>somethingstupid</em> and started server.</p></li>
<li><p>Installed plugins <a href="https://github.com/mobz/elasticsearch-head" rel="nofollow">ESHead</a> and <a href="https://github.com/OlegKunitsyn/elasticsearch-browser" rel="nofollow">ESBrowser</a> b/c Im new and need it (am used to Solr's nice ui). This way I know the server is running too.</p></li>
<li><p>I can create an index via curl : <code>curl -XPOST 'http://localhost:9200/testindex'</code> and delete it too: <code>curl -XDELETE 'http://localhost:9200/testindex'</code></p></li>
</ol>
<p>When I try creating a new index and indexing a document of type article and viewing it via Java API, eclipse runs the code, shows basic logging in the console, and then closes with no errors. Also, inside my logs the latest line just shows that I have started up elastic search but nothing else. Its like the code isnt even reaching elastic search. No indexes or articles show up after I run the java api. What am I missing? </p>
<pre><code>import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;
import static org.elasticsearch.node.NodeBuilder.*;
public class PostES {
public static void main (String args[]){
PostES p = new PostES();
p.postElasticSearch();
}
public static Map<String, Object> putJsonDocument(String title, String content, Date postDate, String author){
Map<String, Object> jsonDocument = new HashMap<String, Object>();
jsonDocument.put("title", title);
jsonDocument.put("conten", content);
jsonDocument.put("postDate", postDate);
jsonDocument.put("author", author);
return jsonDocument;
}
private void postElasticSearch(){
Node node = nodeBuilder().node();
Client client = node.client();
client.prepareIndex("testindex", "article")
.setSource(putJsonDocument("Example Title",
"This description is so important. You don't even know!",
new Date(),
"J.R."))
.execute().actionGet();
node.close();
}
}
</code></pre>
<p>My Source: <a href="http://java.dzone.com/articles/elasticsearch-java-api" rel="nofollow">http://java.dzone.com/articles/elasticsearch-java-api</a>. Everything else including the elastic documentation failed one way or another....(The method jsonBuilder() is undefined for the type PostES).</p>
<p>According to documentation I should be able to do this. But it does nothing either:</p>
<pre><code>import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;
public class TestPostMethod2 {
public static void main(String[] args) {
Node node = nodeBuilder().local(true).node();
Client client = node.client();
String json =
"{\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elastic Search\"}";
IndexResponse response = client.prepareIndex("testindex", "article")
.setSource(json)
.execute()
.actionGet();
}
}
</code></pre> | 0 | 1,511 |
Insert data in h2 database through data.sql file before performing unit testing in spring boot | <p>I want to perform unit testing in spring boot+ JPA. For that I created configuration file to create bean for dataSource, all hibernate properties, entityManagerFactory and transactionManager. Everything going perfect. Tables are getting created by model classes. but now I want to insert data in all tables of database for testing through data.sql file.
I kept data.sql file in src/main/resources but it not loading the file.
So how can I load data in h2 database before starting with unit testing. </p>
<p>This is my cofiguration file - </p>
<pre><code>
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.cfg.Environment;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = "base_package_name")
@EnableTransactionManagement
public class JPAConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1");
/*dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
dataSource.setUrl("jdbc:hsqldb:mem:testdb");*/
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.put("hibernate.hbm2ddl.auto", "create");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "false");
return properties;
}
@Bean(name="entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){
LocalContainerEntityManagerFactoryBean lcemfb
= new LocalContainerEntityManagerFactoryBean();
lcemfb.setDataSource(this.dataSource());
lcemfb.setPackagesToScan(new String[] {"Package_to_scan"});
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
lcemfb.setJpaVendorAdapter(va);
lcemfb.setJpaProperties(this.hibernateProperties());
lcemfb.afterPropertiesSet();
return lcemfb;
}
@Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(
this.entityManagerFactoryBean().getObject() );
return tm;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
}
</code></pre> | 0 | 1,222 |
Compilation error in Android Studio When making a simple Google Android Maps API v2 project | <p>Recently I migrated to the New <strong>Android Studio IDE</strong> based on IntelliJ</p>
<p>The Guides i followed were:</p>
<ol>
<li><p><a href="https://developers.google.com/maps/documentation/android/start" rel="nofollow noreferrer">https://developers.google.com/maps/documentation/android/start</a> (<em>for
basics</em>)</p></li>
<li><p><a href="https://stackoverflow.com/questions/16596715/how-can-i-create-an-android-application-in-android-studio-that-uses-the-google-m">How can I create an Android application in Android Studio that uses the Google Maps Api v2?</a>
(<em>for importing the required Google Play services and support
libraries into android studio</em>)</p></li>
</ol>
<p>All the libraries were properly detected by Android Studio and i didn't get any 'library not found errors'. The project was shown error free. Then when i tried to compile it i got this error.</p>
<pre><code>Gradle:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':AID-AmritaInfoDesk:compileDebug'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Could not execute build using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.6-bin.zip'.
</code></pre>
<p>This was my <strong>explorer.java</strong> file</p>
<pre><code>package com.aid.explorer;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class explorer extends FragmentActivity {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.explorer);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
</code></pre>
<p>And this was my <strong>explorer.xml</strong> file</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</code></pre>
<p>I would like to know what went wrong. any help would be <em>greatly</em> appreciated</p> | 0 | 1,218 |
Open PDF returned by REST Web Service | <p>I have a JAXB REST Web Service getting in request a POST of a JSON and should return a PDF document in response:</p>
<pre><code>@POST
@Path("getReceipt")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ "application/pdf" })
public Response getReceipt(InputStream incomingData, @Context HttpServletRequest httpRequest) {
...
}
</code></pre>
<p>I'm trying to test it with Advanced Rest Client (Google Chrome plugin), which is showing the following as response:</p>
<pre><code>%PDF-1.4
%����
3 0 obj
<</C[0 0 1]/Border[0 0 0]/A<</URI(https://www.totalerg.it/)/S/URI>>/Subtype/Link/Rect[491.43 723.5 557 733.5]>>
endobj
4 0 obj
<</C[0 0 1]/Border[0 0 0]/A<</URI(https://www.totalerg.it/)/S/URI>>/Subtype/Link/Rect[256.65 274.5 322.22 284.5]>>
endobj
5 0 obj
<</Length 993/Filter/FlateDecode>>stream
x��U�n�8}�W�[��Ð����lG�j�릲�}Y0kpaK�,%���s�3vHY����"9�̙G/%>�9��gD������ҙ;�( \|:+WP�h�|D�zo�����)������h�������L2CR��a�%L�
���:��&��g L���1ϲ�Oq���9M�[<�-�ǹ����r���
wL�2�:W�m#��J��\*��":��Ld7�]
�3�6�E��Kn_<�}�;���,��g�����uk��D^O��6~��Y����]�=1ٸ�gq:���v�l��"��o��x��ǔ�a�09�3H���VeSY?��,�A����l��^*(��W�BE#J�PKX��Fк�s�^��
�H�)��� ��V��
�k<���FntUj<��!F�/
���U#dU#�q�]ZzUnd�I��Z�w�w'��%��l�4�^!G���~��Ƅ�n��̯�?Ԫ,&�U�1teT"u^���r�P�Bw�:YkLX_:�������ī��Mw��P"���\!%���7����zWO}Yp���h�8�����n�]�� ;x�o�2w�38�ś.��/�~�+e"pC����ڳk�]�c#
�����E�{�}�nZ��8�35T�IC+��6�6����E���">J��AZ���F��#��j*����*7�#Pm]����e�e���U�,�؍�!�j�Z��B�de�ҿ�������A֍i����`\T0�0r������Ȇ �G#A��������϶��f���'���͵�,6c�.�4�O�Y:6C.6�}�!]éy�{E߱?��>�<Ƭ�u�y$��9��L���f�]�T��ܸ�/w���������^qj[�r��U)g1b������W���Ǥ�*1�؆�������Ȁ8�F�c�ٯB^�bk�n=�?u��x�;�]�H0rsg���tI[x�����G�0�����@p�EW��B�������L�
endstream
endobj
7 0 obj
<</Parent 6 0 R/Contents 5 0 R/Type/Page/Resources<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]/Font<</F1 1 0 R/F2 2 0 R>>>>/MediaBox[0 0 595 842]/Annots[3 0 R 4 0 R]>>
endobj
1 0 obj
<</BaseFont/Helvetica/Type/Font/Encoding/WinAnsiEncoding/Subtype/Type1>>
endobj
2 0 obj
<</BaseFont/Helvetica-Bold/Type/Font/Encoding/WinAnsiEncoding/Subtype/Type1>>
endobj
6 0 obj
<</ITXT(2.1.7)/Type/Pages/Count 1/Kids[7 0 R]>>
endobj
8 0 obj
<</Type/Catalog/Pages 6 0 R>>
endobj
9 0 obj
<</Producer(iText 2.1.7 by 1T3XT)/ModDate(D:20150907102806+02'00')/CreationDate(D:20150907102806+02'00')>>
endobj
xref
0 10
0000000000 65535 f
0000001518 00000 n
0000001606 00000 n
0000000015 00000 n
0000000142 00000 n
0000000272 00000 n
0000001699 00000 n
0000001332 00000 n
0000001762 00000 n
0000001807 00000 n
trailer
<</Root 8 0 R/ID [<f16ea10e09183af8aff079f97cfac53f><fe60918ac5b80276ed8a082dedebf230>]/Info 9 0 R/Size 10>>
startxref
1929
%%EOF
</code></pre>
<p>This text version of binary file is different (more question marked characters in place of other ones) from the one I can see opening the binary file from file system with a text editor.</p>
<p>My question is: how could I test this service posting the JSON request and being able to open PDF document in the response? Should I use another tool, or build a form?</p> | 0 | 1,659 |
Angular Error: 'Component 'X' is not included in a module...' when declared in a sub module | <p>I'm trying to consolidate my dialogs into an Angular module, but I'm getting a linting error in the IDE:</p>
<blockquote>
<p>Component 'X' is not included in a module and will not be available
inside a template. Consider adding it to an NgModule declaration.</p>
</blockquote>
<p>Despite this error the application still loads and runs successfully.</p>
<p><strong>Example Component Definition</strong></p>
<pre><code>import { Component, Inject, OnInit, ViewEncapsulation } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
export interface AlertDialogData {
titleText: string;
dismissalText: string;
contentComponent: string;
}
@Component({
selector: 'app-alert-dialog',
templateUrl: './alert-dialog.component.html',
styleUrls: ['./alert-dialog.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class AlertDialogComponent implements OnInit {
constructor(private dialogRef: MatDialogRef<AlertDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
}
handleCloseClick(): void {
this.dialogRef.close();
}
}
</code></pre>
<p><strong>Sub module making Declaration/Export</strong></p>
<pre><code>import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ZipLocatorDialogComponent } from './zip-locator-dialog/zip-locator-dialog.component';
import { AlertDialogComponent } from './alert-dialog/alert-dialog.component';
import { HelperDialogComponent } from './helper-dialog/helper-dialog.component';
import {
MatAutocompleteModule, MatButtonModule, MatDialogModule, MatFormFieldModule, MatInputModule,
MatSelectModule
} from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
CommonModule,
FlexLayoutModule,
FormsModule,
ReactiveFormsModule,
MatDialogModule,
MatInputModule,
MatFormFieldModule,
MatSelectModule,
MatAutocompleteModule,
MatButtonModule
],
exports: [
ZipLocatorDialogComponent,
HelperDialogComponent,
AlertDialogComponent
],
declarations: [
ZipLocatorDialogComponent,
HelperDialogComponent,
AlertDialogComponent
],
entryComponents: [
ZipLocatorDialogComponent,
HelperDialogComponent,
AlertDialogComponent
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
})
export class AppDialogsModule { }
</code></pre>
<p><strong>App Module</strong></p>
<pre><code>// <editor-fold desc="Global Application Imports">
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { RouteDefinitions } from './app.routes';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FlexLayoutModule } from '@angular/flex-layout';
import { WebWrapperModule } from 'web-wrapper';
import { UiComponentsModule } from './ui-components.module';
import { AppComponent } from './app.component';
// OPERATORS
import './rxjs-operators';
// SERVICES
import { LoginManagerService } from './services/login-manager.service';
import { UtilsService } from './services/utils.service';
import { DataManagerService } from './services/data-manager.service';
import { ReferenceDataManagerService } from './services/reference-data-manager.service';
import { InfrastructureApiService } from './services/infrastructure-api.service';
// </editor-fold>
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
FlexLayoutModule,
HttpClientModule,
WebWrapperModule,
UiComponentsModule,
AppDialogsModule,
RouterModule.forRoot(RouteDefinitions)
],
providers: [
UtilsService,
LoginManagerService,
DataManagerService,
InfrastructureApiService,
ReferenceDataManagerService
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p><strong>Versions</strong></p>
<pre><code>Angular CLI: 1.5.0
Node: 7.2.1
OS: win32 x64
Angular: 4.4.6
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router, tsc-wrapped
@angular/cdk: 2.0.0-beta.12
@angular/cli: 1.5.0
@angular/flex-layout: 2.0.0-beta.11-b01c2d7
@angular/material: 2.0.0-beta.12
@angular-devkit/build-optimizer: 0.0.32
@angular-devkit/core: 0.0.20
@angular-devkit/schematics: 0.0.35
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.0
@schematics/angular: 0.1.2
typescript: 2.4.2
webpack: 3.8.1
</code></pre> | 0 | 1,668 |
Trying to make simple PDF document with Apache poi | <p>I see the internet is riddled with people complaining about apache's pdf products, but I cannot find my particular usecase here. I am trying to do a simple Hello World with apache poi. Right now my code is as follows:</p>
<pre><code>public ByteArrayOutputStream export() throws IOException {
//Blank Document
XWPFDocument document = new XWPFDocument();
//Write the Document in file system
ByteArrayOutputStream out = new ByteArrayOutputStream();;
//create table
XWPFTable table = document.createTable();
XWPFStyles styles = document.createStyles();
styles.setSpellingLanguage("English");
//create first row
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("col one, row one");
tableRowOne.addNewTableCell().setText("col two, row one");
tableRowOne.addNewTableCell().setText("col three, row one");
//create second row
XWPFTableRow tableRowTwo = table.createRow();
tableRowTwo.getCell(0).setText("col one, row two");
tableRowTwo.getCell(1).setText("col two, row two");
tableRowTwo.getCell(2).setText("col three, row two");
//create third row
XWPFTableRow tableRowThree = table.createRow();
tableRowThree.getCell(0).setText("col one, row three");
tableRowThree.getCell(1).setText("col two, row three");
tableRowThree.getCell(2).setText("col three, row three");
PdfOptions options = PdfOptions.create();
PdfConverter.getInstance().convert(document, out, options);
out.close();
return out;
}
</code></pre>
<p>and the code that calls this is:</p>
<pre><code> public ResponseEntity<Resource> convertToPDFPost(@ApiParam(value = "DTOs passed from the FE" ,required=true ) @Valid @RequestBody ExportEnvelopeDTO exportDtos) {
if (exportDtos.getProdExportDTOs() != null) {
try {
FileOutputStream out = new FileOutputStream("/Users/kornhaus/Desktop/test.pdf");
out.write(exporter.export().toByteArray());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<Resource>(responseFile, responseHeaders, HttpStatus.OK);
}
return new ResponseEntity<Resource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
</code></pre>
<p>On this line here: <code>out.write(exporter.export().toByteArray());
</code> the code throws an exception: </p>
<pre><code>org.apache.poi.xwpf.converter.core.XWPFConverterException: java.io.IOException: Unable to parse xml bean
</code></pre>
<p>I have no clue what's causing this, where to even look for this kind of documentation. I have been coding a decade plus and never had such difficulty with what should be a simple Java library. Any help would be great.</p> | 0 | 1,026 |
Could not extract response: no suitable HttpMessageConverter found for response type | <p>I am new with spring integration and working in spring integration http module for my project requirement. I am sending request from outbound gateway as a http client.
I am trying to initiate a request to the server and server should return me the message payload with my set values. I am converting object to JSON using to send to server
I am sending a request to inbound gateway present on the server side from client(HttpClientDemo) shown below. For that purpose, I am converting my object into the JSON and then converting to JSON string to object on the client side, performing some simple operation there and sending it back to the client(HttpClientDemo) but before this, I am getting exception related to HttpMessageConverter as below:</p>
<pre><code>Exception in thread "main" org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.mycompany.MyChannel.model.FFSampleResponseHttp] and content type [text/plain;charset=UTF-8]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:784)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:769)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:549)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:517)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:462)
at org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler.handleRequestMessage(HttpRequestExecutingMessageHandler.java:421)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:170)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:101)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:97)
at org.springframework.integration.channel.AbstractSubscribablMyChannel.doSend(AbstractSubscribablMyChannel.java:77)
at org.springframework.integration.channel.AbstractMessagMyChannel.send(AbstractMessagMyChannel.java:255)
at org.springframework.integration.channel.AbstractMessagMyChannel.send(AbstractMessagMyChannel.java:223)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:114)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:44)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:93)
</code></pre>
<p>Please find Below related code :</p>
<p>Client side code:
HttpClientDemo.java</p>
<pre><code>public class HttpClientDemo {
private static Logger logger = Logger.getLogger(HttpClientDemo.class);
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/META-INF/spring/integration/http-outbound-config.xml");
RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class);
FFSampleRequestHttp FFSampleRequesthttp = new FFSampleRequestHttp();
FFSampleRequesthttp.setMyChannelID("1");
FFSampleRequesthttp.setMyNumber("88");
FFSampleRequesthttp.setReferenceID("9I");
FFSampleRequesthttp.setTemplateType(1);
FFSampleRequesthttp.setTimestamp("today");
FFSampleResponseHttp reply = requestGateway.FFSampleResponsegatway(FFSampleRequesthttp);
logger.info("Replied with: " + reply);
}
}
</code></pre>
<p>My Request Gateway is as follows: RequestGateway.java</p>
<pre><code>public interface RequestGateway {
FFSampleResponseHttp FFSampleResponsegatway(FFSampleRequestHttp request);
}
</code></pre>
<p>http-outbound-config.xml </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
<int:gateway id="requestGateway"
service-interface="com.mycompany.MyChannel.Common.RequestGateway"
default-request-channel="requestChannel"/>
<int:channel id="requestChannel"/>
<int:channel id="requestChannel1"/>
<!-- com.mycompany.MyChannel.model.FFSampleResponseHttp -->
<int-http:outbound-gateway request-channel="requestChannel1" reply-channel="replyChannel1" url="http://localhost:8080/MyChannel_prj-1.0.0.BUILD-SNAPSHOT/receiveGateway" http-method="POST" extract-request-payload="true" expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp"/>
<int:object-to-json-transformer input-channel="requestChannel" output-channel="requestChannel1" content-type="application/json" result-type="STRING"/>
<bean id="FFSampleRequestHttp" class="com.mycompany.MyChannel.model.FFSampleRequestHttp"></bean>
</beans>
</code></pre>
<p>Web.xml</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>MyChannel-http</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyChannel-http</servlet-name>
<url-pattern>/receiveGateway</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
</code></pre>
<p>servlet-config.xml</p>
<pre><code> <int:channel id="receivMyChannel"/>
<int-http:inbound-gateway request-channel="receivMyChannel" path="/receiveGateway" supported-methods="POST"/>
<int:service-activator input-channel="receivMyChannel">
<bean class="com.mycompany.MyChannel.serviceImpl.FFSampleHttpImpl">
<constructor-arg ref = "FFSampleRequestHttp"></constructor-arg>
</bean>
</int:service-activator>
<bean id="FFSampleRequestHttp" class="com.mycompany.MyChannel.model.FFSampleRequestHttp"></bean>
<bean id="FFSampleResponseHttp" class="com.mycompany.MyChannel.model.FFSampleResponseHttp"></bean>
</beans>
public class FFSampleHttpImpl{
private static org.apache.log4j.Logger log = Logger
.getLogger(FFSampleImpl.class);
@Autowired
FFSampleRequestHttp request;
public FFSampleHttpImpl() {
}
public FFSampleHttpImpl(FFSampleRequestHttp request) {
super();
this.request = request;
}
public String issueResponseFor(String str) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
FFSampleRequestHttp FFSampleRequestHttp = mapper.readValue(new String(str), FFSampleRequestHttp.class);
FFSampleRequestHttp.setReferenceID("Hi My Number");
String strs = new String();
strs = mapper.writeValueAsString(FFSampleRequestHttp);
return strs;
}
}
</code></pre>
<p>FFSampleRequestHttp.java</p>
<pre><code>public class FFSampleRequestHttp {
protected String MyNumber;
protected String referenceID;
protected String myChannelID;
protected String timestamp;
protected int templateType;
public String getMyNumber() {
return MyNumber;
}
public void setMyNumber(String MyNumber) {
this.MyNumber = MyNumber;
}
public String getReferenceID() {
return referenceID;
}
public void setReferenceID(String referenceID) {
this.referenceID = referenceID;
}
public String getMyChannelID() {
return myChannelID;
}
public void setMyChannelID(String myChannelID) {
this.myChannelID = myChannelID;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public int getTemplateType() {
return templateType;
}
public void setTemplateType(int templateType) {
this.templateType = templateType;
}
}
</code></pre>
<p>FFSampleResponseHttp.java</p>
<pre><code>public class FFSampleResponseHttp {
protected String MyNumber;
protected String referenceID;
protected String myChannelID;
protected String timestamp;
protected int templateType;
public String getMyNumber() {
return MyNumber;
}
public void setMyNumber(String MyNumber) {
this.MyNumber = MyNumber;
}
public String getReferenceID() {
return referenceID;
}
public void setReferenceID(String referenceID) {
this.referenceID = referenceID;
}
public String getMyChannelID() {
return myChannelID;
}
public void setMyChannelID(String myChannelID) {
this.myChannelID = myChannelID;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public int getTemplateType() {
return templateType;
}
public void setTemplateType(int templateType) {
this.templateType = templateType;
}
}
</code></pre>
<p>When I run the above code I get following error: </p>
<pre><code>16:55:46.843 [main] DEBUG o.s.web.client.RestTemplate - Writing [{"MyNumber":"88","referenceID":"9I","myChannelID":"1","timestamp":"today","templateType":1}] as "text/plain;charset=UTF-8" using [org.springframework.http.converter.StringHttpMessageConverter@7d31a3e2]
16:55:46.988 [main] DEBUG o.s.web.client.RestTemplate - POST request for "http://localhost:8080/MyChannel_prj-1.0.0.BUILD-SNAPSHOT/receiveGateway" resulted in 200 (OK)
Exception in thread "main" org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.mycompany.MyChannel.model.FFSampleResponseHttp] and content type [text/plain;charset=UTF-8]
at org.springframework.web.client.HttpMessageConverterExtractor.
</code></pre>
<p>I have used spring integration basic sample code for reference.
Please provide your input. I also tried by using the spring object mapper in the configuration files with JSON to object transformer but then also I am getting similer issues for HttpMessageConverter.
Please help me with your valuable inputs/suggestion and let me know if we have any limitation with spring integration http object mapper.</p>
<hr>
<p>Hi Artem,
Thanks for your reply. I am still facing some challenges mentioned below. I have done the changes in my configuration files as per of your suggestion. but facing issue when using Jackson2JsonObjectMapper and need your further help. Please find below issue description.</p>
<p>I have done changes in my files and now files are like below:
My Servlet-Config.xml file content is as below:</p>
<pre><code><int:channel id="channel1" />
<int:channel id="channel2" />
<int:channel id="channel3" />
<int-http:inbound-gateway request-channel="channel1" supported-methods="POST" path="/receiveGateway" />
- <int:service-activator input-channel="channel2">
- <bean class="com.myCompany.myChannel.serviceImpl.FFSampleHttpImpl">
<constructor-arg ref="ffSampleRequestHttp" />
</bean>
</int:service-activator>
<int:json-to-object-transformer input-channel="channel1" output-channel="channel2" type="com.myCompany.myChannel.model.FFSampleRequestHttp" object-mapper="jackson2JsonObjectMapper" />
<bean id="jackson2JsonObjectMapper" class="org.springframework.integration.support.json.Jackson2JsonObjectMapper" />
<bean id="ffSampleRequestHttp" class="com.myCompany.myChannel.model.FFSampleRequestHttp" />
<bean id="ffSampleResponseHttp" class="com.myCompany.myChannel.model.FFSampleResponseHttp" />
</beans>
</code></pre>
<p>Out bound file config(file which is responsible to sent message to server):</p>
<pre><code><int:gateway id="requestGateway" service-interface="com.myCompany.myChannel.Common.RequestGateway" default-request-channel="requestChannel" />
<int:channel id="requestChannel" />
<int:channel id="requestChannel1" />
<int:object-to-json-transformer input-channel="requestChannel" output-channel="requestChannel1" content-type="application/json" />
<int-http:outbound-gateway request-channel="requestChannel1" reply-channel="channel4" url="http://localhost:8080/myChannel_prj-1.0.0.BUILD-SNAPSHOT/http/receiveGateway" http-method="POST" />
<bean id="FFSampleRequestHttp" class="com.myCompany.myChannel.model.FFSampleRequestHttp" />
<int:json-to-object-transformer input-channel="channel4" output-channel="requestChannel" type="com.myCompany.myChannel.model.FFSampleResponseHttp" object-mapper="jackson2JsonObjectMapper" />
<bean id="jackson2JsonObjectMapper" class="org.springframework.integration.support.json.Jackson2JsonObjectMapper" />
</beans>
</code></pre>
<p>My impl class method is as below:</p>
<pre><code>public FfSampleResponseHttp issueResponseFor(FfSampleRequestHttp request) {
FfSampleResponseHttp ffSampleResponse2 = new FfSampleResponseHttp();
ffSampleResponse2.setCifNumber("Yappi I am in the method");
log.info("issueResponseFor(FfSampleRequesthttp request)");
return ffSampleResponse2;
}
</code></pre>
<p>I am able to call my service method issueResponseFor present in server side from the client but when this is processing further:</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: 'json' argument must be an instance of: [class java.lang.String, class [B, class java.io.File, class java.net.URL, class java.io.InputStream, class java.io.Reader]
at org.springframework.integration.support.json.Jackson2JsonObjectMapper.fromJson(Jackson2JsonObjectMapper.java:93)
at org.springframework.integration.support.json.Jackson2JsonObjectMapper.fromJson(Jackson2JsonObjectMapper.java:44)
at org.springframework.integration.support.json.AbstractJacksonJsonObjectMapper.fromJson(AbstractJacksonJsonObjectMapper.java:55)
at org.springframework.integration.json.JsonToObjectTransformer.doTransform(JsonToObjectTransformer.java:78)
at org.springframework.integration.transformer.AbstractTransformer.transform(AbstractTransformer.java:33)
... 54 more
</code></pre>
<p>I have verified while debugging that the payload body while in response is coming blank in json object in the parameter of Jackson2JsonObjectMapper.fromJson(…) after roaming through my service method successfully. I am not able to understand where am I doing the mistake. Please provide your help/input.
Again let me know if I am again missing something in my config files. Thank you very much for your support.</p> | 0 | 5,766 |
MVC binding to model with list property ignores other properties | <p>I have a basic ViewModel with a property that is a List of complex types. When binding, I seem to be stuck with getting either the list of values, OR the other model properties depending on the posted values (i.e. the view arrangement).</p>
<p>The view model:</p>
<pre><code>public class MyViewModel
{
public int Id { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public List<MyDataItem> Data { get; set; }
}
public class MyDataItem
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
</code></pre>
<p>The controller actions:</p>
<pre><code> public ActionResult MyForm()
{
MyViewModel model = new MyViewModel();
model.Id = 1;
model.Data = new List<MyDataItem>()
{
new MyDataItem{ Id = 1, ParentId = 1, Name = "MyListItem1", Value = "SomeValue"}
};
return View(model);
}
[HttpPost]
public ActionResult MyForm(MyViewModel model)
{
//...
return View(model);
}
</code></pre>
<p>Here is the basic view (without the list mark-up)</p>
<pre><code>@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>My View Model</legend>
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Property1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Property1)
@Html.ValidationMessageFor(model => model.Property1)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Property2)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Property2)
@Html.ValidationMessageFor(model => model.Property2)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
</code></pre>
<p>When posted back to the controller, I get the 2 property values and a null value for the 'Data' property as expected. </p>
<p><img src="https://i.stack.imgur.com/Uspzv.gif" alt="Without List Mark-up"></p>
<p>If I add the mark-up for the List as follows (based on the information in this <a href="http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx" rel="nofollow noreferrer">Scott Hanselman post</a> and <a href="http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx" rel="nofollow noreferrer">Phil Haack's post</a>):</p>
<pre><code><div class="editor-field">
@for (int i = 0; i < Model.Data.Count(); i++)
{
MyDataItem data = Model.Data[i];
@Html.Hidden("model.Data[" + i + "].Id", data.Id)
@Html.Hidden("model.Data[" + i + "].ParentId", data.ParentId)
@Html.Hidden("model.Data[" + i + "].Name", data.Name)
@Html.TextBox("model.Data[" + i + "].Value", data.Value)
}
</div>
</code></pre>
<p>The 'Data' property of the model is successfully bound but the other properties are null. </p>
<p><img src="https://i.stack.imgur.com/CAIKg.gif" alt="With List Mark-up"></p>
<p>The form values posted are as follows:</p>
<pre><code>Id=1&Property1=test1&Property2=test2&model.Data%5B0%5D.Id=1&model.Data%5B0%5D.ParentId=1&model.Data%5B0%5D.Name=MyListItem1&model.Data%5B0%5D.Value=SomeValue
</code></pre>
<p>Is there a way to get both sets of properties populated or am I just missing something obvious?</p>
<p><strong>EDIT:</strong> </p>
<p>For those of you who are curious. Based on the answer from <a href="https://stackoverflow.com/users/2972/martinhn">MartinHN</a>, the original generated mark-up was:</p>
<pre><code><div class="editor-field">
<input id="model_Data_0__Id" name="model.Data[0].Id" type="hidden" value="1" />
<input id="model_Data_0__ParentId" name="model.Data[0].ParentId" type="hidden" value="1" />
<input id="model_Data_0__Name" name="model.Data[0].Name" type="hidden" value="MyListItem1" />
<input id="model_Data_0__Value" name="model.Data[0].Value" type="text" value="SomeValue" />
</div>
</code></pre>
<p>The new generated mark-up is:</p>
<pre><code><div class="editor-field">
<input id="Data_0__Id" data-val="true" name="Data[0].Id" type="hidden" value="1" data-val-number="The field Id must be a number." data-val-required="The Id field is required." />
<input id="Data_0__ParentId" name="Data[0].ParentId" type="hidden" value="1" data-val="true" data-val-number="The field ParentId must be a number." data-val-required="The ParentId field is required." />
<input id="Data_0__Name" name="Data[0].Name" type="hidden" value="MyListItem1" />
<input id="Data_0__Value" name="Data[0].Value" type="text" value="SomeValue" />
</div>
</code></pre>
<p>Which results in the following posted values:</p>
<pre><code>Id=1&Property1=test1&Property2=test2&Data%5B0%5D.Id=1&Data%5B0%5D.ParentId=1&Data%5B0%5D.Name=MyListItem1&Data%5B0%5D.Value=SomeValue
</code></pre>
<p>Notice there's no 'model.' in the name and posted values...</p> | 0 | 2,261 |
How do I fix blurry text in my HTML5 canvas? | <p>I am a total <em>n00b</em> with <code>HTML5</code> and am working with the <code>canvas</code> to render shapes, colors, and text. In my app, I have a <em>view adapter</em> that creates a canvas dynamically, and fills it with content. This works really nicely, except that my text is rendered very fuzzy/blurry/stretched. I have seen a lot of other posts on why defining the <em>width</em> and <em>height</em> in <code>CSS</code> will cause this issue, but I define it all in <code>javascript</code>.</p>
<p>The relevant code (view <a href="http://jsfiddle.net/65maD/" rel="noreferrer">Fiddle</a>):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var width = 500;//FIXME:size.w;
var height = 500;//FIXME:size.h;
var canvas = document.createElement("canvas");
//canvas.className="singleUserCanvas";
canvas.width=width;
canvas.height=height;
canvas.border = "3px solid #999999";
canvas.bgcolor = "#999999";
canvas.margin = "(0, 2%, 0, 2%)";
var context = canvas.getContext("2d");
//////////////////
//// SHAPES ////
//////////////////
var left = 0;
//draw zone 1 rect
context.fillStyle = "#8bacbe";
context.fillRect(0, (canvas.height*5/6)+1, canvas.width*1.5/8.5, canvas.height*1/6);
left = left + canvas.width*1.5/8.5;
//draw zone 2 rect
context.fillStyle = "#ffe381";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*2.75/8.5, canvas.height*1/6);
left = left + canvas.width*2.75/8.5 + 1;
//draw zone 3 rect
context.fillStyle = "#fbbd36";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*1.25/8.5, canvas.height*1/6);
left = left + canvas.width*1.25/8.5;
//draw target zone rect
context.fillStyle = "#004880";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*0.25/8.5, canvas.height*1/6);
left = left + canvas.width*0.25/8.5;
//draw zone 4 rect
context.fillStyle = "#f8961d";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*1.25/8.5, canvas.height*1/6);
left = left + canvas.width*1.25/8.5 + 1;
//draw zone 5 rect
context.fillStyle = "#8a1002";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width-left, canvas.height*1/6);
////////////////
//// TEXT ////
////////////////
//user name
context.fillStyle = "black";
context.font = "bold 18px sans-serif";
context.textAlign = 'right';
context.fillText("User Name", canvas.width, canvas.height*.05);
//AT:
context.font = "bold 12px sans-serif";
context.fillText("AT: 140", canvas.width, canvas.height*.1);
//AB:
context.fillText("AB: 94", canvas.width, canvas.height*.15);
//this part is done after the callback from the view adapter, but is relevant here to add the view back into the layout.
var parent = document.getElementById("layout-content");
parent.appendChild(canvas);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="layout-content"></div></code></pre>
</div>
</div>
</p>
<p>The results I am seeing (in <em>Safari</em>) are much more skewed than shown in the Fiddle:</p>
<p><strong>Mine</strong></p>
<p><img src="https://i.stack.imgur.com/Dh51D.png" alt="Rendered output in Safari" /></p>
<p><strong>Fiddle</strong></p>
<p><img src="https://i.stack.imgur.com/HuRUB.png" alt="Rendered output on JSFiddle" /></p>
<p>What am I doing incorrectly? Do I need a separate canvas for each text element? Is it the font? Am I required to first define the canvas in the HTML5 layout? Is there a typo? I am lost.</p> | 0 | 1,324 |
How to connect CakePHP to a Postgres database? | <p>I'm just starting with CakePHP, I went through the blog tutorial without trouble but would now like to try it with a proper DBMS like postgres. I tweaked the database.php file to point to a database I created in my local postgres instance: </p>
<pre><code>class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => 'localhost',
'port' => '5432',
'login' => 'cakephp',
'password' => 'cakephp',
'database' => 'cakephp',
'schema' => 'blog_tuto',
'prefix' => '',
//'encoding' => 'utf8',
);
public $test = array(
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => 'localhost',
'port' => '5432',
'login' => 'cakephp',
'password' => 'cakephp',
'database' => 'cakephp',
'schema' => 'blog_tuto',
'prefix' => '',
//'encoding' => 'utf8',
);
}
</code></pre>
<p>I have no issues connecting to this database with a SQL client, but CakePHP complains with the following message:</p>
<pre><code>CakePHP is NOT able to connect to the database.
Database connection "Postgres" is missing, or could not be created.
Selected driver is not enabled
</code></pre>
<p>I already verified that the postgres DboSource class in present. The postgres php module is also installed:</p>
<pre><code>$ php -m | grep pg
pdo_pgsql
pgsql
</code></pre>
<p>What am I missing? Thanks.</p>
<p><strong>Update I</strong> : The output of phpinfo related to Postgres goes below:</p>
<pre><code>pdo_pgsql
PDO Driver for PostgreSQL enabled
PostgreSQL(libpq) Version 9.1.9
Module version 1.0.2
Revision $Id: pdo_pgsql.c 321634 2012-01-01 13:15:04Z felipe $
pgsql
PostgreSQL Support enabled
PostgreSQL(libpq) Version 9.1.9
Multibyte character support enabled
SSL support enabled
Active Persistent Links 0
Active Links 0
Directive Local Value Master Value
pgsql.allow_persistent On On
pgsql.auto_reset_persistent Off Off
pgsql.ignore_notice Off Off
pgsql.log_notice Off Off
pgsql.max_links Unlimited Unlimited
pgsql.max_persistent Unlimited Unlimited
</code></pre>
<p><strong>Update II</strong> : When I accessed the application today trying to follow <a href="https://stackoverflow.com/questions/20948599/how-to-connect-cakephp-to-a-postgres-database#comment42869042_27106796">Ajir's suggestion</a> I surprisingly got a different error message: "Authentication failed" - meaning that CakePHP is now able to connect. I installed Postgres 9.3 some months ago and had not re-created the tutorial objects; all I needed to do was run the SQL script and the tutorial application is now fully functional.</p>
<p>Whatever is wrong is likely restricted to Postgres 9.1. </p> | 0 | 1,095 |
best practice for specifying pronunciation for Android TTS engine? | <p>In general, I'm very impressed with Android's default text to speech engine (i.e., com.svox.pico). As expected, it mispronounces some words (as do I) and it therefore occasionally needs some pronunciation guidance. So I'm wondering about best practices for phonetically spelling out those words that the pico TTS engine mispronounces.</p>
<p>For example, the correct pronunciation of the bird Chachalaca is CHAH-chah-LAH-kah. Here is what the TTS engine produces:</p>
<pre><code>mTts.speak("Chachalaca", TextToSpeech.QUEUE_ADD, null); // output: chuh-KAL-uh-KUH
mTts.speak("CHAH-chah-LAH-kah", TextToSpeech.QUEUE_ADD, null); // output: CHAH-chah-EL-AY-AYCH-dash-kuh
mTts.speak("CHAHchahLAHkah", TextToSpeech.QUEUE_ADD, null); // output: CHA-chah-LAH-ka
mTts.speak("CHAH chah LOCKah", TextToSpeech.QUEUE_ADD, null); // output: CHAH-chah-LAH-kah
</code></pre>
<p>Here are my questions.</p>
<p><b></p>
<ul>
<li>Is there a standard phonetic spelling recognized by the Android TTS engine?</li>
<li>If not, are there some general rules for making custom pronunciation spellings that will make the spellings more likely to be correct in future TTS engines/versions?</li>
<li>It appears that the Android TTS engine ignores text case. What is the best way to specify emphasis?</li>
</ul>
<p></b></p>
<p>By the way, this is what the TTS engine writes to logcat:</p>
<p>V/TtsService( 294): TTS processing: CHAH chah LOCKah<br>
V/TtsService( 294): TtsService.setLanguage(eng, USA, )<br>
I/SVOX Pico Engine( 294): Language already loaded (en-US == en-US)<br>
I/SynthProxy( 294): setting speech rate to 100<br>
I/SynthProxy( 294): setting pitch to 100 </p>
<p>[UPDATE]</p>
<p>I tried passing an XML document to TextToSpeech.speak() as follows:</p>
<pre><code> String text = "<?xml version=\"1.0\"?>" +
"<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"http://www.w3.org/2001/10/synthesis " +
"http://www.w3.org/TR/speech-synthesis/synthesis.xsd\" " +
"xml:lang=\"en-US\">" +
"That is a big car! " +
"That <emphasis>is</emphasis> a big car! " +
"That is a <emphasis>big</emphasis> car! " +
"That is a huge bank account! " +
"That <emphasis level=\"strong\">is</emphasis> a huge bank account! " +
"That is a <emphasis level=\"strong\">huge</emphasis> bank account!" +
"</speak>";
mTts.speak(text, TextToSpeech.QUEUE_ADD, null);
</code></pre>
<p>As Android Eve suggested, the TTS engine read only the XML body (i.e., the comments about the big car and the huge bank account). I didn't realize the TTS engine was capable of parsing XML documents. However, I did not hear any emphasis in the TTS output.</p>
<p>[UPDATE 2]</p>
<p>I simplified the question to whether or not Android TTS supports Speech Synthesis Markup Language <a href="https://stackoverflow.com/questions/3525424/does-android-tts-support-speech-synthesis-markup-language">here</a>.</p> | 0 | 1,356 |
How to add Animated Vector Drawable Animation? | <p>I am trying to animate a vector path to a different path in my android app for testing but its not working properly . no animation is displayed on screen and neither any animation is shown.</p>
<p><strong>My vector file is:</strong></p>
<pre><code> <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="8dp"
android:height="5dp"
android:viewportWidth="8"
android:viewportHeight="5">
<path
android:name="redot"
android:pathData="M2.5,2.5L6,2.5"
android:strokeWidth="4"
android:fillColor="#00000000"
android:strokeColor="#E61B1B"
android:fillType="evenOdd"
android:strokeLineCap="round"/>
</vector>
</code></pre>
<p><strong>And my VectorAnimation file is:</strong></p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:targetApi="lollipop"
android:drawable="@drawable/ic_reddot">
<target
android:animation="@anim/redanim"
android:name="redot"/>
</animated-vector>
</code></pre>
<p><strong>My Animation file in anim folder is:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:duration="10000"
android:propertyName="pathData"
android:valueFrom="M2.5,2.5L6,2.5"
android:valueTo="M2.5,2.5L31,2.5"
android:valueType="pathType" />
</set>
</code></pre>
<p><strong>And finally my MainActivityCode is as following:</strong></p>
<pre><code> public class MainActivity extends AppCompatActivity {
private TextView testObj;
private ImageView reddot;
private AnimatedVectorDrawable animation;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// testObj = (TextView) findViewById(R.id.testObj);
// testObj.setVisibility(View.INVISIBLE);
reddot = (ImageView) findViewById(R.id.reddot);
Drawable d = reddot.getBackground();
if (d instanceof AnimatedVectorDrawable) {
Log.d("testanim", "onCreate: instancefound" );
animation = (AnimatedVectorDrawable) d;
animation.start();
}
}
}
</code></pre> | 0 | 1,131 |
How to display Woocommerce product price by ID number on a custom page? | <p>I'm trying to display a price of a product in Woocommerce, on a custom page.
There is a short code for that, but it gives product price and also adds an "Add to cart button", I don't want the button, i just want to get the price of a specific product by ID.</p>
<p>Is this possible?</p>
<p>Thanks.</p>
<p>CODE:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="unlockTableBorder">
<tbody>
<tr>
<td>
<h2>פתיחת מכשירי Alcatel כלל עולמי</h2>
<h4>אנא קראו והבינו את תנאי השירות הבאים לפני הזמנת שירות זה:</h4>
<ul>
<li>שירות זה תומך בפתיחת מכשירים סלולריים מסוג Alcatel מארה"ב, קנדה ומקסיקו.</li>
<li>מכשירי CDMA וספקיות שירות CDMA לא נתמכים בידי שירות זה, אנא אל תשתמשו בשירות זה בשביל מכשירים אלו - במידה ותשמשו בשירות זה למכשירי CDMA, אתם תקבלו קוד שלא תוכלו להשתמש בו, ולא תוכלו לקבל החזר כספי! - אנא <a title="פתיחת מכשירי CDMA לכל הרשתות" href="http://www.unlocker.co.il/sim-unlock-cdma-mobile-device/">ראו פתיחת מכשירי CDMA לכל הרשתות בישראל.</a></li>
</ul>
<h5><strong>זמן הספקה: 1-24 שעות</strong></h5>
<form id="unlock1" class="cart" enctype="multipart/form-data" method="post" name="unlock"><input class="the_imei" style="width: 80%; border-radius: 15px;" name="the_imei" type="text" value="" placeholder="מספר סידורי IMEI של המכשיר (חייג #06#*)" /> <input class="add-to-cart" name="add-to-cart" type="hidden" value="76" /> <button class="unlockButton" type="submit" value="submit">פתח לכל הרשתות בישראל </button></form>*בלחיצה על הפתור, אתם מסכימים ל<a title="תנאי השירות" href="http://www.unlocker.co.il/terms-and-conditions/">תנאי השירות</a>.</td>
</tr>
</tbody>
</table>
<script src="http://www.unlocker.co.il/checkimei1.js" type="text/javascript"></script></code></pre>
</div>
</div>
</p> | 0 | 1,250 |
Linking unmanaged C++ DLL with managed C++ class library DLL | <p>As in the question <a href="https://stackoverflow.com/questions/2637571/creating-simple-c-net-wrapper-step-by-step">Creating simple c++.net wrapper. Step-by-step</a></p>
<p>I am tring to use C++ classes in .NET
but I am having problems building in Visual Studio (2008).</p>
<p>I have an unmanaged class A (C++ compiled with /clr).
I created a C++/clr class 'Class1' which wraps A and with matching
method delegates to A's methods.</p>
<p>If I include class A's unit source file in the class library
project for Class1 (managed) I have no problems
everything links and works fine,
But I have many unmanaged C++ classes like A and I am tring to put them in
a DLL and link that DLL to the managed library (of class wrappers).
[I actually don't see a need to link these DLL's together at this point,
but the compiler appears to be requiring it, giving the same errors shown below.]</p>
<p>I created VisualC++ / CLR / Class library
and added my C++ class (A listed below) and build.
[I used the default settings but
in the project linker settings I've tried both
Register output with yes and no.]
There were no errors and the .DLL file was created.</p>
<p>I created VisualC++ / CLR / Class library
and created the wrapper class 'Class1'
I used all default settings.
Under project properties I clicked 'References' 'Add New Reference"
and selected the DLL created in the first step.</p>
<p>I get linker errors:</p>
<pre><code>test_NET_library.obj : error LNK2028: unresolved token (0A000009) "public: int __thiscall Z::A::m1(int,int)" (?m1@A@Z@@$$FQAEHHH@Z) referenced in function "public: int __clrcall test_NET_library::Class1::m1(int,int)" (?m1@Class1@test_NET_library@@$$FQ$AAMHHH@Z)
test_NET_library.obj : error LNK2028: unresolved token (0A00000A) "public: int __thiscall Z::A::m2(int,int)" (?m2@A@Z@@$$FQAEHHH@Z) referenced in function "public: int __clrcall test_NET_library::Class1::m2(int,int)" (?m2@Class1@test_NET_library@@$$FQ$AAMHHH@Z)
test_NET_library.obj : error LNK2019: unresolved external symbol "public: int __thiscall Z::A::m1(int,int)" (?m1@A@Z@@$$FQAEHHH@Z) referenced in function "public: int __clrcall test_NET_library::Class1::m1(int,int)" (?m1@Class1@test_NET_library@@$$FQ$AAMHHH@Z)
test_NET_library.obj : error LNK2019: unresolved external symbol "public: int __thiscall Z::A::m2(int,int)" (?m2@A@Z@@$$FQAEHHH@Z) referenced in function "public: int __clrcall test_NET_library::Class1::m2(int,int)" (?m2@Class1@test_NET_library@@$$FQ$AAMHHH@Z)
C:\temp\test_Cpp_CLI\test_NET_library\Debug\test_NET_library.dll : fatal error LNK1120: 4 unresolved externals
</code></pre>
<p>The same errors as if I remove A.cpp in the wrapper class library project (the option that works).
I don't understand why the build is trying to resolve externals in the first place
because this is a library, not a program.</p>
<p>Is there something else I need to add to the wrapper class library project properties
or register the DLL of unmanaged classes, or compiler options?
Do I also need a .lib file to go with the DLL? (no lib file appears in the projects target directory)</p>
<p>Do I still have to use __declspec(dllexport) [it thought that was only for C style functions
not class members.]
as in the question: <a href="https://stackoverflow.com/questions/1208271/export-unmanaged-classes-from-a-visual-c-dll">Export Unmanaged Classes from a Visual C++ DLL?</a>
even though the unmanaged C++ library is compiled with CLR enabled.</p>
<p>(I did also try compiling as a static library, but I can't figure out how to add
the .lib file to the CLR class library project).</p>
<p>My test class is </p>
<pre><code>namespace Z
{
class A
{
public:
int m1(int p1, int p2);
int m2(int p3, int p4);
};
};
</code></pre>
<p>with the implementation:</p>
<pre><code>#include "A.h"
namespace Z
{
int A::m1(int p1, int p2) { return p1+p2; };
int A::m2(int p3, int p4) { return p3 * p4; };
};
</code></pre>
<p>And the wrapper class is</p>
<pre><code>#pragma once
#include "../A.h"
using namespace System;
namespace test_NET_library {
public ref class Class1
{
private: Z::A *a;
public: Class1()
: a(new Z::A)
{}
public: inline int m1(int p1, int p2)
{ return a->m1(p1,p2);
};
public: inline int m2(int p3, int p4)
{return a->m2(p3,p4);
};
};
}
</code></pre>
<p>As per the question: <a href="https://stackoverflow.com/questions/2691325/c-cli-mixed-mode-dll-creation">C++/CLI Mixed Mode DLL Creation</a>
I have also tried:</p>
<pre><code>#pragma managed(push, off)
#include "../A.h"
#pragma managed(pop)
</code></pre>
<p>And also this pushing managed around A.cpp.</p>
<p>Update:
As per mcdave's response I removed the /clr this produced a DLL, now how do I make this DLL available to my test_NET_library? </p>
<p>I tried References/Add New Reference, and selected the new this new DLL; and got the message "Could not add reference to file 'C:..\unmanaged_lib.dll' because it is neither .NET assembly or registered ActiveX control.". The DLL was added to the project's file list, but the compiler appears to be ignoring it.</p>
<p>I tried Add/Existing item and selected the new DLL.
but .DLL files are not a selectable file type.</p> | 0 | 1,809 |
SFTP connection error with JSch: SSH_MSG_DISCONNECT: 11 Internal server error | <p>I was trying to retrieve a file from SFTP server - while connecting to this SFTP works with FileZilla - SFTP method.</p>
<p>For JSch I have tried this code using JSch </p>
<pre><code>JSch jsch = new JSch();
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications", "password");
Session session = jsch.getSession( "super_robot", "192.192.192.com", 6222 );
session.setConfig(config );
session.setPassword( "a1234!X@" );
session.connect( 30000 );
</code></pre>
<p>Though I got this error:</p>
<pre class="lang-none prettyprint-override"><code>Caused by: com.jcraft.jsch.JSchException: SSH_MSG_DISCONNECT: 11 Internal server error.
at com.jcraft.jsch.Session.read(Session.java:1004)
at com.jcraft.jsch.Session.connect(Session.java:323)
</code></pre>
<p>With <code>StandardFileSystemManager</code> I'm also having the same error:</p>
<pre><code>SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, connectionTimeout);
SftpFileSystemConfigBuilder.getInstance().setIdentityInfo(opts);
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
StandardFileSystemManager fsManager = new StandardFileSystemManager();
fsManager.init();
</code></pre>
<p>Got me this error:</p>
<pre class="lang-none prettyprint-override"><code>Caused by: org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "digital.crossix.com".
at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:147)
at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:79)
... 40 more
Caused by: com.jcraft.jsch.JSchException: SSH_MSG_DISCONNECT: 11 Internal server error.
at com.jcraft.jsch.Session.read(Session.java:1004)
at com.jcraft.jsch.Session.connect(Session.java:323)
at com.jcraft.jsch.Session.connect(Session.java:183)
at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:145)
... 41 more
</code></pre>
<p>I have tried other solution offered in these links which didn't solve it:</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/43070939/sftp-connector-throwing-error-while-giving-encrytped-passwords-in-properties-fil">SFTP connector throwing error while giving encrytped passwords in properties file</a> </p></li>
<li><p><a href="https://stackoverflow.com/questions/44653214/com-jcraft-jsch-jschexception-ssh-msg-disconnect-2-protocol-error-rcvd-type-9">com.jcraft.jsch.JSchException: SSH_MSG_DISCONNECT: 2 protocol error: rcvd type 90</a> </p></li>
<li><p><a href="https://stackoverflow.com/questions/34351298/com-jcraft-jsch-jschexception-ssh-msg-disconnect-11-no-appropriate-prime-betwe">com.jcraft.jsch.JSchException: SSH_MSG_DISCONNECT: 11 No appropriate prime between 1024 and 1024 is available. en</a> </p></li>
<li><p><a href="https://stackoverflow.com/questions/32307009/java-jsch-ssh-msg-disconnect-failed-to-read-binary-packet-data">java jsch SSH_MSG_DISCONNECT Failed to read binary packet data</a></p></li>
</ul>
<p>Note that none of these errors is exactly the same as the error I'm facing - they are a bit similar.
Didn't found someone that had the exact error I'm facing.</p>
<p>When I was working with FileZilla this is the log I was seeing in console:</p>
<pre class="lang-none prettyprint-override"><code>Status: Connecting to 192.192.com:6222...
Trace: CControlSocket::SendNextCommand()
Trace: CSftpConnectOpData::Send() in state 0
Trace: Going to execute C:\Program Files\FileZilla FTP Client\fzsftp.exe
Response: fzSftp started, protocol_version=8
Trace: CSftpConnectOpData::ParseResponse() in state 0
Trace: CControlSocket::SendNextCommand()
Trace: CSftpConnectOpData::Send() in state 3
Command: open "super_robot@192.192.com" 6222
Trace: Connecting to 192.192.194 port 6222
Trace: We claim version: SSH-2.0-FileZilla_3.30.0
Trace: Server version: SSH-2.0-NuaneSSH_0.8.1.0
Trace: Using SSH protocol version 2
Trace: Doing Diffie-Hellman group exchange
Trace: Doing Diffie-Hellman key exchange with hash SHA-1
Trace: Server also has ssh-dss host key, but we don't know it
Trace: Host key fingerprint is:
Trace: ssh-rsa 1024 ------------------------------------
Command: Trust new Hostkey: Once
Trace: Initialised AES-256 CBC client->server encryption
Trace: Initialised HMAC-SHA1 client->server MAC algorithm
Trace: Initialised AES-256 CBC server->client encryption
Trace: Initialised HMAC-SHA1 server->client MAC algorithm
Trace: Attempting keyboard-interactive authentication
Trace: Using keyboard-interactive authentication. inst_len: 0, num_prompts: 1
Command: Pass: ********
Trace: Access granted
Trace: Opening session as main channel
Trace: Opened main channel
Trace: Started a shell/command
Status: Connected to 192.192.com
Trace: CSftpConnectOpData::ParseResponse() in state 3
Trace: CControlSocket::ResetOperation(0)
Trace: CSftpConnectOpData::Reset(0) in state 3
Trace: CFileZillaEnginePrivate::ResetOperation(0)
Status: Retrieving directory listing...
Trace: CControlSocket::SendNextCommand()
Trace: CSftpListOpData::Send() in state 0
Trace: CSftpChangeDirOpData::Send() in state 0
Trace: CSftpChangeDirOpData::Send() in state 1
Command: pwd
Response: Current directory is: "/"
Trace: CSftpChangeDirOpData::ParseResponse() in state 1
Trace: CControlSocket::ResetOperation(0)
Trace: CControlSocket::ParseSubcommandResult(0)
Trace: CSftpListOpData::SubcommandResult() in state 1
Trace: CControlSocket::SendNextCommand()
Trace: CSftpListOpData::Send() in state 2
Trace: CSftpListOpData::Send() in state 3
Command: ls
Status: Listing directory /
Trace: CSftpListOpData::ParseResponse() in state 3
Trace: CControlSocket::ResetOperation(0)
Status: Directory listing of "/" successful
Trace: CFileZillaEnginePrivate::ResetOperation(0)
</code></pre>
<p>What can I do to solve this error?</p>
<p>Attaching also the log from JSch</p>
<pre class="lang-none prettyprint-override"><code>INFO: Connection established
INFO: Remote version string: SSH-2.0-NuaneSSH_0.8.1.0
INFO: Local version string: SSH-2.0-JSCH-0.1.54
INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
INFO: aes256-ctr is not available.
INFO: aes192-ctr is not available.
INFO: aes256-cbc is not available.
INFO: aes192-cbc is not available.
INFO: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
INFO: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
INFO: SSH_MSG_KEXINIT sent
INFO: SSH_MSG_KEXINIT received
INFO: kex: server: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
INFO: kex: server: ssh-rsa,ssh-dss
INFO: kex: server: aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc
INFO: kex: server: aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc
INFO: kex: server: hmac-sha1,hmac-md5
INFO: kex: server: hmac-sha1,hmac-md5
INFO: kex: client: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
INFO: kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc
INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc
INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
INFO: kex: server->client aes128-cbc hmac-md5 none
INFO: kex: client->server aes128-cbc hmac-md5 none
INFO: SSH_MSG_KEXDH_INIT sent
INFO: expecting SSH_MSG_KEXDH_REPLY
INFO: Disconnecting from 192.192.com port 6222
Exception in thread "main" java.lang.reflect.InvocationTargetException
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 com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:65)
Caused by: com.jcraft.jsch.JSchException: SSH_MSG_DISCONNECT: 11 Internal server error.
at com.jcraft.jsch.Session.read(Session.java:1004)
at com.jcraft.jsch.Session.connect(Session.java:323)
at com.xxxxxxx.yyyy.service.SFTPTest.main(SFTPProviderTest.java:50)
... 5 more
</code></pre> | 0 | 3,243 |
Get hidden field value in code behind | <p>How can I get the value of the hiddenfield in code behind?</p>
<pre><code> <telerik:RadRotator ID="RadRotator1" RotatorType="AutomaticAdvance" ScrollDirection="Up"
ScrollDuration="4000" runat="server" Width="714"
ItemWidth="695" Height="260px" ItemHeight="70" FrameDuration="1" InitialItemIndex="-1"
CssClass="rotator">
<ItemTemplate>
<div class="itemTemplate" style="background-image: url('IMAGES3/<%# this.GetDayOfWeek(XPath("pubDate").ToString()) %>.png');">
<div class="dateTime">
<div class="time">
<%# (this.GetTimeOnly(XPath("pubDate").ToString())) %>
</div>
<div class="date">
<%# (this.GetDateOnly(XPath("pubDate").ToString()))%>
</div>
</div>
<div class="title">
<span>
<%# System.Web.HttpUtility.HtmlEncode(XPath("title").ToString())%>
</span>
</div>
<div class="buttonDiv">
<asp:Button ID="Button1" class="button" runat="server" Text="View" OnClientClick="OnClick" />
THIS HIDDENFIELD >>>>> <asp:HiddenField id="rssLink" runat="server" value='<%= System.Web.HttpUtility.HtmlEncode(XPath("link").ToString()%>' />
</div>
<div class="description">
<span>
<%# System.Web.HttpUtility.HtmlEncode(XPath("description").ToString())%>
</span>
</div>
</div>
</ItemTemplate>
</telerik:RadRotator>
</code></pre>
<p>The hidden field is inside a RadRotator and I am battling to get the value of it in code behind.</p> | 0 | 1,325 |
How to use "css" in the "jsp" in Spring MVC project? | <p>I am working on a spring MVC project in which I am trying to use <code>css</code> style sheets by referencing it to design my JSP page. But somehow my css files are not being picked up once I hit my method in the controller..</p>
<p>Below is my JSP file -</p>
<pre><code><html>
<head>
<link rel="stylesheet" type="text/css" href="test.css" />
</head>
<body>
<h1>All header 1 elements will be red</h1>
<h2>All header 2 elements will be blue</h2>
<p>All text in paragraphs will be green.</p>
</body>
</html>
</code></pre>
<p>And below is my <code>test.css</code> file - </p>
<pre><code>h1 {color:red;}
h2 {color:blue;}
p {color:green;}
</code></pre>
<p>And below is my method in controller class - </p>
<pre><code>@RequestMapping(value = "testing", method = RequestMethod.GET)
public Map<String, String> testing() {
final Map<String, String> model = new LinkedHashMap<String, String>();
return model;
}
</code></pre>
<p>Directory structure is like this - </p>
<pre>webapp/
|-- resources/
| +-- css/
| test.css
+- WEB-INF/
+-- views/
testing.jsp</pre>
<p>But somehow it's not working for me.. Is there anything wrong I am doing here? </p>
<p><strong>UPDATE:-</strong></p>
<p>Here is my web.xml file- </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>testweb</display-name>
<listener>
<listener-class>com.host.webres.resource.env.EbayResourceRuntimeListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>index</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/testweb/*</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>And below is my <code>context.xml</code> file -</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Allow proxys -->
<aop:aspectj-autoproxy />
<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven>
<mvc:message-converters>
<!-- Support AJAX processing with progressive rendering. Overrides HttpOutputMessage with RaptorResponseWriter -->
<beans:bean class="com.host.terr.kernel.filter.RaptorJacksonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<context:component-scan base-package="com.host.terr.config" />
<context:component-scan base-package="com.host.personalization.bullseye.zookeeper.p13nzook.controller" />
<!-- Handles HTTP GET requests by efficiently serving up static resources
in the corresponding directory -->
<resources mapping="/js/**" location="/js/" />
<resources mapping="/css/**" location="/css/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>
</code></pre>
<p>This is exception I am getting on my console but browser shows the data without any css - </p>
<pre><code>404 /testweb/test.css Not Found /testweb/test.css Not Found }, Correlations : {} }
</code></pre> | 0 | 2,497 |
Using angularJS with requireJS - cannot read property 'module' of undefined | <p>I had started writing an app using angularJS. After a few weeks, I suddenly realized that I should have used require JS from the beginning to load my modules. Yes, I know, it was stupid. But it is what it is.
So I've tried to convert my code to suit requireJS now.</p>
<p>This is my main.js</p>
<pre><code>requirejs.config({
baseUrl: "js",
paths: {
jquery:'jquery-1.7.min',
angular: 'angular',
angularRoute:'angular-route',
mainApp:'AngularApp/app'
},
priority:['angular'],
shim:{
angularRoute:{
deps:["angular"]
},
mainApp:{
deps:['angularRoute']
}
}});
require(['angular','angularRoute', 'mainApp'],
function(angular, angularRoute, app)
{
angular.bootstrap(document, ['ServiceContractModule']);
});
</code></pre>
<p>This is my app.js</p>
<pre><code>define(['angular',
'angularRoute',
'AngularApp/services',
'AngularApp/directives',
'AngularApp/controllers'],
function(angular, angularRoute, services, directives, controllers)
{
console.log("sup");
var serviceContractModule = angular.module('ServiceContractModule',[ 'ngRoute', services, directives, controllers ]);
serviceContractModule.config(function($routeProvider,$locationProvider) {
$routeProvider.when('/contractNumber/:contractNumbers', {
controller : 'ContractController',
templateUrl : './contractSearchResult',
reloadOnSearch : true
}).when('/serialNumber/:serialNumbers', {
controller : 'SerialController',
templateUrl : './serialSearchResult'
}).when('/QuoteManager',{
controller : 'QuoteManagerController',
templateUrl: './quoteManagerView'
}).when('/QuoteManagerHome',{
controller : 'QuoteManagerController',
templateUrl: './quoteManagerHome'
});
});
return serviceContractModule;
});
</code></pre>
<p>This is my directives.js file</p>
<pre><code>define(['angular',
'AngularApp/Directives/tableOperations',
'AngularApp/Directives/line',
'AngularApp/Directives/listOfValues'],
function(
angular,
tableOperations,
line,
listOfValues)
{
var directiveModule = angular.module('ServiceContractModule.directives');
directiveModule.directive('tableoperations', tableOperations);
directiveModule.directive('line', line);
directiveModule.directive('listOfValues', listOfValues);
return directiveModule;
}
</code></pre>
<p>)</p>
<p>And this is my services.js file</p>
<pre><code>define(['angular',
'AngularApp/Services/quoteManagerSearch'],
function(angular, quoteManagerSearch)
{
var serviceModule = angular.module('ServiceContractModule.services');
serviceModule.factory('searchRequestHandler', quoteManagerSearch);
return serviceModule;
}
</code></pre>
<p>)</p>
<p>When I run my page, the current error I am getting is</p>
<blockquote>
<p>Uncaught TypeError: Cannot read property 'module' of undefined directives.js:14</p>
<p>Uncaught TypeError: Cannot read property 'module' of undefined services.js:5</p>
</blockquote>
<p>This seems to be happening on this particular line</p>
<pre><code>var directiveModule = angular.module('ServiceContractModule.directives');
</code></pre>
<p>I think for some reason, the angular file is not getting loaded. Although when I run the page, I can see all the js files being loaded in the correct order in chrome.</p>
<p>Any ideas guys? Need quick help! Thanks!</p> | 0 | 1,382 |
how to get number input type from edittext android studio | <p>I have problem here,my java code is</p>
<pre><code>int num = Integer.parseInt(mark.getText().toString());
</code></pre>
<p>And my xml code is </p>
<pre><code>android. InputType="number"
</code></pre>
<p>But i am still getting error saying that <code>"invalid int ="""</code>
Can anyone help me..i really really need help right now. </p>
<pre><code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_remove);
parentLinearLayout = (LinearLayout) findViewById(R.id.parent_linear_layout);
final EditText mark = (EditText)findViewById(R.id.etMark);
EditText j = (EditText)findViewById(R.id.etJam);
TextView status = (TextView)findViewById(R.id.tVGred);
TextView pn = (TextView)findViewById(R.id.tvPnm);
double pointer;
String grade;
int num = Integer.parseInt(mark.getText().toString());
if (num >= 90 && num <= 100) {
grade = "A+";
pointer = 4.00;
status.setText(grade);
}
else if (num >= 80 && num <= 89) {
grade = "A";
pointer = 4.00;
status.setText(grade);
}
else if (num >= 75 && num <= 79) {
grade = "A-";
pointer = 3.67;
status.setText(grade);
}
else if (num >= 70 && num <= 74) {
grade = "B+";
pointer = 3.33;
status.setText(grade);
}
else if (num >= 65 && num <= 69) {
grade = "B";
pointer = 3.00;
status.setText(grade);
}
else if (num >= 60 && num <= 64) {
grade = "B-";
pointer = 2.67;
status.setText(grade);
}
else if (num >= 55 && num <= 59) {
grade = "C+";
pointer = 2.33;
status.setText(grade);
}
else if (num >= 50 && num <= 54) {
grade = "C";
pointer = 2.00;
status.setText(grade);
}
else if (num >= 47 && num <= 49) {
grade = "C-";
pointer = 1.67;
status.setText(grade);
}
else if (num >= 44 && num <= 46) {
grade = "D+";
pointer = 1.33;
status.setText(grade);
}
else if (num >= 40 && num <= 43) {
grade = "D";
pointer = 1.00;
status.setText(grade);
}
else
{
grade = "F";
pointer = 0.00;
status.setText(grade);
}
}
</code></pre> | 0 | 1,513 |
How call a redux action with an argument and access from the reducer? | <p>How can I call a <strong>setCounter</strong> action with a <strong>value</strong> argument from my component's render function?</p>
<p><strong>How do you access an action's argument in the reducer?</strong></p>
<pre><code>// File: app/actions/counterActions.js
export function setCounter(value) {
return {
type: types.SETCOUNTER,
value
};
}
export function increment() {
return {
type: types.INCREMENT
};
}
export function decrement() {
return {
type: types.DECREMENT
};
}
</code></pre>
<p>How to retrieve the action argument in the reducer?</p>
<pre><code>// File: app/reducers/counter.js
export default function counter(state = initialState, action = {}) {
switch (action.type) {
case types.INCREMENT:
return {
...state,
count: state.count + 1
};
case types.DECREMENT:
return {
...state,
count: state.count - 1
};
case types.SETCOUNTER:
return {
...state,
count: value /* How do I access an action argument ?? */
};
default:
return state;
}
}
</code></pre>
<p>How do I pass argument to setCounter action ?</p>
<pre><code>File: app/components/counter.js
export default class Counter extends Component {
constructor(props) {
super(props);
}
render() {
const { counter, increment, decrement, setCounter } = this.props;
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Count:{counter}</Text>
<TouchableOpacity onPress={setCounter(99)} style={styles.button}>
<Text>Reset to 99</Text>
</TouchableOpacity>
<TouchableOpacity onPress={increment} style={styles.button}>
<Text>up</Text>
</TouchableOpacity>
<TouchableOpacity onPress={decrement} style={styles.button}>
<Text>down</Text>
</TouchableOpacity>
</View>
);
}
}
</code></pre>
<p>I am learning react-native redux using this counter example:
<a href="https://github.com/alinz/example-react-native-redux" rel="noreferrer">https://github.com/alinz/example-react-native-redux</a></p>
<p>This app has two buttons; increment and decrement that call actions on the counter and the counter value re-renders. </p>
<p>I want to add a 3rd button to setCounter to an arbitrary value.</p>
<p>Thanks in advance,</p>
<p>-Ed
javascript, react-native, redux newbie</p>
<p>I do not understand the javascript syntax to make the call to setCounter(value) in my view component render function?</p>
<p><strong>{setCounter(99)} does not work?</strong></p>
<p>render() {
const { counter, increment, decrement, setCounter } = this.props;</p>
<pre><code>return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Count:{counter}</Text>
<TouchableOpacity onPress={setCounter(99)} style={styles.button}>
<Text>Reset to 99</Text>
</TouchableOpacity>
<TouchableOpacity onPress={increment} style={styles.button}>
<Text>up</Text>
</TouchableOpacity>
<TouchableOpacity onPress={decrement} style={styles.button}>
<Text>down</Text>
</TouchableOpacity>
</View>
);
</code></pre>
<p>}</p> | 0 | 1,391 |
Get nested fields with MongoDB shell | <p>I've "users" collection with a "watchlists" field, which have many inner fields too, one of that is "arrangeable_values" (the second field within "watchlists"). </p>
<p>I need to find for each user in "users" collection, each "arrangeable_values" within "watchlists".</p>
<p>How can I do that with mongodb shell ?</p>
<p>Here is an example of data model :</p>
<pre><code>> db.users.findOne({'nickname': 'superj'})
{
"_id" : ObjectId("4f6c42f6018a590001000001"),
"nickname" : "superj",
"provider" : "github",
"user_hash" : null,
"watchlists" : [
{
"_id" : ObjectId("4f6c42f7018a590001000002"),
"arrangeable_values" : {
"description" : "My introduction presentation to node.js along with sample code at various stages of building a simple RESTful web service with journey, cradle, winston, optimist, and http-console.",
"tag" : "",
"html_url" : "https://github.com/indexzero/nodejs-intro"
},
"avatar_url" : "https://secure.gravatar.com/avatar/d43e8ea63b61e7669ded5b9d3c2e980f?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
"created_at" : ISODate("2011-02-01T10:20:29Z"),
"description" : "My introduction presentation to node.js along with sample code at various stages of building a simple RESTful web service with journey, cradle, winston, optimist, and http-console.",
"fork_" : false,
"forks" : 13,
"html_url" : "https://github.com/indexzero/nodejs-intro",
"pushed_at" : ISODate("2011-09-12T17:54:58Z"),
"searchable_values" : [
"description:my",
"description:introduction",
"description:presentation",
"html_url:indexzero",
"html_url:nodejs",
"html_url:intro"
],
"tags_array" : [ ],
"watchers" : 75
},
{
"_id" : ObjectId("4f6c42f7018a590001000003"),
"arrangeable_values" : {
"description" : "A Backbone alternative idea",
"tag" : "",
"html_url" : "https://github.com/maccman/spine.todos"
},
"avatar_url" : "https://secure.gravatar.com/avatar/baf018e2cc4616e4776d323215c7136c?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
"created_at" : ISODate("2011-03-18T11:03:42Z"),
"description" : "A Backbone alternative idea",
"fork_" : false,
"forks" : 31,
"html_url" : "https://github.com/maccman/spine.todos",
"pushed_at" : ISODate("2011-11-20T22:59:45Z"),
"searchable_values" : [
"description:a",
"description:backbone",
"description:alternative",
"description:idea",
"html_url:https",
"html_url:github",
"html_url:com",
"html_url:maccman",
"html_url:spine",
"html_url:todos"
],
"tags_array" : [ ],
"watchers" : 139
}
]
}
</code></pre> | 0 | 1,564 |
MappedListIterable is not a SubType | <p>I'm new to flutter and dart and trying to fetch data from firestore as a stream and feed to my ListView but I keep getting this error:</p>
<pre><code>type 'MappedListIterable<DocumentSnapshot, Product>' is not a subtype
of type 'List<Product>'
</code></pre>
<p>I have seen a couple of other posts on stackoverflow like this but they either do not help me or do not apply to my situation.</p>
<p>This is my products page widget:</p>
<pre><code>import 'package:xxx/models/Product.dart';
import 'package:agrogator/screens/products/widgets/products_list.dart';
import 'package:xxx/services/product.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class ProductsScreen extends StatelessWidget {
ProductsScreen({Key key}) : super(key: key);
final product = ProductService();
// This widget is the productsucts page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
@override
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return StreamProvider<List<Product>>.value(
value: product.streamProducts(),
child: new Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: new Text("xxx"),
),
body: new ProductsList(),
floatingActionButton: new FloatingActionButton(
onPressed: () {},
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}
</code></pre>
<p>This is my ProductsList widget:</p>
<pre><code>import 'package:xxx/models/Product.dart';
import 'package:xxx/screens/products/widgets/product_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class ProductsList extends StatelessWidget {
@override
Widget build(BuildContext context) {
var products = Provider.of<List<Product>>(context);
return Container(
height: 100,
child: ListView(
children: products.map((product) {
return new ProductItem(product: product);
}).toList(),
),
);
}
}
</code></pre>
<p>This is my ProductItem widget:</p>
<pre><code>import 'package:xxx/models/Product.dart';
import 'package:flutter/material.dart';
class ProductItem extends StatelessWidget {
final Product product;
ProductItem({this.product});
@override
Widget build(BuildContext context) {
return Text(product.name, style: TextStyle(color: Colors.black));
}
}
</code></pre>
<p>This is my Product Model:</p>
<pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
class Product {
String uid;
String name;
String unit;
int avgQuantity;
double avgWeight;
double previousAvgPrice;
double currentAvgPrice;
String lastUpdatedBy;
String lastUpdatedAt;
String remarks;
Product(
{this.uid,
this.name,
this.unit,
this.avgQuantity,
this.avgWeight,
this.previousAvgPrice,
this.currentAvgPrice,
this.lastUpdatedBy,
this.lastUpdatedAt,
this.remarks});
factory Product.fromFirestore(DocumentSnapshot doc) {
Map data = doc.data;
return Product(
uid: doc.documentID,
name: data["name"],
unit: data["unit"],
avgQuantity: data["avgQuantity"],
avgWeight: data["avgWeight"],
previousAvgPrice: data["previousAvgPrice"],
currentAvgPrice: data["ccurrentAvgPrice"],
lastUpdatedBy: data["lastUpdatedBy"],
lastUpdatedAt: data["lastUpdatedAt"],
remarks: data["remarks"]);
}
}
</code></pre>
<p>And my service:</p>
<pre><code>import 'package:xxx/models/Product.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ProductService {
final Firestore _db = Firestore.instance;
Stream<List<Product>> streamProducts() {
var ref = _db.collection("products");
return ref
.snapshots()
.map((list) => list.documents.map((doc) => Product.fromFirestore(doc)));
}
}
</code></pre> | 0 | 1,731 |
Cannot find class [org.springframework.mail.javamail.JavaMailSenderImpl] for bean with name 'mailSender' defined | <p>I am writing a spring mail program:</p>
<pre><code>@Service("LeaveEmail")
public class LeaveEmail {
@Autowired
private MailSender mailSender;
@Autowired
private SimpleMailMessage alertMailMessage;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public boolean sendMail(LeaveApplyForm leaveApplyForm)
{
SimpleMailMessage message = new SimpleMailMessage();
EmpRegistrationForm empRegistrationForm=new EmpRegistrationForm();
String to=leaveApplyForm.getFirstApprover();
// String to1=leaveApplyForm.getFinalApprover();
String text=leaveApplyForm.getReason();
String from=empRegistrationForm.getEmail();
String subject="Application for the Leave";
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
return true;
}
}
</code></pre>
<p>and my spring-servlet.xml is:
</p>
<p>
<br>
</p>
<pre><code><bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="dattatraykotaledz@gmail.com" />
<property name="password" value="dattSkotale" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.ssl.trust">smtp.gmail.com</prop>
</props>
</property>
</code></pre>
<p>
And I am getting this error as soon as I start the Server:</p>
<pre><code>[org.springframework.web.servlet.view.InternalResourceViewResolver#0]
17:25:14,633 DEBUG XmlBeanDefinitionReader:216 - Loaded 15 bean definitions from location pattern [/WEB-INF/spring-servlet.xml]
17:25:14,633 DEBUG XmlWebApplicationContext:525 - Bean factory for WebApplicationContext for namespace 'spring-servlet': org.springframework.beans.factory.support.DefaultListableBeanFactory@1e13e07: defining beans [adminLoginController,empLeaveApplyController,empRegisterController,LeaveEmail,profileController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.web.servlet.view.InternalResourceViewResolver#0,messageSource,localeChangeInterceptor,localeResolver,handlerMapping,mailSender]; root of factory hierarchy
17:25:14,671 DEBUG DefaultListableBeanFactory:334 - Ignoring bean class loading failure for bean 'mailSender'
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.mail.javamail.JavaMailSenderImpl] for bean with name 'mailSender' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.mail.javamail.JavaMailSenderImpl
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1254)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1323)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:315)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:394)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:612)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:609)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:623)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:491)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:432)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:981)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4058)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4364)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.ClassNotFoundException: org.springframework.mail.javamail.JavaMailSenderImpl
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1360)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1206)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:257)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1275)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1246)
... 30 more
17:25:14,674 DEBUG DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
17:25:14,674 DEBUG DefaultListableBeanFactory:430 - Creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
17:25:14,681 DEBUG DefaultListableBeanFactory:504 - Eagerly caching bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' to allow for resolving potential circular references
17:25:14,683 DEBUG DefaultListableBeanFactory:458 - Finished creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
17:25:14,705 DEBUG ConfigurationClassUtils:74 - Could not find class file for introspecting factory methods: org.springframework.mail.javamail.JavaMailSenderImpl
java.io.FileNotFoundException: class path resource [org/springframework/mail/javamail/JavaMailSenderImpl.class] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:45)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
at org.springframework.context.annotation.ConfigurationClassUtils.checkConfigurationClassCandidate(ConfigurationClassUtils.java:69)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:219)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigurationClasses(ConfigurationClassPostProcessor.java:199)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:175)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:617)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:609)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:623)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:491)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:432)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:981)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4058)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4364)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
17:25:14,730 DEBUG DefaultListableBeanFactory:334 - Ignoring bean class loading failure for bean 'mailSender'
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.mail.javamail.JavaMailSenderImpl] for bean with name 'mailSender' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.mail.javamail.JavaMailSenderImpl
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1254)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1323)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:315)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:632)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:609)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:623)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:49
</code></pre>
<p>can anyone help me with this problem?
also I made some changes in spring-servlet.xml then It is giving ApplicationContext log
SEVERE: StandardWrapper.Throwable error which I do not understand please help with this.</p> | 0 | 4,735 |
ASPNETCORE_ENVIRONMENT in Docker | <p>i have problems setting the <strong>ASPNETCORE_ENVIRONMENT</strong> variable running my project in a <strong>docker container</strong>. The problem is that the value is always <strong>set/overwritten to "Development"</strong>.</p>
<p>I have tried setting the environment variable in my <strong>Dockerfile</strong> using </p>
<pre><code>ENV ASPNETCORE_ENVIRONMENT test
</code></pre>
<p>also tried setting the environment variable in my <strong>docker-compose</strong> file using </p>
<pre><code>environment:
- ASPNETCORE_ENVIRONMENT=test
</code></pre>
<p>When I set any other environment variable <strong>it works</strong>, for example:</p>
<pre><code>environment:
- OTHER_TEST_VARIABLE=test
</code></pre>
<p>I assume that the value for <strong>ASPNETCORE_ENVIRONMENT</strong> variable is overwritten somewhere but I have difficulties finding out where.</p>
<p>I have added Docker support to an existing project and am running the project directly via Visual Studio's Docker/Docker compose option </p>
<p>The project runs on Asp Net Core 2.1</p>
<p>Thanks in advance</p>
<p>My launchSettings.json:</p>
<pre><code>{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:53183/",
"sslPort": 0
}
},
"profiles": {
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://localhost:{ServicePort}/api/values"
}
}
}
</code></pre>
<p>I also tried adding the environment variable configuration to the launchSettings.json</p>
<pre><code>"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://localhost:{ServicePort}/api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "test"
}
}
</code></pre>
<p>My Webhost:</p>
<pre><code> public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((builderContext,config) =>
{
config.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>()
.Build();
}
</code></pre>
<p>My docker-compose.yml</p>
<pre><code>version: '3.4'
services:
api:
image: ${DOCKER_REGISTRY}api
build:
context: .
dockerfile: API/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=test
</code></pre>
<p>My Dockerfile:</p>
<pre><code>FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY API/API.csproj API/
RUN dotnet restore API/API.csproj
COPY . .
WORKDIR /src/API
RUN dotnet build API.csproj -c Release -o /app
FROM build AS publish
RUN dotnet publish API.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "API.dll"]
</code></pre>
<p>Here is a list of the environment variables in the container</p>
<pre><code>C:\Users\Administrator>docker exec -ti d6 /bin/bash
root@d6f26d2ed2c3:/app# printenv
HOSTNAME=d6f26d2ed2c3
ASPNETCORE_URLS=http://+:80
test1=asdasd
test2=dasdasd
test3=dasdasd
PWD=/app
HOME=/root
NUGET_FALLBACK_PACKAGES=/root/.nuget/fallbackpackages
DOTNET_USE_POLLING_FILE_WATCHER=1
ASPNETCORE_VERSION=2.1.3
DOTNET_RUNNING_IN_CONTAINER=true
TERM=xterm
SHLVL=1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ASPNETCORE_ENVIRONMENT=Development
_=/usr/bin/printenv
root@d6f26d2ed2c3:/app#
</code></pre> | 0 | 1,667 |
How do I change the Action Bar Overflow button color | <p>First off I have read <a href="https://stackoverflow.com/questions/11425660/change-color-of-the-overflow-button-on-actionbar">Change color of the overflow button on action bar</a> but
I'm not able to get it to work. </p>
<p>I just want to have a simple theme: Action bar background blue and the buttons and text white. For the list views that I have I want them to be the inverse: white background and blue text. If there is a simple way to achieve this please let me know.
I have tried setting text color using a style but I cannot get the text and the buttons to be different colors so I tried setting the overflow drawable and for testing purposes I made the dots red but don't see any effect.</p>
<pre><code> <!-- Application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="actionBarStyle">@style/ActionBarStyle</item>
</style>
<style name="ActionBarStyle" parent="Widget.AppCompat.ActionBar">
<item name="background">@color/background_blue</item>
<item name="titleTextStyle">@style/AppTheme.ActionBar.Title</item>
<item name="actionOverflowButtonStyle">@style/AppTheme.ActionButton.Overflow</item>
</style>
<style name="AppTheme.ActionBar.Title" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/white</item>
</style>
<style name="AppTheme.ActionButton.Overflow" parent="@style/Widget.AppCompat.ActionButton.Overflow">
<item name="android:src">@drawable/abc_ic_menu_overflow_button</item>
</style>
</code></pre>
<p>The overflow button that I'm using for testing
<a href="https://i.stack.imgur.com/goKrG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/goKrG.png" alt="The overflow button that I'm using for testing"></a></p>
<p>While what I see</p>
<p><a href="https://i.stack.imgur.com/rK4Xd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rK4Xd.png" alt="What I see"></a> </p>
<p>which clearly is not using the red buttons.</p>
<p>I was able to use the android:textColorPrimary attribute but that has undesirable side effects. </p>
<pre><code> <style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:textColorPrimary">@color/white</item>
<item name="actionBarStyle">@style/ActionBarStyle</item>
</style>
<style name="ActionBarStyle" parent="Widget.AppCompat.ActionBar">
<item name="background">@color/background_blue</item>
<item name="titleTextStyle">@style/AppTheme.ActionBar.Title</item>
</style>
<style name="AppTheme.ActionBar.Title" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/white</item>
</style>
</code></pre>
<p><a href="https://i.stack.imgur.com/iAMRs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iAMRs.png" alt="enter image description here"></a></p>
<p>but then since I want a white background for my lists I end up not being able to see some text since the text and background are both white.</p>
<p>Thanks!</p> | 0 | 1,168 |
The Microsoft.Office.Interop.Word assembly version is higher than referenced | <p>What is the cause of the following error:</p>
<blockquote>
<p>Error 12 Assembly 'Microsoft.Office.Interop.Word, Version=14.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c' uses 'office,
Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'
which has a higher version than referenced assembly 'office,
Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c' c:\Program Files\Microsoft Visual
Studio 10.0\Visual Studio Tools for
Office\PIA\Office14\Microsoft.Office.Interop.Word.dll WindowsFormsApplication1</p>
</blockquote>
<p>my code :</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using DataTable = System.Data.DataTable;
using Document = Microsoft.Office.Interop.Word.Document;
using Microsoft.Office;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var wordApp = new Application { Visible = false };
object objMissing = Missing.Value;
Document wordDoc = wordApp.Documents.Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing);
wordApp.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;
wordApp.Selection.TypeParagraph();
String docNumber = "1";
String revisionNumber = "0";
wordApp.Selection.Paragraphs.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
wordApp.ActiveWindow.Selection.Font.Name = "Arial";
wordApp.ActiveWindow.Selection.Font.Size = 8;
wordApp.ActiveWindow.Selection.TypeText("Document #: " + docNumber + " - Revision #: " + revisionNumber);
wordApp.ActiveWindow.Selection.TypeText("\t");
wordApp.ActiveWindow.Selection.TypeText("\t");
wordApp.ActiveWindow.Selection.TypeText("Page ");
Object CurrentPage = WdFieldType.wdFieldPage;
wordApp.ActiveWindow.Selection.Fields.Add(wordApp.Selection.Range, ref CurrentPage, ref objMissing, ref objMissing);
wordApp.ActiveWindow.Selection.TypeText(" of ");
Object TotalPages = WdFieldType.wdFieldNumPages;
wordApp.ActiveWindow.Selection.Fields.Add(wordApp.Selection.Range, ref TotalPages, ref objMissing, ref objMissing);
wordApp.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;
object c = "d:\\1.doc";
wordDoc.Paragraphs.LineSpacing = 8;
Paragraph wp = wordDoc.Paragraphs.Add(ref objMissing);
wp.Range.Text += richTextBox1.Text;
wordDoc.SaveAs(ref c, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
ref objMissing
, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
ref objMissing, ref objMissing
, ref objMissing, ref objMissing);
(wordDoc).Close(ref objMissing, ref objMissing, ref objMissing);
(wordApp).Quit(ref objMissing, ref objMissing, ref objMissing);
}
}
}
</code></pre> | 0 | 1,413 |
AttributeError: 'function' object has no attribute 'upper' | <p>When i run the given code i get the error</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\Users\Matthew\Desktop\Code\Functionised\encoder idea 2 GUI ATTEMPT.py", line 10, in encode
m = m.upper()
AttributeError: 'function' object has no attribute 'upper'
</code></pre>
<p>I know it is to do with the line - m = m.upper()</p>
<p>but i have no idea how to fix this</p>
<pre><code>import sys
import os.path
from tkinter import *
def encode():
array = []
temp_array = []
i = 0
m = message.get
m = m.upper()
array.append(m)
o = offset.get()
array.append(o)
length = len(array[0])
while length > i:
temp = array[0][i]
if temp == " ":
temp_array.append(temp)
i = i + 1
elif temp == ".":
temp_array.append(temp)
i = i + 1
elif (ord(temp) + o) <= 90 and (ord(temp) + o) >= 65:
#print("Easy option")
temp = ord(temp)
temp = temp + o
temp = chr(temp)
temp_array.append(temp)
i = i + 1
else:
#print("Hard option")
temp = ord(temp)
temp = temp + o
temp = (temp % 90) + 64
temp = chr(temp)
temp_array.append(temp)
i = i + 1
i = i - 1
temp = temp_array[i]
while i > 0:
i = i - 1
temp = temp_array[i] + temp
array.append(temp)
word = (array[2])
print(word)
my_file = open("messages.txt", "a") #Open the file messages or if it does not exist create it
for item in array: #Get all items in array
my_file.write(str(item)) #Write them to file
my_file.write("\n") #New line
my_file.close() #Close the file
gui = Tk()
gui.title("Caesar Cypher Encoder")
Button(gui, text="Encode", command=encode).grid(row = 3, column = 0)
Label(gui, text = "Message").grid(row = 1, column =0)
Label(gui, text = "Offset").grid(row = 1, column =1)
message = Entry(gui)
message.grid(row=2, column=0)
offset = Scale(gui, from_=1, to=25, orient=HORIZONTAL)
offset.grid(row=2, column=1)
mainloop( )
</code></pre>
<p>Before anyone asks - yes this was for my controlled assessment - WHICH IS NOW FINISHED - and i am using the code to learn more advanced features - eg tkinter</p> | 0 | 1,157 |
Unity-How do I check if an object is seen by the Main Camera | <p>I'm doing this thing where an object is moving on a plane, and the camera is in the center of it. I got it so the camera rotates along with the mouse, and when the main camera sees the game object, it stops. So I was using the onbecamevisible() and onbecameinvisible() functions, but that applies to any camera, including the scene view. How do I make it so the objects stops when seen only by the main game camera?</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cubeMove : MonoBehaviour,moveObject
{
Camera cam;
public Transform checkedObject;
void Start()
{
cam = GetComponent<Camera>();
}
void Update()
{
Vector3 viewPos = cam.WorldToViewportPoint(checkedObject.position);
if ()
move();
}
public void move()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}
</code></pre>
<p>}</p>
<p>Here's my Camera Script</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour {
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
float rotationX = 0F;
float rotationY = 0F;
private List<float> rotArrayX = new List<float>();
float rotAverageX = 0F;
private List<float> rotArrayY = new List<float>();
float rotAverageY = 0F;
public float frameCounter = 20;
Quaternion originalRotation;
void Update()
{
if (axes == RotationAxes.MouseXAndY)
{
rotAverageY = 0f;
rotAverageX = 0f;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotArrayY.Add(rotationY);
rotArrayX.Add(rotationX);
if (rotArrayY.Count >= frameCounter)
{
rotArrayY.RemoveAt(0);
}
if (rotArrayX.Count >= frameCounter)
{
rotArrayX.RemoveAt(0);
}
for (int j = 0; j < rotArrayY.Count; j++)
{
rotAverageY += rotArrayY[j];
}
for (int i = 0; i < rotArrayX.Count; i++)
{
rotAverageX += rotArrayX[i];
}
rotAverageY /= rotArrayY.Count;
rotAverageX /= rotArrayX.Count;
rotAverageY = ClampAngle(rotAverageY, minimumY, maximumY);
rotAverageX = ClampAngle(rotAverageX, minimumX, maximumX);
Quaternion yQuaternion = Quaternion.AngleAxis(rotAverageY, Vector3.left);
Quaternion xQuaternion = Quaternion.AngleAxis(rotAverageX, Vector3.up);
transform.localRotation = originalRotation * xQuaternion * yQuaternion;
}
else if (axes == RotationAxes.MouseX)
{
rotAverageX = 0f;
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotArrayX.Add(rotationX);
if (rotArrayX.Count >= frameCounter)
{
rotArrayX.RemoveAt(0);
}
for (int i = 0; i < rotArrayX.Count; i++)
{
rotAverageX += rotArrayX[i];
}
rotAverageX /= rotArrayX.Count;
rotAverageX = ClampAngle(rotAverageX, minimumX, maximumX);
Quaternion xQuaternion = Quaternion.AngleAxis(rotAverageX, Vector3.up);
transform.localRotation = originalRotation * xQuaternion;
}
else
{
rotAverageY = 0f;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotArrayY.Add(rotationY);
if (rotArrayY.Count >= frameCounter)
{
rotArrayY.RemoveAt(0);
}
for (int j = 0; j < rotArrayY.Count; j++)
{
rotAverageY += rotArrayY[j];
}
rotAverageY /= rotArrayY.Count;
rotAverageY = ClampAngle(rotAverageY, minimumY, maximumY);
Quaternion yQuaternion = Quaternion.AngleAxis(rotAverageY, Vector3.left);
transform.localRotation = originalRotation * yQuaternion;
}
}
void Start()
{
Rigidbody rb = GetComponent<Rigidbody>();
if (rb)
rb.freezeRotation = true;
originalRotation = transform.localRotation;
}
public static float ClampAngle(float angle, float min, float max)
{
angle = angle % 360;
if ((angle >= -360F) && (angle <= 360F))
{
if (angle < -360F)
{
angle += 360F;
}
if (angle > 360F)
{
angle -= 360F;
}
}
return Mathf.Clamp(angle, min, max);
}
</code></pre>
<p>}</p>
<p>SphereMove</p>
<pre><code>public class sphereMove : MonoBehaviour,moveObject {
public float delta = 1.5f;
public float speed = 2.0f;
private Vector3 startPos;
public UnityEngine.Camera cam;
public Transform checkedObject;
bool isMoving;
void Start()
{
isMoving = true;
cam = Camera.main;
}
void Update()
{
Vector3 viewPos = cam.WorldToViewportPoint(checkedObject.position);
if (viewPos.x > 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1 && viewPos.z > 0)
isMoving = false;
else
isMoving = true;
if (isMoving)
move();
}
public void move()
{
Vector3 v = startPos;
v.x += delta * Mathf.Sin(Time.time * speed);
transform.position = v;
}
</code></pre>
<p>}</p> | 0 | 2,378 |
Difference between adjustResize and adjustPan in android? | <p>I tried to write a code which is used to re-size the UI components when <strong>soft-keyboard</strong> appears.
When I use <strong>adjustResize,</strong> it res-size the UI components and at the same time <strong>adjustPan</strong> gave me same output.
I want to know the difference between them and when to use each component? Which one(adjustPan or adjustResize) is good for resizing UI? </p>
<p>Here is my xml: </p>
<pre><code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
<EditText
android:id="@+id/editText5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="45dp"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:text="My Button" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
</code></pre>
<p>and the menifest file: </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.adjustscroll"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.adjustscroll.MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="adjustPan|adjustResize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre> | 0 | 1,230 |
What is $$phase in AngularJS? | <p>I found this code snippet which is part of a angular directive someone wrote for bootstrap modal.</p>
<pre><code>//Update the visible value when the dialog is closed
//through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
</code></pre>
<p>I understood that this part is for the latter half of two way binding we bind to hide.bs.modal event and update modal when UI changes.</p>
<p>I just wanted to know why is the person checking $$phase for scope and rootScope before calling apply ?</p>
<p>Can't we straightaway call apply ?</p>
<p>What is $$phase here?</p>
<p>I tried searching a lot, couldn't find any good explanation. </p>
<p><strong>EDIT:</strong></p>
<p><strong>I found where I saw the example:</strong>
<a href="https://stackoverflow.com/questions/19644405/simple-angular-directive-for-bootstrap-modal">Simple Angular Directive for Bootstrap Modal</a></p> | 0 | 1,729 |
Creating a matrix from CSV file | <p>I've been working on Python for around 2 months now so I have a OK understanding of it. </p>
<p>My goal is to create a matrix using CSV data, then populating that matrix from the data in the 3rd column of that CSV file.</p>
<p>I came up with this code thus far:</p>
<pre><code>import csv
import csv
def readcsv(csvfile_name):
with open(csvfile_name) as csvfile:
file=csv.reader(csvfile, delimiter=",")
#remove rubbish data in first few rows
skiprows = int(input('Number of rows to skip? '))
for i in range(skiprows):
_ = next(file)
#change strings into integers/floats
for z in file:
z[:2]=map(int, z[:2])
z[2:]=map(float, z[2:])
print(z[:2])
return
</code></pre>
<p>After removing the rubbish data with the above code, the data in the CSV file looks like this:</p>
<pre><code> Input:
1 1 51 9 3
1 2 39 4 4
1 3 40 3 9
1 4 60 2 .
1 5 80 2 .
2 1 40 6 .
2 2 28 4 .
2 3 40 2 .
2 4 39 3 .
3 1 10 . .
3 2 20 . .
3 3 30 . .
3 4 40 . .
. . . . .
</code></pre>
<p>The output should look like this:</p>
<pre><code> 1 2 3 4 . .
1 51 39 40 60
2 40 28 40 39
3 10 20 30 40
.
.
</code></pre>
<p>There are about a few thousand rows and columns in this CSV file, however I'm only interested is the first 3 columns of the CSV file. So the first and second columns are basically like co-ordinates for the matrix, and then populating the matrix with data in the 3rd column.</p>
<p>After lots of trial and error, I realised that numpy was the way to go with matrices. This is what I tried thus far with example data:</p>
<pre><code> left_column = [1, 2, 1, 2, 1, 2, 1, 2]
middle_column = [1, 1, 3, 3, 2, 2, 4, 4]
right_column = [1., 5., 3., 7., 2., 6., 4., 8.]
import numpy as np
m = np.zeros((max(left_column), max(middle_column)), dtype=np.float)
for x, y, z in zip(left_column, middle_column, right_column):
x -= 1 # Because the indicies are 1-based
y -= 1 # Need to be 0-based
m[x, y] = z
print(m)
#: array([[ 1., 2., 3., 4.],
#: [ 5., 6., 7., 8.]])
</code></pre>
<p>However, it is unrealistic for me to specify all of my data in my script to generate the matrix. I tried using the generators to pull the data out of my CSV file but it didn't work well for me.</p>
<p>I learnt as much numpy as I could, however it appears like it requires my data to already be in matrix form, which it isn't.</p> | 0 | 1,057 |
Dropdown menu moves content | <p>My problem is quite simple but i don't know what i've done bad..</p>
<p>Dropdown menu on my site moves content.I've tried a z-index with absolute and relative position but it did not worked.Maybe i've screwed something up but right now i don't know what</p>
<p>Thanks for help and Greets</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font-family: 'Segoe UI', sans-serif;
}
#logo {
margin-top: 15px;
margin-left: 10px;
float: left;
font-size: 30px;
color: white;
}
.menu>ul {
list-style-type: none;
width: 100%;
background-color: #333;
min-height: 130px;
}
#fest {
margin-left: 280px;
}
#pierwszy {
clear: both;
}
.element {
width: 120px;
height: auto;
display: inline-block;
padding: 10px;
color: white;
text-align: center;
font-size: 20px;
}
.menu>ul>li {
float: left;
margin-left: 30px;
margin-top: 30px;
}
.element:hover {
background-color: #555;
cursor: pointer;
}
.menu>#logo>p {
font-size: 40px;
color: white;
}
a {
text-decoration: none;
color: white;
}
.menu>ul>li>ul {
margin: 0;
padding: 0;
list-style-type: none;
display: none;
}
.menu>ul>li:hover>ul {
display: block;
}
.menu>ul>li:hover>ul:hover>li:hover {
display: block;
background-color: #666;
}
.menu>ul>li>ul>li {
margin: 10px;
}
.jumbotron {
background-color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang="pl">
<head>
<meta charset="utf-8" />
<title>
LOREN IPSUM DZIADU !
</title>
<meta name="description" content="nananananana moje testy i zabawy" />
<meta name="keywords" content="moje,nowe,zabawy,strony,html" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="topbar">
<div id="logo">
<a href="index.html">
<img src="developer.png" width=220px height=90px;>
</a>
</div>
<nav class="menu">
<!--<img src="pan.jpg" alt=" "!-->
<ul>
<li class="element"><a href="#">Something</a>
<ul>
<li>Something</li>
<li>Something</li>
<li>Something</li>
</ul>
</li>
<li class="element"><a href="#">Something</a>
<ul>
<li>Something</li>
<li>Something</li>
<li>Something</li>
</ul>
<li class="element">Something</li>
<li class="element">Something</li>
</ul>
</nav>
<br/>
<br/>
</div>
</div>
<article>
<img id="fest" src="fest.jpg" width=320px height=350px;>
</a>
<p>Proin vel luctus urna, a suscipit lectus. Quisque aliquam sollicitudin feugiat. In et venenatis nisl, at mattis arcu. Quisque dictum posuere dui eu luctus. Quisque dignissim ipsum orci, sed malesuada nibh posuere quis. Vestibulum venenatis hendrerit
enim a scelerisque. Integer fringilla diam et mauris viverra, eget ornare eros faucibus. Phasellus id ex vitae lacus porta pulvinar.</p>
</article>
<article>
<p>Mauris urna sapien, molestie quis vulputate et, interdum vitae massa. Suspendisse dolor velit, imperdiet eu bibendum vitae, finibus quis lorem. Morbi ultricies lorem quis dui hendrerit luctus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis scelerisque varius leo. Quisque malesuada tortor id risus posuere, sodales rutrum nunc tristique. Vivamus pulvinar id leo ut fringilla.</p>
</article>
<!-- Latest compiled and minified JavaScript -->
<script>
src = "js/bootstrap.min.js"
</script>
</body></code></pre>
</div>
</div>
</p> | 0 | 2,089 |
The request sent by the client was syntactically incorrect.-Spring MVC + JDBC Template | <p>I am newbie to Spring MVC.
I was stuck by an error while running my project
<strong>Error-The request sent by the client was syntactically incorrect.</strong>
I have an entity class PatientInfo.
My jsp page is demo1.
My controller is Patient Controller.
The functionality i want to implement is Inserting values into database.
But i am not able to call my function(add-update2) in controller.</p>
<p>demo1.jsp</p>
<pre><code> <%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2 align="center">Full Registration Form</h2>
<hr />
<table align="center" cellpadding="5" cellspacing="5">
<form:form modelAttribute="patientInfo" method="POST" action="add-update2">
<tr>
<td> First Name</td>
<td><form:input path="firstName"/></td>
</tr>
<tr>
<td>Middle Name</td>
<td><form:input path="middleName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><form:input path="lastName"/>
</td>
</tr>
<tr>
<td>Age</td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td>Gender</td>
<td><form:select path="gender">
<form:option value="" label="Select Gender" />
<form:options items="${genderList}" itemLabel="gender" itemValue="gender" />
</form:select></td>
</tr>
<tr>
<td>Marital Status</td>
<td><form:select path="maritalStatus">
<form:option value="" label="Select Marital Status" />
<form:options items="${maritalList}" itemLabel="maritalstatus" itemValue="maritalstatus" />
</form:select></td>
</tr>
<tr>
<td>Nationality</td>
<td><form:select path="nationality">
<form:option value="" label="Select Nationality" />
<form:options items="${nationalityList}" itemLabel="country" itemValue="country" />
</form:select></td>
</tr>
<tr name="tstest">
<td>Date Of Birth</td>
<td><form:input path="dateOfBirth" name="timestamp" value=""/>
<a href="javascript:show_calendar('document.tstest.timestamp', document.tstest.timestamp.value);"><img src="../images/cal.gif" width="16" height="16" border="0" alt="Click Here to Pick up the timestamp"></a>
</td>
</tr>
<tr>
<td>E-mail</td>
<td><form:input path="email"/></td>
</tr>
<tr>
<td>Blood Group</td>
<td><form:select path="bloodGroup">
<form:option value="" label="Select Blood Group" />
<form:options items="${bloodList}" itemLabel="bloodgroupname" itemValue="bloodgroupname" />
</form:select></td>
</tr>
<tr>
<td><input type="submit" value="submit"/></td>
</tr>
</form:form>
</table>
</body>
</html>
</code></pre>
<p>Controller-PatientController.java</p>
<pre><code>package com.app.ehr.api;
import com.app.ehr.domain.Bloodgroup;
import com.app.ehr.domain.Gendertype;
import com.app.ehr.entities.Patientinfo;
import com.app.ehr.domain.Maritalstatus;
import com.app.ehr.domain.Nationality;
import com.app.ehr.model.Patient;
import com.app.ehr.service.PatientService;
import org.springframework.stereotype.Controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class PatientController {
public PatientService patientService;
@Autowired
public PatientController(PatientService patientService){
this.patientService = patientService;
}
@RequestMapping(value="/", method= RequestMethod.GET)
public String index(ModelMap map) {
return "index";
}
@RequestMapping(value="/full-reg", method= RequestMethod.GET)
public String fullreg(ModelMap map,Patientinfo patientInfo) {
List<Bloodgroup> bloodList = new ArrayList<Bloodgroup>();
List<Gendertype> genderList = new ArrayList<Gendertype>();
List<Nationality> nationalityList = new ArrayList<Nationality>();
List<Maritalstatus> maritalList = new ArrayList<Maritalstatus>();
bloodList=patientService.getAllBloodgroup();
genderList= patientService.getAllGendertype();
nationalityList=patientService.getAllNationality();
maritalList=patientService.getAllMaritalstatus();
for(int i=0;i<bloodList.size();i++)
{
System.out.println("---------------------Controller"+bloodList.get(i));
}
// map.addAttribute("hello", "Hello Spring from Netbeans!!");
map.addAttribute("patientInfo", patientInfo);
map.addAttribute("bloodList", patientService.getAllBloodgroup());
map.addAttribute("genderList", patientService.getAllGendertype());
map.addAttribute("maritalList", patientService.getAllMaritalstatus());
map.addAttribute("nationalityList", patientService.getAllNationality());
return "demo1";
}
@RequestMapping(value="/add-update2", method= RequestMethod.POST)
public String addUpdate(@ModelAttribute("patientInfo") Patientinfo patientInfo) {
System.out.println("----------------------------------------- From Controller------------------------------------------------");
//patientService.addPatient(patientInfo);
return "redirect:/full-reg";
}
}
</code></pre>
<p>Entity Class- PatientInfo.java</p>
<pre><code>package com.app.ehr.entities;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author HP LAPTOP
*/
@Entity
@Table(name = "patientinfo")
@NamedQueries({
@NamedQuery(name = "Patientinfo.findAll", query = "SELECT p FROM Patientinfo p")})
public class Patientinfo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "PatientKey")
private Long patientKey;
@Column(name = "PatientMRNumber")
private String patientMRNumber;
@Column(name = "IntPrimaryPhysicianKey")
private BigInteger intPrimaryPhysicianKey;
@Column(name = "FirstName")
private String firstName;
@Column(name = "MiddleName")
private String middleName;
@Column(name = "LastName")
private String lastName;
@Column(name = "Age")
private Short age;
@Column(name = "Gender")
private String gender;
@Column(name = "Nationality")
private String nationality;
@Column(name = "DateOfBirth")
@Temporal(TemporalType.TIMESTAMP)
private Date dateOfBirth;
@Column(name = "MaritalStatus")
private String maritalStatus;
@Column(name = "Occupation")
private String occupation;
@Column(name = "AnnualIncome")
private String annualIncome;
@Column(name = "BloodGroup")
private String bloodGroup;
@Column(name = "Email")
private String email;
@Column(name = "ModeOfPayment")
private String modeOfPayment;
@Column(name = "ModeOfPaymentAlt")
private String modeOfPaymentAlt;
@Column(name = "ExtPrimaryPhysicianName")
private String extPrimaryPhysicianName;
@Column(name = "ExtPrimaryPhysicianPhoneNumber")
private String extPrimaryPhysicianPhoneNumber;
@Column(name = "IsDeleted")
private Boolean isDeleted;
@Column(name = "Meta_CreatedByUser")
private String metaCreatedByUser;
@Column(name = "Meta_UpdatedDT")
@Temporal(TemporalType.TIMESTAMP)
private Date metaUpdatedDT;
@Column(name = "Meta_CreatedDT")
@Temporal(TemporalType.TIMESTAMP)
private Date metaCreatedDT;
public Patientinfo() {
}
public Patientinfo(Long patientKey) {
this.patientKey = patientKey;
}
public Long getPatientKey() {
return patientKey;
}
public void setPatientKey(Long patientKey) {
this.patientKey = patientKey;
}
public String getPatientMRNumber() {
return patientMRNumber;
}
public void setPatientMRNumber(String patientMRNumber) {
this.patientMRNumber = patientMRNumber;
}
public BigInteger getIntPrimaryPhysicianKey() {
return intPrimaryPhysicianKey;
}
public void setIntPrimaryPhysicianKey(BigInteger intPrimaryPhysicianKey) {
this.intPrimaryPhysicianKey = intPrimaryPhysicianKey;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Short getAge() {
return age;
}
public void setAge(Short age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getAnnualIncome() {
return annualIncome;
}
public void setAnnualIncome(String annualIncome) {
this.annualIncome = annualIncome;
}
public String getBloodGroup() {
return bloodGroup;
}
public void setBloodGroup(String bloodGroup) {
this.bloodGroup = bloodGroup;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getModeOfPayment() {
return modeOfPayment;
}
public void setModeOfPayment(String modeOfPayment) {
this.modeOfPayment = modeOfPayment;
}
public String getModeOfPaymentAlt() {
return modeOfPaymentAlt;
}
public void setModeOfPaymentAlt(String modeOfPaymentAlt) {
this.modeOfPaymentAlt = modeOfPaymentAlt;
}
public String getExtPrimaryPhysicianName() {
return extPrimaryPhysicianName;
}
public void setExtPrimaryPhysicianName(String extPrimaryPhysicianName) {
this.extPrimaryPhysicianName = extPrimaryPhysicianName;
}
public String getExtPrimaryPhysicianPhoneNumber() {
return extPrimaryPhysicianPhoneNumber;
}
public void setExtPrimaryPhysicianPhoneNumber(String extPrimaryPhysicianPhoneNumber) {
this.extPrimaryPhysicianPhoneNumber = extPrimaryPhysicianPhoneNumber;
}
public Boolean getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
public String getMetaCreatedByUser() {
return metaCreatedByUser;
}
public void setMetaCreatedByUser(String metaCreatedByUser) {
this.metaCreatedByUser = metaCreatedByUser;
}
public Date getMetaUpdatedDT() {
return metaUpdatedDT;
}
public void setMetaUpdatedDT(Date metaUpdatedDT) {
this.metaUpdatedDT = metaUpdatedDT;
}
public Date getMetaCreatedDT() {
return metaCreatedDT;
}
public void setMetaCreatedDT(Date metaCreatedDT) {
this.metaCreatedDT = metaCreatedDT;
}
@Override
public int hashCode() {
int hash = 0;
hash += (patientKey != null ? patientKey.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Patientinfo)) {
return false;
}
Patientinfo other = (Patientinfo) object;
if ((this.patientKey == null && other.patientKey != null) || (this.patientKey != null && !this.patientKey.equals(other.patientKey))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.app.ehr.entities.Patientinfo[ patientKey=" + patientKey + " ]";
}
}
</code></pre> | 0 | 5,959 |
CodeIgniter - adding comments to a post | <p>I'd like some help please. I have a post page that has the full post and below the post a small form for adding comments. The uri of the post page is: site/posts/1, so it is in posts controller, and the form action is <code>form_open(site_url('comments/add/'.$post->post_id))</code>.</p>
<p>This is my add() function inside comments controller:</p>
<pre><code>public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$result = $this->comment_model->add($post_id);
if ($result !== false) {
redirect('posts/'.$post_id);
}
// TODO:load the view if required
}
</code></pre>
<p>and this is the add() function inside the comment model</p>
<pre><code>public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
if ($this->validate($post_data)) {
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
} else {
return false;
}
}
</code></pre>
<p>What I'm trying to do is if the $result = $this->comment_model->add($post_id); fails the validation to display the validation errors in my post view, else insert the comment and redirect to the same post page (site/posts/1). </p>
<p>The problem is that when I hit submit the form action goes in the comments/add/1, as expected, but doesn't do any these above.</p>
<p>Any ideas how can I fix this??</p>
<p><strong>EDIT</strong>
I did a small change to the code without the 'confusing' validate() function. Maybe this is more helpful.</p>
<p>Comment controller:</p>
<pre><code> public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
echo "Ok! TODO save the comment.";
// $this->comment_model->add($post_id);
// redirect('posts/'.$post_id);
} else {
echo "Validation Failed! TODO: show validation errors!";
}
// TODO:load the view if required
}
</code></pre>
<p>Comment model:</p>
<pre><code> public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
}
</code></pre> | 0 | 1,269 |
My Algorithm to Calculate Position of Smartphone - GPS and Sensors | <p>I am developing an android application to calculate position based on Sensor's Data</p>
<ol>
<li><p>Accelerometer --> Calculate Linear Acceleration</p></li>
<li><p>Magnetometer + Accelerometer --> Direction of movement</p></li>
</ol>
<p>The initial position will be taken from GPS (Latitude + Longitude).</p>
<p>Now based on Sensor's Readings i need to calculate the new position of the Smartphone:</p>
<p>My Algorithm is following - (But is not calculating Accurate Position): Please help me improve it.</p>
<p><strong>Note:</strong> <strong>My algorithm Code is in C# (I am sending Sensor Data to Server - Where Data is stored in the Database. I am calculating the position on Server)</strong></p>
<p><strong>All DateTime Objects have been calculated using TimeStamps - From 01-01-1970</strong></p>
<pre><code> var prevLocation = ServerHandler.getLatestPosition(IMEI);
var newLocation = new ReceivedDataDTO()
{
LocationDataDto = new LocationDataDTO(),
UsersDto = new UsersDTO(),
DeviceDto = new DeviceDTO(),
SensorDataDto = new SensorDataDTO()
};
//First Reading
if (prevLocation.Latitude == null)
{
//Save GPS Readings
newLocation.LocationDataDto.DeviceId = ServerHandler.GetDeviceIdByIMEI(IMEI);
newLocation.LocationDataDto.Latitude = Latitude;
newLocation.LocationDataDto.Longitude = Longitude;
newLocation.LocationDataDto.Acceleration = float.Parse(currentAcceleration);
newLocation.LocationDataDto.Direction = float.Parse(currentDirection);
newLocation.LocationDataDto.Speed = (float) 0.0;
newLocation.LocationDataDto.ReadingDateTime = date;
newLocation.DeviceDto.IMEI = IMEI;
// saving to database
ServerHandler.SaveReceivedData(newLocation);
return;
}
//If Previous Position not NULL --> Calculate New Position
**//Algorithm Starts HERE**
var oldLatitude = Double.Parse(prevLocation.Latitude);
var oldLongitude = Double.Parse(prevLocation.Longitude);
var direction = Double.Parse(currentDirection);
Double initialVelocity = prevLocation.Speed;
//Get Current Time to calculate time Travelling - In seconds
var secondsTravelling = date - tripStartTime;
var t = secondsTravelling.TotalSeconds;
//Calculate Distance using physice formula, s= Vi * t + 0.5 * a * t^2
// distanceTravelled = initialVelocity * timeTravelling + 0.5 * currentAcceleration * timeTravelling * timeTravelling;
var distanceTravelled = initialVelocity * t + 0.5 * Double.Parse(currentAcceleration) * t * t;
//Calculate the Final Velocity/ Speed of the device.
// this Final Velocity is the Initil Velocity of the next reading
//Physics Formula: Vf = Vi + a * t
var finalvelocity = initialVelocity + Double.Parse(currentAcceleration) * t;
//Convert from Degree to Radians (For Formula)
oldLatitude = Math.PI * oldLatitude / 180;
oldLongitude = Math.PI * oldLongitude / 180;
direction = Math.PI * direction / 180.0;
//Calculate the New Longitude and Latitude
var newLatitude = Math.Asin(Math.Sin(oldLatitude) * Math.Cos(distanceTravelled / earthRadius) + Math.Cos(oldLatitude) * Math.Sin(distanceTravelled / earthRadius) * Math.Cos(direction));
var newLongitude = oldLongitude + Math.Atan2(Math.Sin(direction) * Math.Sin(distanceTravelled / earthRadius) * Math.Cos(oldLatitude), Math.Cos(distanceTravelled / earthRadius) - Math.Sin(oldLatitude) * Math.Sin(newLatitude));
//Convert From Radian to degree/Decimal
newLatitude = 180 * newLatitude / Math.PI;
newLongitude = 180 * newLongitude / Math.PI;
</code></pre>
<p>This is the Result I get --> Phone was not moving. As you can see <em>speed is 27.3263111114502</em> <strong>So there is something wrong in calculating Speed but I don't know what</strong></p>
<p><img src="https://i.stack.imgur.com/oi3NR.png" alt="enter image description here"></p>
<p><strong>ANSWER:</strong></p>
<p>I found a solution to calculate position based on Sensor: I have posted an Answer below.</p>
<p>If you need any help, please leave a comment</p>
<p>this is The results compared to GPS (<strong>Note:</strong> GPS is in Red)</p>
<p><img src="https://i.stack.imgur.com/3QjcP.png" alt="enter image description here"></p> | 0 | 1,607 |
Bootstrap 3 Navbar Collapse menu at Left for left and right navbar items | <p>I have a Bootstrap 3 navbar with left nav items and right nav items (as shown below). </p>
<p><img src="https://i.stack.imgur.com/pCkke.jpg" alt="Left and Right nav items"></p>
<p>When collapsed, I want both the navbar-toggle (AKA the 'hamburger menu') and its items to be left aligned. </p>
<p>My code so far:</p>
<pre><code><nav class="navbar navbar-default custom-navbar" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#">Left</a></li>
<li><a href="#about">Left</a></li>
</ul>
<ul class="nav navbar-nav pull-right">
<li><a href="#about">Right</a></li>
<li><a href="#contact">Right</a></li>
</ul>
</div>
</nav>
</code></pre>
<p>The CSS to have the navbar-toggle on the left is:</p>
<pre class="lang-css prettyprint-override"><code>@media (max-width:767px) {
.custom-navbar .navbar-right {
float: right;
padding-right: 15px;
}
.custom-navbar .nav.navbar-nav.navbar-right li {
float: left;
}
.custom-navbar .nav.navbar-nav.navbar-right li > a {
padding:8px 5px;
}
.custom-navbar .navbar-toggle {
float: left;
margin-right: 0
}
.custom-navbar .navbar-header {
float: left;
width: auto!important;
}
.custom-navbar .navbar-collapse {
clear: both;
float: none;
}
}
</code></pre>
<p>I have added a "pull-right" style to have the items aligned, with no success.</p>
<p>The "navbar-right" works badly. In fact, with it, I will have both right-hand items on the same row.
Using "pull-right" they work as single rows, but still stay on the right.</p>
<p>This leaves me with:</p>
<ul>
<li>The hamburger menu on the left (as desired),</li>
<li>The navbar-left items on the left (as desired),</li>
<li>The navbar right items <em>are still on the right</em> (I want this to be fixed!).</li>
</ul>
<p>The final result:</p>
<p><img src="https://i.stack.imgur.com/Gqtu0.jpg" alt="The last two elements are still on the right"></p>
<p>The code snippet is <a href="http://www.bootply.com/JJOrdaJtoY" rel="nofollow noreferrer">here</a>.</p> | 0 | 1,200 |
java.io.StreamCorruptedException: invalid stream header: 75720002 | <p>i am creating a server-client application where the server sends a pdf file to the all connected clients. The problem is i get this error and i searched for a solution but couldn`t get any. This is the error</p>
<pre><code> java.io.StreamCorruptedException: invalid stream header: 75720002
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:782)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at StudentThread.run(StudentThread.java:102)
</code></pre>
<p>Here is the server sending code:</p>
<pre><code>public void run()
{
try
{
String modifiedSentence;
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
inFromServer = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream())), true);
//String sentence;
System.out.println("TeachID. "+id);
modifiedSentence = in.readLine();
System.out.println("Student "+id+" says:"+modifiedSentence);
arrS=modifiedSentence.split(" ");
out.println("Hello "+arrS[2]+","+id);
studName=arrS[2];
((DefaultListModel) Teacher.made_list.getModel()).addElement(studName);
while( true )
{
modifiedSentence = in.readLine();
arrS=modifiedSentence.split(" ");
if(arrS[0].equals("AcceptFile"))
{
try
{
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
byte[] buffer = (byte[])ois.readObject();
String pic="copyServer"+id+".pdf";
System.out.println(pic);
FileOutputStream fos = new FileOutputStream(pic);
fos.write(buffer);
fos.flush();
fos.close();
}
catch(Exception e)
{
System.out.println("Exception writing");
}
}
}
catch (IOException e)
{
}
finally
{
try
{
socket.close();
}
catch(IOException e)
{
}
}
}
public void sendF(String fn,Teacher teach)
{
try{
out.println("AcceptFile,");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()) ;
FileInputStream fis = new FileInputStream(fn);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
//ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()) ;
oos.writeObject(buffer);
oos.flush();
fis.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public void sendThread(String elem, Teacher teach)
{
out.println(elem);
//System.out.println ("Thread id is " + this.id);
System.out.println(this.socket.getInetAddress());
}
</code></pre>
<p>Here is the client receiving code:</p>
<pre><code>public void run()
{
try
{
out=new PrintWriter(socket.getOutputStream(), true);
out.println("Hello Server "+name+",");
String modifiedSentence;
BufferedReader inFromServer = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
modifiedSentence = inFromServer.readLine();
System.out.println( modifiedSentence );
arrT=modifiedSentence.split(",");
if(arrT[0].equals("Hello "+name))
{
studId=Integer.parseInt(arrT[2]);
System.out.println("My Id="+studId);
}
while( true )
{
modifiedSentence = inFromServer.readLine();
System.out.println( modifiedSentence );
arrT=modifiedSentence.split(",");
if(arrT[0].equals("AcceptFile"))
{
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
byte[] buffer = (byte[])ois.readObject();
String pic="copyServer"+studId+".gif";
System.out.println(pic);
FileOutputStream fos = new FileOutputStream(pic);
fos.write(buffer);
fos.flush();
fos.close();
}
}
}
catch( Exception e )
{
e.printStackTrace();
}
}
</code></pre> | 0 | 2,053 |
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997) | <p>I was playing with some web frameworks for Python, when I tried to use the framework <a href="https://docs.aiohttp.org/en/stable/" rel="nofollow noreferrer">aiohhtp</a> with this code (taken from the documentation):</p>
<pre><code>import aiohttp
import asyncio
#********************************
# a solution I found on the forum:
# https://stackoverflow.com/questions/50236117/scraping-ssl-certificate-verify-failed-error-for-http-en-wikipedia-org?rq=1
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# ... but it doesn't work :(
#********************************
async def main():
async with aiohttp.ClientSession() as session:
async with session.get("https://python.org") as response:
print("Status:", response.status)
print("Content-type:", response.headers["content-type"])
html = await response.text()
print("Body:", html[:15], "...")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</code></pre>
<p>When I run this code I get this traceback:</p>
<pre><code>DeprecationWarning: There is
no current event loop
loop = asyncio.get_event_loop()
Traceback (most recent call last):
File "c:\Python310\lib\site-packages\aiohttp\connector.py", line 986, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore[return-value] # noqa
File "c:\Python310\lib\asyncio\base_events.py", line 1080, in create_connection
transport, protocol = await self._create_connection_transport(
File "c:\Python310\lib\asyncio\base_events.py", line 1110, in _create_connection_transport
await waiter
File "c:\Python310\lib\asyncio\sslproto.py", line 528, in data_received
ssldata, appdata = self._sslpipe.feed_ssldata(data)
File "c:\Python310\lib\asyncio\sslproto.py", line 188, in feed_ssldata
self._sslobj.do_handshake()
File "c:\Python310\lib\ssl.py", line 974, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\chris\Documents\Programmi_in_Python_offline\Esercitazioni\Python_commands\aioWebTest.py", line 21, in <module>
loop.run_until_complete(main())
File "c:\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
return future.result()
File "c:\Users\chris\Documents\Programmi_in_Python_offline\Esercitazioni\Python_commands\aioWebTest.py", line 12, in main
async with session.get("https://python.org") as response:
File "c:\Python310\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__
self._resp = await self._coro
File "c:\Python310\lib\site-packages\aiohttp\client.py", line 535, in _request
conn = await self._connector.connect(
File "c:\Python310\lib\site-packages\aiohttp\connector.py", line 542, in connect
proto = await self._create_connection(req, traces, timeout)
File "c:\Python310\lib\site-packages\aiohttp\connector.py", line 907, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "c:\Python310\lib\site-packages\aiohttp\connector.py", line 1206, in _create_direct_connection
raise last_exc
File "c:\Python310\lib\site-packages\aiohttp\connector.py", line 1175, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "c:\Python310\lib\site-packages\aiohttp\connector.py", line 988, in _wrap_create_connection
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host python.org:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)')]
</code></pre>
<p>From the final row I have thought that it was a problem with a certificate that is expired, so I searched on the internet and I tried to solve installing some certificates:</p>
<ul>
<li><a href="https://crt.sh/?id=2835394" rel="nofollow noreferrer">COMODO ECC Certification Authority</a>;</li>
<li>three certificates that I took from the site <a href="https://www.python.org" rel="nofollow noreferrer">www.python.org</a> under <a href="https://stackoverflow.com/users/4445768/bango">Bango</a>'s advice for the <a href="https://stackoverflow.com/questions/63742983/certificate-verify-failed-certificate-has-expired-ssl-c-when-attempti">question</a>:<img src="https://i.postimg.cc/85YsRrw3/immagine-2021-12-05-181731.png" alt="" /></li>
</ul>
<p>I'm sorry for the long question, but I searched a lot on the internet and I couldn't find the solution for my case.
Thank you in advance, guys <3</p> | 0 | 1,878 |
html side by side tables in email are forced under in Outlook 2007 and above | <p>I have just run into my first frustration with Outlook breaking my html emails.</p>
<p>I have a container table that is 640 px wide. In it is two 320px tables one align left, one align right.
They site side by side in ALL email clients except Word Engined Outlook (2007 and up).</p>
<p>THIS is the important part. I have code to make the containing table become 320px wide when viewed on mobile phone. This forces the two tables to be one on top of the other.
This works exactly as planned for mobiles.</p>
<p>But Outlook on a desktop renders the left aligned table, then below it it renders the right hand table below the left but still aligned to the right, creating a big gap beneath the left hand table and a big gap above the right hand table.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
img
{display:block;}
a
{text-decoration:none;}
a:hover
{text-decoration: underline !important;}
td.contentblock p {
color:#FFFFFF;
font-size:16px;
font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;
margin-top:0;
margin-bottom:12px;
padding-top:0;
padding-bottom:0;
font-weight:normal;
}
td.contentblock p a {
color:#e45808;
text-decoration:none;
}
.heading {
font-size:24px;
font-weight:bold;
}
@media only screen and (max-device-width: 480px) {
table[class="table"], td[class="cell"] {
width: 320px !important;
}
td[class="footershow"] {
width: 320px !important;
}
table[class="hide"], img[class="hide"], td[class="hide"], br[class="hide"], div[class="hide"] {
display: none !important;
}
img[class="divider"] {
height: 1px !important;
}
img[id="header"] {
width: 320px !important;
height: 69px !important;
}
img[id="main"] {
width: 320px !important;
height: 45px !important;
}
img[id="footer"] {
width: 320px !important;
height: 43px !important;
}
p[class="reminder"] {
font-size: 11px !important;
}
span[class="secondary"] {
line-height: 20px !important;
margin-bottom: 15px !important;
font-size: 13px !important;
}
}
</style>
</head>
<body bgcolor="#e4e4e4" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="-webkit-font-smoothing: antialiased;width:100% !important;background:#e4e4e4;-webkit-text-size-adjust:none;">
<table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#EEEEEE">
<tr>
<td bgcolor="#EEEEEE" width="100%">
<table width="640" cellpadding="0" cellspacing="0" border="0" align="center" class="table">
<tr>
<td width="640" class="cell" style="color:#FFF;">
<table class="table" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td bgcolor="#cc6600" class="contentblock cell" style="color:#FFFFFF;font-size:16px;font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;">
<table width="320" bgcolor="#cc6600" cellpadding="0" cellspacing="0" border="0" align="left">
<tr>
<td>
<a href="#" target="_blank" title="#" style="text-decoration:none;color:#FFF;"><img src="http://www.example.com/image_01.png" alt="#" width="320" height="167" border="0" style="display:block;" /></a>
</td>
</tr>
</table>
<table width="320" bgcolor="#cc6600" cellpadding="0" cellspacing="0" border="0" align="right">
<tr>
<td>
<a href="#" target="_blank" title="#" style="text-decoration:none;color:#FFF;"><img src="http://www.example.com/image_02.png" alt="#" width="320" height="167" border="0" style="display:block;" /></a>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
</code></pre>
<p>If any one could help me find a way to still have my two side by side tables in Outlook, but still have them re-align to one under the other in mobile phones, I would be very appreciative.</p> | 0 | 2,299 |
if else statement in android | <p>I was new in Android and found some good tutorials on the internet, so I tried a simple activity with an <code>if-else</code> statement. I'm trying "correct and wrong" prompt/<code>Toast</code>:</p>
<pre><code>Button page1 = (Button) findViewById(R.id.button2);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
if (iv1.equals(R.drawable.airplane1)) {
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane2)) {
Toast.makeText(getApplicationContext(), "Please put an answer",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane3)){
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
</code></pre>
<p>I'm not sure what is wrong in my <code>if-else</code> statement but never prompts at all. I tried removing the <code>(iv1.equals(R.drawable.airplane3))</code> and <code>(iv1.equals(R.drawable.airplane2))</code> then it only shows the wrong Toast. I can't get seem to make the correct to prompt me.</p>
<p>Here is the full code of my class:</p>
<pre><code>public class MainActivity extends Activity {
private static final Random imagerandom = new Random();
private static final Integer[] Imagesnumber =
{ R.drawable.airplane1, R.drawable.airplane2, R.drawable.airplane3, };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Integer a = Imagesnumber[imagerandom.nextInt(Imagesnumber.length)];
final ImageView iv = (ImageView) findViewById(R.id.imageView1);
View nextButton = findViewById(R.id.button1);
nextButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View V) {
int resource = Imagesnumber[imagerandom.nextInt(Imagesnumber.length)];
iv.setImageResource(resource);
}
});
Button page1 = (Button) findViewById(R.id.button2);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
if (iv1.equals(R.drawable.airplane1)) {
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane2)) {
Toast.makeText(getApplicationContext(), "Please put an answer",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane3)){
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
</code></pre> | 0 | 1,416 |
Delete List Item on right swipe react-native | <p>// Here I am trying to delete List item from Flat List .
Data is populating from JSON on Flat List now I have to delete particular list item data form list , for that I am using "Swipeout" . but getting error "Type error: undefined is not an object(evaluting this.2.viewNote.bind")<br>
Please help . Where am going wrong and how can I do this </p>
<pre><code>import React, { Component } from 'react';
import { View, Text, TextInput,
FooterTab,Button,TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator ,Header,FlatList} from 'react-native';
import {Icon} from 'native-base';
import { Table, Row, Rows } from 'react-native-table-component';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
import Swipeout from 'react-native-swipeout';
let swipeBtns = [{
text: 'Delete',
backgroundColor: 'red',
underlayColor: 'rgba(0, 0, 0, 1, 0.6)',
onPress: () => { this.deleteNote(item) }
}];
export default class OpenApplianceIssue extends Component {
constructor() {
super();
this.state = {
AbcSdata: null,
loading: true,
search: '',
tableData: [], qrData: '', selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
};
this.setDate = this.setDate.bind(this);
}
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for(let i=0; i<len; i++)
{
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({tableData: tData } );
console.log(this.state.tableData);
this.setState({loading: true});
}
componentDidMount() {
this._loadInitialState().done();
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'http:/Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit":"0",
"valuelimit":"10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
renderItem = ({ item }) => (
<Swipeout right={swipeBtns}>
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={this.viewNote.bind(this, item)} >
<Text >Id : {item.id}</Text>
<Text>Inventory : {item.inventory}</Text>
<Text>SensorType : {item.sensorType}</Text>
<Text>TypeName : {item.typeName}</Text>
</TouchableOpacity>
</Swipeout>
);
viewNote(item) {
this.props.navigator.push({
title: 'The Note',
component: ViewNote,
passProps: {
noteText: item,
noteId: this.noteId(item),
}
});
}
onClickListener = (viewId) => {
if(viewId == 'tag')
{
this.props.navigation.navigate('AddSensors');
}}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
}}
/>
);
};
render() {
const { loading, AbcSdata } = this.state;
const state = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<Button full rounded
style={{fontSize: 20, color: 'green'}}
styleDisabled={{color: 'red'}}
onPress={() => this.onClickListener('tag')}
title="Add Sensors"
>
Add Sensors
</Button>
</View>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={this.renderSeparator}
/>
)}
</View>
<View>
<Text
style={{alignSelf: 'center', fontWeight: 'bold', color: 'black'}} >
Inventory Details
</Text>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff', padding:10,paddingBottom: 10}}>
<Rows data={state.tableData} textStyle={styles.text}/>
</Table>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create(
{
container1:
{
flex: 1,
alignItems: 'stretch',
fontFamily: "vincHand",
color: 'blue'
},
header_footer_style:{
width: '100%',
height: 44,
backgroundColor: '#4169E1',
alignItems: 'center',
justifyContent: 'center',
color:'#ffffff',
},
Progressbar:{
justifyContent: 'center',
alignItems: 'center',
color: 'blue',
},
ListContainer :{
borderColor: '#48BBEC',
backgroundColor: '#000000',
color:'red',
alignSelf: 'stretch' ,
},
container2:
{
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
paddingHorizontal: 15
},
inputBox:{
width:300,
borderColor: '#48BBEC',
backgroundColor: '#F8F8FF',
borderRadius:25,
paddingHorizontal:16,
fontSize:16,
color:'#000000',
marginVertical:10,
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
textStyle:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
item:
{
padding: 15
},
text:
{
fontSize: 18
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'red',
textAlign:'center'
},
separator:
{
height: 2,
backgroundColor: 'rgba(0,0,0,0.5)'
},
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
Thanks .
</code></pre> | 0 | 4,000 |
Hibernate cannot simultaneously fetch multiple bags two Lists | <p>I have very strange situation. Before when I tried to fetch multiple collections by one try of HQL query I have not had this error. The Internet says that the problem can occur because of FetchType.LAZY, but I removed it and nothing change.</p>
<p>My entity from where I'm trying to fetch some data: </p>
<pre><code>@Entity
@Table(name="INSTITUTION_IN_FORM")
public class InstitutionInForm implements Serializable {
private static final long serialVersionUID = -721358037476057890L;
private int institutionId;
@Id
@GeneratedValue(strategy= IDENTITY)
@Column(name="INSTITUTION_ID")
public int getInstitutionId() {
return institutionId;
}
public void setInstitutionId(int institutionId) {
this.institutionId = institutionId;
}
private int version;
@Version
@Column(name="VERSION")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
private String nameOfInstitution;
@Column(name="INSTITUTION_NAME")
public String getNameOfInstitution() {
return nameOfInstitution;
}
public void setNameOfInstitution(String nameOfInstitution) {
this.nameOfInstitution = nameOfInstitution;
}
private List<FormDate> formDateList = new ArrayList<FormDate>();
@ManyToMany(mappedBy="institutions")
@Cascade(CascadeType.ALL)
public List<FormDate> getFormDateList() {
return formDateList;
}
public void setFormDateList(List<FormDate> formDateList) {
this.formDateList = formDateList;
}
private List<FormDescription> formDescriptionList = new ArrayList<FormDescription>();
@OneToMany(mappedBy="institutions", orphanRemoval=true)
@Cascade(CascadeType.ALL)
public List<FormDescription> getFormDescriptionList() {
return formDescriptionList;
}
public void setFormDescriptionList(List<FormDescription> formDescriptionList) {
this.formDescriptionList = formDescriptionList;
}
}
</code></pre>
<p>My dao method I use to find data in DB:</p>
<pre><code>@SuppressWarnings("unchecked")
@Override
public List<InstitutionInForm> fetchByName(String institutionName) {
return sessionFactory.getCurrentSession().createQuery("select distinct institution from InstitutionInForm institution " +
"left join fetch institution.formDateList formDate left join fetch institution.formDescriptionList formDescription where institution.nameOfInstitution= :institutionName")
.setParameter("institutionName", institutionName).list();
}
</code></pre>
<p>My error stacktrace:</p>
<pre><code>Exception in thread "main" org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
at org.hibernate.loader.BasicLoader.postInstantiate(BasicLoader.java:93)
at org.hibernate.loader.hql.QueryLoader.<init>(QueryLoader.java:121)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:204)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
at edu.demidov.dao.EducationWebDaoImpl.fetchByName(EducationWebDaoImpl.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy24.fetchByName(Unknown Source)
at edu.demidov.dao.AppOut.main(AppOut.java:52)
</code></pre>
<p>What may be a problem with it. Any help will be well appreciated. Thank you guys.</p> | 0 | 2,106 |
How to force RecyclerView.Adapter to call the onBindViewHolder() on all elements | <p>I have a <code>VerticalGridView</code> that is using a <code>RecyclerView.Adapter</code> to populate the elements. I have discovered that the <code>onBindViewHolder()</code> method does not get called if the potential element is off of the viewport. Unfortunately, this is causing a <code>NullPointerException</code> from a different method because I am catching a <code>TextView</code> reference in the <code>onBindViewHolder()</code> method and passing it to an outside variable for later manipulation.</p>
<pre><code>@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.txtCategoryName.setText(categories.get(position).getStrCategory());
categories.get(position).setTxtViewReference(viewHolder.txtCategoryDefectTotal);
viewHolder.categoryBoxRoot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(CategoryListItem catItem : categories){
if(catItem.getStrCategory().equals(viewHolder.txtCategoryName.getText())){
int index = Defects.getInstance().getCategories().indexOf(catItem) + 1;
MainInterface.grids.get(index).bringToFront();
MainInterface.grids.get(index).setVisibility(View.VISIBLE);
for(VerticalGridView grid : MainInterface.grids){
int gridIndex = MainInterface.grids.indexOf(grid);
if(gridIndex != index){
grid.setVisibility(View.INVISIBLE);
}
}
break;
}
}
}
});
</code></pre>
<p>From what I understand, the reference to the <code>TextView</code> gets created when the <code>Viewholder</code> object is instantiated.</p>
<pre><code>public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtCategoryName;
public TextView txtCategoryDefectTotal;
public View categoryBoxRoot;
public ViewHolder(View itemView) {
super(itemView);
txtCategoryName = (TextView) itemView.findViewById(R.id.textViewCategoryName);
txtCategoryDefectTotal = (TextView) itemView.findViewById(R.id.textViewCategoryTotalDefects);
categoryBoxRoot = itemView.findViewById(R.id.root_category_box);
}
}
</code></pre>
<p>Is there a way to force <code>onBindViewHolder()</code> to be called on all elements at least one time when the <code>Adapter</code> is instantiated?</p>
<p>I attempted the suggestions <a href="https://stackoverflow.com/questions/32913578/recyclerview-does-not-call-the-onbindviewholder-when-scroll-in-the-view">here</a> without any success.</p>
<p>I understand that forcing <code>onBindViewHolder()</code> on all elements would work against the <a href="https://stackoverflow.com/a/37524217/1510725">whole purpose of the RecycleView.Adapter</a>. Thus, I am open to any other suggestions on how I can catch that <code>TextView</code> reference.</p>
<p>As a temporary fix to this problem, I am able to use a try catch block around the method that generates the <code>NullPointerException</code>. However, I am concerned that the lack of the reference means I could introduce errors in the future.</p> | 0 | 1,253 |
High CPU load running php processes | <p>I have dedicate server with 3.1GHz single quad core CPU with 32 GB RAM.
It works as a web server and configured to:
Apache 2.4 + MPM Worker + Mod_fcgid</p>
<p>When I run top command, I see high CPU usage by PHP processes of website. Below is a snapshot</p>
<pre><code>Tasks: 193 total, 1 running, 112 sleeping, 1 stopped, 79 zombie
Cpu(s): 84.0%us, 1.4%sy, 0.0%ni, 12.3%id, 2.3%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 33554432k total, 26637508k used, 6916924k free, 0k buffers
Swap: 0k total, 0k used, 0k free, 10471152k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8415 mysql 20 0 12.5g 4.1g 6348 S 115.1 12.8 5107:00 mysqld
18687 domainus 20 0 303m 110m 44m S 64.5 0.3 1:05.51 php
18728 domainus 20 0 311m 118m 46m S 42.7 0.4 1:00.57 php
18732 domainus 20 0 333m 140m 45m S 40.3 0.4 1:19.61 php
17371 domainus 20 0 306m 114m 46m S 32.5 0.3 0:57.16 php
18726 domainus 20 0 278m 87m 47m S 24.8 0.3 1:48.62 php
14765 domainus 20 0 324m 133m 47m S 17.7 0.4 4:00.94 php
</code></pre>
<p>I want to be sure that, my Apache configuration is right and the problem is with the PHP code, any suggestions on how to drill down the issue?</p> | 0 | 1,384 |
Can not squeeze dim[1], expected a dimension of 1, got 2 | <p>I have very simple input: Points, and I am trying to classify whether they are in some region or not. So my training data is of the shape <code>(1000000, 2)</code>, which is an array of the form:<br /><code>[ [x1,y1], [x2,y2],... ]</code><br />
My labels are of a similar form (Shaped <code>(10000, 2)</code>):<br />
<code>[ [1,0], [0,1], [0,1],... ]</code><br />
(<code>[0,1]</code>means the point is in the region, <code>[1,0]</code> means it isn't)</p>
<p>My model is set up this way:</p>
<pre><code>import tensorflow as tf
from tensorflow import keras
import numpy as np
# Reads the points and labels from .csv format files
train_data = np.genfromtxt('data/train_data.csv', delimiter=',')
train_labels = np.genfromtxt('data/train_labels.csv', delimiter=',')
model = keras.models.Sequential()
model.add(keras.layers.Dense(128, activation='relu', input_shape=(2,)))
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dense(2, activation='softmax'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(train_data, train_labels, epochs=1, batch_size=100, verbose=1) # ERROR
</code></pre>
<p>Notice that the input shape is <code>(2,)</code>, meaning (according to the <a href="https://keras.io/layers/core/" rel="nofollow noreferrer">reference</a>) that the model would expect arrays of the form <code>(*, 2)</code>.</p>
<p>I am getting the error:<br />
<code>tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 2</code></p>
<p>and I have no idea why. Any suggestions?</p>
<p><strong>Stacktrace:</strong></p>
<pre><code>Traceback (most recent call last):
File "C:/Users/omer/Desktop/Dots/train.py", line 25, in <module>
model.fit(train_data, train_labels, epochs=1, batch_size=100, verbose=1)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 880, in fit
validation_steps=validation_steps)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py", line 329, in model_iteration
batch_outs = f(ins_batch)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\backend.py", line 3076, in __call__
run_metadata=self.run_metadata)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 1439, in __call__
run_metadata_ptr)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 528, in __exit__
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 2
[[{{node metrics/acc/Squeeze}}]]
</code></pre> | 0 | 1,062 |
How to move an image around with arrow keys javascript | <p>I recently began developing a little javascript game, just for fun. The idea was that you controlled a little dot with the arrow keys (or awsd or i don't care what) within a box on the screen. Little rectangles would then randomly spawn on all edges of the box and progress across it. you have to avoid contact with them. The project turned out to be harder than I expected and I couldn't get the movement to work right. If you could help me with that that would be great. also, feel free to take the concept and what little I have done so far and do whatever you want with it. I would be interested to see your results. Below is the code I used for the spawns without any of the movement scripts. I was using the basic idea of this code to do the movement:</p>
<pre><code>var x = 5; //Starting Location - left
var y = 5; //Starting Location - top
var dest_x = 300; //Ending Location - left
var dest_y = 300; //Ending Location - top
var interval = 2; //Move 2px every initialization
function moveImage() {
//Keep on moving the image till the target is achieved
if(x<dest_x) x = x + interval;
if(y<dest_y) y = y + interval;
//Move the image to the new location
document.getElementById("ufo").style.top = y+'px';
document.getElementById("ufo").style.left = x+'px';
if ((x+interval < dest_x) && (y+interval < dest_y)) {
//Keep on calling this function every 100 microsecond
// till the target location is reached
window.setTimeout('moveImage()',100);
}
}
</code></pre>
<p>main body:</p>
<pre><code><html>
<head>
<style type="text/css">
html::-moz-selection{
background-color:Transparent;
}
html::selection {
background-color:Transparent;
}
img.n {position:absolute; top:0px; width:5px; height:10px;}
img.e {position:absolute; right:0px; width:10px; height:5px;}
img.s {position:absolute; bottom:0px; width:5px; height:10px;}
img.w {position:absolute; left:0px; width:10px; height:5px;}
#canvas {
width:300px;
height:300px;
background-color:black;
position:relative;
}
</style>
<script type="text/javascript">
nmecount=0
function play(){
spawn()
var t=setTimeout("play()",1000);
}
function spawn(){
var random=Math.floor(Math.random()*290)
var side=Math.floor(Math.random()*5)
var name=1
var z=10000
if (side=1)
{
var nme = document.createElement('img');
nme.setAttribute('src', '1.png');
nme.setAttribute('class', 'n');
nme.setAttribute('id', name);
nme.setAttribute('style', 'left:'+random+'px;');
nme.onload = moveS;
document.getElementById("canvas").appendChild(nme);
}
if (side=2)
{
var nme = document.createElement('img');
nme.setAttribute('src', '1.png');
nme.setAttribute('class', 'e');
nme.setAttribute('id', name);
nme.setAttribute('style', 'top:'+random+'px;');
nme.onload = moveW;
document.getElementById("canvas").appendChild(nme);
}
if (side=3)
{
var nme = document.createElement('img');
nme.setAttribute('src', '1.png');
nme.setAttribute('class', 's');
nme.setAttribute('id', name);
nme.setAttribute('style', 'left:'+random+'px;');
nme.onload = moveN;
document.getElementById("canvas").appendChild(nme);
}
if (side=4)
{
var nme = document.createElement('img');
nme.setAttribute('src', '1.png');
nme.setAttribute('class', 'w');
nme.setAttribute('id', name);
nme.setAttribute('style', 'top:'+random+'px;');
nme.onload = moveE;
document.getElementById("canvas").appendChild(nme);
}
name=name+1
}
</script>
</head>
<body onLoad="play()">
<div id="canvas">
<img id="a" src="1.png" style="position:absolute; z-index:5; left:150px; top:150px; height:10px; width=10px;" />
<button onclick="moveleft()"><</button>
</body>
</html>
</code></pre> | 0 | 2,052 |
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class com.sun.jersey.core.header.MediaTypes | <p>I'm trying to run a jersey client and facing this issue.</p>
<p>WS Class: </p>
<pre><code>import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/hello")
public class HelloWorldService {
@GET
@Path("/vip")
@Produces(MediaType.APPLICATION_JSON)
public Response getMsg(@QueryParam("msg") String msg) {
String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}
</code></pre>
<p>Client Class:</p>
<pre><code> import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientGet {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:8080/TestRest/rest/hello/vip?msg=ABCD");
ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>Issue is when I'm trying to execute the Client Class, following error message is coming</p>
<pre><code> Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class com.sun.jersey.core.header.MediaTypes
at com.sun.jersey.core.spi.factory.MessageBodyFactory.initReaders(MessageBodyFactory.java:182)
at com.sun.jersey.core.spi.factory.MessageBodyFactory.initReaders(MessageBodyFactory.java:176)
at com.sun.jersey.core.spi.factory.MessageBodyFactory.init(MessageBodyFactory.java:162)
at com.sun.jersey.api.client.Client.init(Client.java:342)
at com.sun.jersey.api.client.Client.access$000(Client.java:118)
at com.sun.jersey.api.client.Client$1.f(Client.java:191)
at com.sun.jersey.api.client.Client$1.f(Client.java:187)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
at com.sun.jersey.api.client.Client.<init>(Client.java:187)
at com.sun.jersey.api.client.Client.<init>(Client.java:159)
at com.sun.jersey.api.client.Client.create(Client.java:669)
at com.mkyong.client.JerseyClientGet.main(JerseyClientGet.java:12)
</code></pre>
<p>I'm using the following jars:</p>
<p><strong>asm-3.1.jar,
jackson-core-asl-1.9.2.jar,
jackson-jaxrs-1.9.2.jar,
jackson-mapper-asl-1.9.2.jar,
jackson-xc-1.9.2.jar,
jersey-bundle-1.8.jar,
jersey-client-1.18.jar,
jersey-core-1.18.jar,
jersey-json-1.18.jar,
jersey-server-1.18.jar,
jersey-servlet-1.18.jar,
jettison-1.1.jar,
jsr311-api-1.1.1.jar</strong></p> | 0 | 1,591 |
'Step Into' is suddenly not working in Visual Studio | <p>All of a sudden, I have run into an issue where I cannot step into any code through debugging in Visual Studio. The step over works fine, but it refuses to step into (<kbd>F11</kbd>) any of my code. This was working before, now all of a sudden it does not. </p>
<p>I've tried some things below, but I still had no success:</p>
<ul>
<li><p>Delete all bin files in every project in my solution, clean solution, re-build solution. </p></li>
<li><p>Build projects in solution indivdualy</p></li>
<li><p>Restart machine</p></li>
</ul>
<p>It an <a href="http://en.wikipedia.org/wiki/ASP.NET">ASP.NET</a> <a href="http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29">C#</a> application consuming a <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation">WCF</a> sevice locally. It is in debug mode. I have a breakpoint set on the page consuming the service. The breakpoint hits, but it will not step into the service code.</p>
<p>The ASP.NET site and the service code is all in the same solution. This all of a sudden does not work, it did work before.</p>
<p>How can I fix this problem?</p>
<p>Adding a breakpoint to the service project I get a warning:</p>
<blockquote>
<p>Breakpoint will not currently be hit. No symbols have been loaded for this document.</p>
</blockquote>
<p>I deleted all the bin folders for all the projects and re-built them one by one. They all succeeded, but still I am getting the <em>symbols won't load</em> on any breakpoint I put into any project in the solution other than the ASP.NET project where the breakpoint works. I was able to debug step into all the projects before, this is an all of a sudden thing. </p>
<p>Information from the output window..</p>
<pre><code>'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\SMDiagnostics\v4.0_4.0.0.0__b77a5c561934e089\SMDiagnostics.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.DurableInstancing\v4.0_4.0.0.0__31bf3856ad364e35\System.Runtime.DurableInstancing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Xaml.Hosting\v4.0_4.0.0.0__31bf3856ad364e35\System.Xaml.Hosting.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\2d49cf50\14eee2cf\App_Web_jmow15fw.dll', Symbols loaded.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Discovery\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Discovery.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Routing\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Routing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Channels\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Channels.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
</code></pre> | 0 | 1,746 |
How to make editable table using bootstrap and jQuery only? | <p>This is my bootstrap table.I want to insert data into table using jQuery only.On clicking a particular cell,a textbox should be open to enter data.I don't want to use any other plugin.</p>
<pre><code> <table class="table table-bordered">
<thead class="mbhead">
<tr class="mbrow">
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</code></pre>
<p>help me.thanx.</p> | 0 | 1,538 |
Get id of TextView in Fragment from FragmentActivity in ViewPager | <p>I'm working with <code>ViewPager</code> with 3 <code>Fragments</code> and I want to change text of <code>TextView</code> in third page.</p>
<p>In that page I have a <code>Button</code>that when its pressed, go to SD images to select one. When done, returns to page and want to update <code>TextView</code> with path of that image. The problem is that when I try to access that <code>TextView</code>from <code>FragmentActivity</code>it is null.</p>
<p><strong>Here is my code</strong></p>
<p><strong>SherlockFragmentActivity:</strong></p>
<pre><code>public class TabsFacturasActivity extends SherlockFragmentActivity {
protected MyApplication myApplication;
private static final int FILE_SELECT_CODE = 0;
private MyAdapter mAdapter;
private ViewPager mPager;
private PageIndicator mIndicator;
private TextView textViewImg;
private int lecturas = 0;
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
private boolean adjunto = false;
private String filePath;
private boolean esLecturaAT = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
// Get the application instance
myApplication = (MyApplication)getApplication();
//Need to get that view
textViewImg = (TextView) findViewById(R.id.textViewUrlImgLectura);
//Creamos la lista
LinkedList<String> direcciones = new LinkedList<String>();
ArrayList<TuplaCupsWS> dirs = myApplication.getUsuarioActual().getCups();
for(int dir = 0; dir < myApplication.getUsuarioActual().getCups().size(); dir++) {
direcciones.add(new String(dirs.get(dir).getDireccion()));
}
int tab = getIntent().getIntExtra("tab", 0);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(tab);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setIcon(R.drawable.logo_factorenergia_peque);
/** Create an array adapter to populate dropdownlist */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(), android.R.layout.simple_spinner_dropdown_item, direcciones);
/** Enabling dropdown list navigation for the action bar */
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
/** Defining Navigation listener */
OnNavigationListener navigationListener = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
return false;
}
};
/** Setting dropdown items and item navigation listener for the actionbar */
getSupportActionBar().setListNavigationCallbacks(adapter,
(com.actionbarsherlock.app.ActionBar.OnNavigationListener)
navigationListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
adjunto = true;
// Get the Uri of the selected file
Uri uri = data.getData();
// Get the path
String path = "";
try {
path = MyUtility.getPath(this, uri);
} catch (URISyntaxException e) {
myApplication.throwException(this);
e.printStackTrace();
}
String imgName = path.split("/")[path.split("/").length-1];
textViewImg.setText(imgName); //Here textViewImg is null
filePath = path;
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
//Method executed when Button is pressed
public void examinar(View view) {
mostrarFileChooser();
}
private void mostrarFileChooser() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
try {
startActivityForResult(intent, FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
}
}
private static class MyAdapter extends FragmentPagerAdapter {
private String[] titles = { "VER FACTURAS", "VER CONSUMO", "INTRODUCIR LECTURA" };
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0
return new FacturasActivity();
case 1: // Fragment # 1
return new ConsumoActivity();
case 2:// Fragment # 2
return new LecturaActivity();
}
//return new MyFragment();
return null;
}
@Override
public int getCount() {
return titles.length;
}
}
}
</code></pre>
<p><strong>fragment_pager.xml</strong></p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".TabsFacturasActivity" >
<com.viewpagerindicator.TitlePageIndicator
android:id="@+id/indicator"
android:padding="10dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#1184A4E8" />
</LinearLayout>
</code></pre> | 0 | 2,728 |
How to call a servlet from a jQuery's $.ajax() function | <p>I am trying to call a servlet from jQuery's .ajax() function.</p>
<p>At the moment I don't think I am even calling the servlet or passing paramaters to it, however lots of Googling doesn't seem to have helped. Any ideas?</p>
<p>This is my html:</p>
<pre><code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function login(){
$("#loading").hide();
var email = document.nameForm.email.value;
$.ajax({
type: "GET",
url: "ProcessForm",
data: "email="+email,
success: function(result){
alert(result);
}
});
}
</script>
<title>My AJAX</title>
</head>
<body>
<p>This time it's gonna work</p>
<form name="nameForm" id="nameForm" method="post" action="javascript:login()">
</code></pre>
<p>Email
loading</p>
<pre><code></body>
</html>
</code></pre>
<p>And my web.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ajaxtry</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ProcessForm</servlet-name>
<servlet-class>com.ajaxtry.web.ProcesFormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProcessForm</servlet-name>
<url-pattern>/ProcessForm</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>The servlet is just a template at the moment:</p>
<pre><code>package com.ajaxtry.web;
// imports here
public class ProcessFormServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println(request.getParameter("email"));
}
}
</code></pre> | 0 | 1,186 |
node app fails to run on mojave: ReferenceError: internalBinding is not defined | <p>I've tried to unsuccessfully run a node app, which runs fine on both High Sierra and Windows 10, but fails on Mojave 10.14.1.
This is the error shown when running the gulp build_dev task:</p>
<pre><code>[23:44:42] Requiring external module babel-register
fs.js:25
'use strict';
^
ReferenceError: internalBinding is not defined
at fs.js:25:1
at req_ (/Users/user1/Documents/NodeProjects/myapp/node_modules/natives/index.js:137:5)
at Object.req [as require] (/Users/user1/Documents/NodeProjects/myapp/node_modules/natives/index.js:54:10)
at Object.<anonymous> (/Users/user1/Documents/NodeProjects/myapp/node_modules/vinyl-fs/node_modules/graceful-fs/fs.js:1:37)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Object.require.extensions.(anonymous function) [as .js] (/Users/user1/Documents/NodeProjects/myapp/node_modules/babel-register/lib/node.js:152:7)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! myapp@1.0.0 dev: `node node_modules/gulp/bin/gulp.js build_dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myapp@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/user1/.npm/_logs/2018-11-04T22_44_42_709Z-debug.log
</code></pre>
<p>This is the content of the package.json file with all the dependencies used in the application:</p>
<pre><code>{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test-dev": "node node_modules/gulp/bin/gulp.js test_dev",
"test-prod": "node node_modules/gulp/bin/gulp.js test_prod",
"dev": "node node_modules/gulp/bin/gulp.js build_dev",
"prod": "node node_modules/gulp/bin/gulp.js build_prod"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-polyfill": "^6.26.0",
"body-parser": "^1.17.2",
"cookie-parser": "^1.4.3",
"envify": "^4.1.0",
"express": "^4.16.2",
"glob": "^7.1.2",
"http-status-codes": "^1.1.6",
"morgan": "^1.8.2",
"multi-glob": "^1.0.1",
"npm": "^6.4.1",
"path": "^0.12.7"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.26.0",
"babel-plugin-syntax-async-functions": "^6.13.0",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-preset-env": "^1.6.0",
"babel-register": "^6.24.1",
"babelify": "^7.3.0",
"browser-sync": "^2.26.3",
"browserify": "^16.1.0",
"gulp": "^3.9.1",
"gulp-concat": "^2.6.1",
"gulp-if": "^2.0.2",
"gulp-imagemin": "^3.3.0",
"gulp-minify-css": "^1.2.4",
"gulp-nodemon": "^2.2.1",
"gulp-notify": "^3.0.0",
"gulp-rename": "^1.2.2",
"gulp-sass": "^3.1.0",
"gulp-sass-glob": "^1.0.8",
"gulp-sourcemaps": "^2.6.0",
"gulp-uglify": "^3.0.0",
"gulp-util": "^3.0.8",
"imagemin-pngquant": "^5.0.1",
"run-sequence": "^2.2.0",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
}
}
</code></pre>
<p>Any hint on how to debug this problem? Could be related to gcc compiler version?</p>
<p>node version: 11.1.0
npm version: 6.4.1</p>
<p>At this link I've uploaded the log of the "npm install" command to install dependencies: <a href="https://drive.google.com/file/d/1hKiK2r0WvZEPuf5fWYgEMoJYwhANWRQ0/view?usp=sharing" rel="noreferrer">npm_install.log</a></p> | 0 | 1,696 |
Wordpress Custom Post Types doesn't show in admin left sidebar menu | <p>I have a weird problem with one of my custom post type that doesn't show in left sidebar admin menu.</p>
<p>I declared 5 custom post types but the fifth doesn't show in left menu. Here it's the Clients post type that doesn't show. I made a lot of search about this, without success.</p>
<p>Thanks a lot for your help !</p>
<pre><code> /**
* Custom Posts Types
*/
add_action('init', 'create_team_post_type');
function create_team_post_type() {
register_post_type( 'phil_team',
array(
'labels' => array(
'name' => __('Équipe'),
'singular_name' => __('Individu'),
'add_new' => __('Ajouter'),
'add_new_item' => __('Ajouter un individu'),
'view_item' => __('Voir individu'),
'edit_item' => __('Modifier individu'),
'search_items' => __('Rechercher un individu'),
'not_found' => __('Individu non trouvé'),
'not_found_in_trash' => __('Individu non trouvé dans la corbeille')
),
'public' => true,
'hierarchical' => false,
'menu_position' => 21,
'rewrite' => array('slug' => 'team'),
'supports' => array('title', 'editor', 'thumbnail'),
'show_ui' => true
)
);
}
add_action('init', 'create_projects_post_type');
function create_projects_post_type() {
register_post_type( 'phil_projects',
array(
'labels' => array(
'name' => __('Projets'),
'singular_name' => __('Projet'),
'add_new' => __('Ajouter'),
'add_new_item' => __('Ajouter un projet'),
'view_item' => __('Voir projet'),
'edit_item' => __('Modifier projet'),
'search_items' => __('Rechercher un projet'),
'not_found' => __('Projet non trouvé'),
'not_found_in_trash' => __('Projet non trouvé dans la corbeille')
),
'public' => true,
'menu_position' => 21,
'query_var' => 'project',
'rewrite' => array('slug' => 'who-we-help/our-work'),
'supports' => array('title', 'editor', 'thumbnail'),
'show_ui' => true
)
);
$set = get_option('post_type_rules_flased_POST-TYPE-NAME-HERE');
if ($set !== true){
flush_rewrite_rules(false);
update_option('post_type_rules_flased_POST-TYPE-NAME-HERE',true);
}
}
add_action('init', 'create_slideshow_post_type');
function create_slideshow_post_type() {
register_post_type( 'phil_home_slideshow',
array(
'labels' => array(
'name' => __('Slideshow'),
'singular_name' => __('Image'),
'add_new' => __('Ajouter'),
'add_new_item' => __('Ajouter une image'),
'view_item' => __('Voir image'),
'edit_item' => __('Modifier image'),
'search_items' => __('Rechercher une image'),
'not_found' => __('Image non trouvé'),
'not_found_in_trash' => __('Image non trouvé dans la corbeille')
),
'public' => true,
'hierarchical' => false,
'menu_position' => 21,
'rewrite' => array('slug' => 'slideshow'),
'supports' => array('title', 'editor', 'thumbnail'),
'show_ui' => true
)
);
}
add_action('init', 'create_home_boxes_post_type');
function create_home_boxes_post_type() {
register_post_type( 'phil_home_boxes',
array(
'labels' => array(
'name' => __('Boîtes page d\'accueil'),
'singular_name' => __('Boîte'),
'add_new' => __('Ajouter'),
'add_new_item' => __('Ajouter une boîte'),
'view_item' => __('Voir boîte'),
'edit_item' => __('Modifier boîte'),
'search_items' => __('Rechercher une boîte'),
'not_found' => __('Boîte non trouvé'),
'not_found_in_trash' => __('Boîte non trouvé dans la corbeille')
),
'public' => true,
'hierarchical' => false,
'menu_position' => 21,
'supports' => array('title', 'editor', 'thumbnail'),
'show_ui' => true
)
);
}
add_action('init', 'create_clients_post_type');
function create_clients_post_type() {
register_post_type( 'phil_clients',
array(
'labels' => array(
'name' => __('Clients'),
'singular_name' => __('Client'),
'add_new' => __('Ajouter'),
'add_new_item' => __('Ajouter un client'),
'view_item' => __('Voir client'),
'edit_item' => __('Modifier client'),
'search_items' => __('Rechercher une client'),
'not_found' => __('Client non trouvé'),
'not_found_in_trash' => __('Client non trouvé dans la corbeille')
),
'public' => true,
'show_ui' => true,
'hierarchical' => false,
'menu_position' => 21,
'supports' => array('title', 'editor', 'thumbnail')
)
);
}
</code></pre> | 0 | 2,985 |
VS2017 installer - the package manifest failed signature validation | <p>I have VS2015 installed, and previously had VS2017 installed on this machine. Adding an extension on VS2017 seemed to completely break my install, so I figured the next thing to do would be to reinstall VS2017.</p>
<p>Oh how I wish I didn't.</p>
<p>The installer has been failing with "The package manifest failed signature validation" I've tried following steps:</p>
<ul>
<li><p><a href="https://developercommunity.visualstudio.com/content/problem/19633/the-package-manifest-failed-signature-validation.html" rel="noreferrer">https://developercommunity.visualstudio.com/content/problem/19633/the-package-manifest-failed-signature-validation.html</a></p></li>
<li><p>Deleting VS15 registry keys</p></li>
<li><p>Installing VS certificates manually</p></li>
<li><p>Potentially more.</p></li>
</ul>
<p>When running the installer, I am presented with:</p>
<p><a href="https://i.stack.imgur.com/psha5.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/psha5.jpg" alt="enter image description here"></a></p>
<p>prior to even selecting a product to install.</p>
<p>When attempting to follow "offline installer" steps at <a href="https://www.hanselman.com/blog/HowToMakeAnOfflineInstallerForVS2017.aspx" rel="noreferrer">https://www.hanselman.com/blog/HowToMakeAnOfflineInstallerForVS2017.aspx</a></p>
<p>On the step where I run:</p>
<pre><code>vs_community.exe --layout e:\vs2017offline --lang en-US
</code></pre>
<p>I am presented with (eventually) a console window:</p>
<p><a href="https://i.stack.imgur.com/3PKjI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3PKjI.png" alt="enter image description here"></a></p>
<p>The log files for the installation.</p>
<p>dd_setup_*.log:</p>
<pre><code>[0df4:000c][2017-05-24T08:37:22] Setup Engine v1.10.101, Microsoft Windows NT 10.0.10586.0
[0df4:000c][2017-05-24T08:37:22] Command line: "C:\Program Files (x86)\Microsoft Visual Studio\Installer\resources\app\ServiceHub\Hosts\Microsoft.ServiceHub.Host.CLR\vs_installerservice.exe" desktopClr$C94B8CFE-E3FD-4BAF-A941-2866DBB566FE 18a10ed3a2b52a1e605bf4679dbe1364
[0df4:000c][2017-05-24T08:37:24] ManifestVerifier verification: Exception has been thrown by the target of an invocation. Stack: at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Security.Cryptography.CryptoConfig.CreateFromName(String name, Object[] args)
at Microsoft.VisualStudio.Setup.Security.ManifestMethods.CalculateHashValue(String dataBlob, String hashMethod)
at Microsoft.VisualStudio.Setup.Security.ManifestVerifier.CheckSign(ManifestDoc manifestDoc, Signature signature, String layoutCertPath)
at Microsoft.VisualStudio.Setup.Security.ManifestVerifier.Verify(FileStream fileStream, String path, String layoutCertPath)
[0df4:000c][2017-05-24T08:37:24] ManifestVerifier Result: Exception
</code></pre>
<p>dd_client_*.log</p>
<pre><code>2017-05-24T08:37:01 : Verbose : Visual Studio Installer (1.10.30637.0 : update2) ["C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vs_installershell.exe","/finalizeInstall","install","--in","C:\\ProgramData\\Microsoft\\VisualStudio\\Packages\\_bootstrapper\\vs_setup_bootstrapper.json","--locale","en-US","--activityId","78239d59-bc71-44e1-b8c6-e67d586fbba5","--campaign","1601306246.1493817089"]
2017-05-24T08:37:02 : Verbose : Creating VS Telemetry Survey
2017-05-24T08:37:03 : Verbose : Received the application ready notification
2017-05-24T08:37:03 : Verbose : Starting ServiceHub Experimentation client.
2017-05-24T08:37:09 : Verbose : Calling ExperimentationProviderService.Initialize()
2017-05-24T08:37:09 : Verbose : ServiceHub Experimentation client started.
2017-05-24T08:37:09 : Verbose : ExperimentsIpcRpcService listening to ipc channel: ExperimentsProxy
2017-05-24T08:37:09 : Verbose : Experiments Ipc Service started.
2017-05-24T08:37:09 : Verbose : Telemetry Session ID: 2b7ca8c1-aa76-4fe1-81eb-36936b1e32d7
2017-05-24T08:37:09 : Verbose : Connected to Hub Controller's client watch 'net.pipe://1140e3f8da9d1a14f42763f0648c14f4'
2017-05-24T08:37:09 : Verbose : ServiceHubExperimentationClient.setSharedProperty(name, value) called,
[name: VS.ABExp.Flights] [value: lazytoolboxinit;fwlargebuffer;refactoring;spmoretempsbtn1;c32bca7948ab42c;tn-none-15b;vswlaunchbcf]
2017-05-24T08:37:10 : Verbose : Calling ExperimentationProviderService.IsFlightEnabledAsync(flightId). [flightId: VSWLaunchBanner]
2017-05-24T08:37:10 : Verbose : ServiceHubExperimentationClient.postEvent(name, properties) called.
[name: VS/ABExp/FlightRequest] [properties: {"VS.ABExp.Flight":"vswlaunchbanner","VS.ABExp.Result":"False"}]
2017-05-24T08:37:10 : Verbose : Resolved ExperimentationProviderService.IsFlightEnabledAsync(flightId).
[flightId: VSWLaunchBanner] [result: false]
2017-05-24T08:37:11 : Verbose : Getting installed product summaries. [installerId: SetupEngine]
2017-05-24T08:37:11 : Verbose : Starting the installed products provider service.
2017-05-24T08:37:11 : Verbose : Starting the products provider service.
2017-05-24T08:37:11 : Verbose : Getting product summaries. [installerId: SetupEngine]
2017-05-24T08:37:11 : Verbose : Starting the installer service.
2017-05-24T08:37:11 : Verbose : Calling SetupEngine.Installer.Initialize. [locale: en-US]
2017-05-24T08:37:11 : Verbose : SetupEngine.Installer.Initialize succeeded. [locale: en-US]
2017-05-24T08:37:11 : Verbose : Started the installer service.
2017-05-24T08:37:11 : Verbose : Calling SetupEngine.Installer.IsElevated.
2017-05-24T08:37:11 : Verbose : SetupEngine.Installer.IsElevated succeeded.
2017-05-24T08:37:22 : Verbose : Started the products provider service.
2017-05-24T08:37:22 : Verbose : Started the installed products provider service.
2017-05-24T08:37:22 : Verbose : Getting product. [installerId: SetupEngine, productId: Microsoft.VisualStudio.Product.Professional].
2017-05-24T08:37:24 : Error : Failed to get product. [installerId: SetupEngine, productId: Microsoft.VisualStudio.Product.Professional, error: The installer manifest failed signature validation. at at Microsoft.VisualStudio.Setup.Engine.Load(String path, Boolean skipVerify)
at Microsoft.VisualStudio.Setup.Engine.Load(Uri manifestUri, Uri channelUri, Uri installChannelUri, CancellationToken token, Boolean skipVerify)
at Microsoft.VisualStudio.Setup.Engine.Load(ChannelNode`1 channelProduct, CancellationToken token, Boolean skipVerify)
at Microsoft.VisualStudio.Setup.ProductInstaller.CreateEngine(IEngineFactory engineFactory, IServiceProvider engineServiceProvider, IProgressReporter progressReporter, IMessageBus messageBus, IRestartManager restartManager, String instanceId, ChannelNode`1 channelProductSummary)
at Microsoft.VisualStudio.Setup.ProductInstaller.GetEngine()
at Microsoft.VisualStudio.Setup.ProductInstaller..ctor(ILogger logger, String language, LocalizedResourceFallback languageFallback, IEngineFactory engineFactory, IRestartManager restartManager, IInstance instance, ChannelNode`1 channelProductSummary, VersionBundle latestVersion, IServiceProvider setupServiceProvider)
at Microsoft.VisualStudio.Setup.ProductInstallerFactory.Create(ChannelNode`1 channelProductSummary, IInstance instance, VersionBundle latestVersion)
at Microsoft.VisualStudio.Setup.ProductInstallerCache.GetInstaller(String installerId, Func`2 func)
at Microsoft.VisualStudio.Setup.ProductsProviderService.GetProduct(String channelId, String productId)]
2017-05-24T08:38:09 : Verbose : Closing installer. Return code: 0.
2017-05-24T08:38:09 : Verbose : [ProductsProviderImpl]: Rpc connection was closed.
2017-05-24T08:38:09 : Verbose : [InstalledProductsProviderImpl]: Rpc connection was closed.
2017-05-24T08:38:09 : Verbose : [InstallerImpl]: Rpc connection was closed.
</code></pre>
<p>I'm not sure what else to try, Microsoft live support did not offer anything new that I hadn't already tried in the above links.</p>
<p>Has anyone else experienced this and know how to help?</p>
<p>Oh, and I forgot to mention, the installer seems to be in such an unusable state, that I cannot sign in to report an issue. Additionally, the developercommunity.visualstudio.com website seems to have problems logging me in with my microsoft account as well. </p>
<p>[<img src="https://i.stack.imgur.com/PYKdl.png" alt="click sign in">
<a href="https://i.stack.imgur.com/dGWZf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dGWZf.png" alt="immediately get presented with error (where is the credential window?"></a>
<a href="https://i.stack.imgur.com/GZISr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GZISr.png" alt="can't do anything on the screen without signing in"></a></p> | 0 | 2,857 |
CentOS 7 apachectl httpd.service fails to start | <p>I'm building <a href="https://github.com/devopsgroup-io/catapult-release-management" rel="nofollow">https://github.com/devopsgroup-io/catapult-release-management</a> and every once in a while trying to <code>apachectl start</code> an error of:</p>
<p>Job for httpd.service failed. See 'systemctl status httpd.service' and 'journalctl -xn' for details.</p>
<p><code>systemctl status httpd.service</code> outputs:</p>
<pre><code>httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)
Active: failed (Result: exit-code) since Wed 2015-07-15 19:25:23 EDT; 4s ago
Process: 3247 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
Process: 3246 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
Main PID: 3246 (code=exited, status=1/FAILURE)
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: Starting The Apache HTTP Server...
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Jul 15 19:25:23 devopsgroup.io-dev-redhat kill[3247]: kill: cannot find process ""
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: httpd.service: control process exited, code=exited status=1
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: Failed to start The Apache HTTP Server.
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: Unit httpd.service entered failed state.
</code></pre>
<p>and <code>journalctl -xn</code> outputs:</p>
<pre><code>-- Logs begin at Wed 2015-07-15 19:23:53 EDT, end at Wed 2015-07-15 19:25:23 EDT. --
Jul 15 19:25:11 devopsgroup.io-dev-redhat sshd[3196]: pam_unix(sshd:session): session opened for user vagrant by (uid=0)
Jul 15 19:25:17 devopsgroup.io-dev-redhat sudo[3221]: vagrant : TTY=pts/0 ; PWD=/home/vagrant ; USER=root ; COMMAND=/bin/su -l
Jul 15 19:25:17 devopsgroup.io-dev-redhat su[3222]: (to root) vagrant on pts/0
Jul 15 19:25:17 devopsgroup.io-dev-redhat su[3222]: pam_unix(su-l:session): session opened for user root by vagrant(uid=0)
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: Starting The Apache HTTP Server...
-- Subject: Unit httpd.service has begun with start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has begun starting up.
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Jul 15 19:25:23 devopsgroup.io-dev-redhat kill[3247]: kill: cannot find process ""
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: httpd.service: control process exited, code=exited status=1
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has failed.
--
-- The result is failed.
Jul 15 19:25:23 devopsgroup.io-dev-redhat systemd[1]: Unit httpd.service entered failed state.
</code></pre>
<p>Any ideas?</p> | 0 | 1,112 |
Angular 5 formGroup formControlName issue with select options | <p><strong>Update</strong></p>
<p>We are using Angular5 and we have a form that is constructed using FormGroup and then binded using formgroup and formControlName. </p>
<p>On initial load everything is populating correctly in all input fields. After closing the modal and then clicking on another record populates all fields with the correct userFrm value except the Salutation and AwardStatus Dropbox. If you click back on the first record then the values are correct. This has been causing issues for us. I'm pretty sure it is the [Selected[ property is not updating.</p>
<p><strong>user.component.ts snippet</strong> </p>
<pre><code>ngOnInit(): void {
this.indLoading = true;
this.loadSalutationField();
this.loadResearchField();
this.loadTrustField();
this.loadRegionField();
this.loadAwardStatusField();
this.loadRoleField();
this.loadUsers();
this.indLoading = false;
this.createForm();
}
createForm() {
this.userFrm = new FormGroup({
UserKey: new FormControl(''),
SiID: new FormControl('', Validators.required),
OrcidID: new FormControl(''),
Salutation: new FormControl({}),
FirstName: new FormControl('', Validators.required),
Surname: new FormControl('', Validators.required),
CurrentPost: new FormControl(''),
Department: new FormControl(''),
Institution: new FormControl(''),
Region: new FormControl({}),
PrimaryResearchField: new FormControl({}),
SecondaryResearchField: new FormControl({}),
NHSTrust: new FormControl({}),
Street: new FormControl(''),
City: new FormControl(''),
County: new FormControl(''),
Postcode: new FormControl(''),
Telephone: new FormControl(''),
Mobile: new FormControl(''),
Email: new FormControl('', Validators.required),
Fax: new FormControl(''),
SecondaryEmail: new FormControl(''),
ProfessionalBackground: new FormControl(''),
ApprovalStatus: new FormControl(''),
Biography: new FormControl(''),
NIHRAccount: new FormControl(''),
IsCurrent: new FormControl(''),
AwardStatusDate: new FormControl(''),
CreatedDate: new FormControl(''),
UpdatedDate: new FormControl(''),
IsActive: new FormControl(''),
Image: new FormControl({}),
AwardStatus: new FormControl({}),
Role: new FormControl({})
});
}
updateUserForm() {
this.userFrm.setValue({
UserKey: this.user.UserKey,
SiID: this.user.SiID,
OrcidID: this.user.OrcidID,
Salutation: this.user.Salutation,
FirstName: this.user.FirstName,
Surname: this.user.Surname,
CurrentPost: this.user.CurrentPost,
Department: this.user.Department,
Institution: this.user.Institution,
Region: this.user.Region,
PrimaryResearchField: this.user.PrimaryResearchField,
SecondaryResearchField: this.user.SecondaryResearchField,
NHSTrust: this.user.NHSTrust,
Street: this.user.Street,
City: this.user.City,
County: this.user.County,
Postcode: this.user.Postcode,
Telephone: this.user.Telephone,
Mobile: this.user.Mobile,
Email: this.user.Email,
Fax: this.user.Fax,
SecondaryEmail: this.user.SecondaryEmail,
ProfessionalBackground: this.user.ProfessionalBackground,
ApprovalStatus: this.user.ApprovalStatus,
Biography: this.user.Biography,
NIHRAccount: this.user.NIHRAccount,
IsCurrent: this.user.IsCurrent,
AwardStatusDate: this.user.AwardStatusDate,
CreatedDate: this.user.CreatedDate,
UpdatedDate: this.user.UpdatedDate,
IsActive: this.user.IsActive,
Image: this.user.Image,
AwardStatus: this.user.AwardStatus,
Role: this.user.Role
});
editUser(userKey: number) {
this.dbops = DBOperation.update;
this.setControlsState(true);
this.createForm();
this.modalTitle = "Edit User";
this.modalBtnTitle = "Update";
this.user = this.users.filter(x => x.UserKey === userKey)[0];
this.dangerousImage = "data:image/jpg;base64," + this.user.Image.ImageStream;
this.trustedImage = this._sanitizer.bypassSecurityTrustUrl(this.dangerousImage);
this.updateUserForm();
this.editModal.open();
}
</code></pre>
<p><strong>user.component.html</strong></p>
<pre><code><bs-modal #editModal [keyboard]="false" [backdrop]="'static'">
<form [formGroup]="userFrm" (ngSubmit)="onSubmit()" novalidate>
<!--<pre>{{userFrm.value | json}}</pre>-->
<bs-modal-header>
<h4 class="modal-title">{{modalTitle}}</h4>
</bs-modal-header>
<bs-modal-body>
<div class="square">
<img [src]="trustedImage" />
<button (click)="updateUserPhoto(user.UserKey)">Upload Image</button>
</div>
<br />
<div class="form-group" *ngIf="isAdmin">
<span>Role*</span>
<select class="form-group" formControlName="Role">
<option *ngFor="let role of roles"
[value]="role"
[selected]="role.Description === userFrm.value.Role.Description">
{{role.Description}}
</option>
</select>
</div>
<div class="form-group" *ngIf="isAdmin">
<span>
Award Status*
</span>
<select class="form-group" formControlName="AwardStatus">
<option *ngFor="let awardStatus of awardStatues"
[value]="awardStatus"
[selected]="awardStatus.Description == userFrm.value.AwardStatus.Description">
{{awardStatus.Description}}
</option>
</select>
</div>
<div class="form-group">
<span>SI Number*</span>
<input type="text" class="form-control" placeholder="Si Number" formControlName="SiID" />
</div>
<div class="form-group">
<span>Title*</span>
<select class="form-control" formControlName="Salutation">
<option *ngFor="let salutationfield of salutationfields"
[value]="salutationfield"
[selected]="salutationfield.Description === userFrm.value.Salutation.Description">
{{salutationfield.Description}}
</option>
</select>
</div>
<div class="form-group">
<span>First name*</span>
<input type="text" class="form-control" placeholder="First name" formControlName="FirstName" />
</div>
<div class="form-group">
<span>Surname*</span>
<input type="text" class="form-control" placeholder="Surname" formControlName="Surname" />
</div>
<div class="form-group">
<span>Orchid ID*</span>
<input type="text" class="form-control" placeholder="OrcidID" formControlName="OrcidID" />
</div>
<div class="form-group">
<span>Telephone*</span>
<input type="text" class="form-control" placeholder="Telephone" formControlName="Telephone" />
</div>
<div class="form-group">
<span>Email*</span>
<input type="text" class="form-control" placeholder="Email" formControlName="Email" />
</div>
<div class="form-group">
<span>Current Post*</span>
<input type="text" class="form-control" placeholder="Current Post" formControlName="CurrentPost" />
</div>
<div class="form-group">
<span>Institution*</span>
<input type="text" class="form-control" placeholder="Institution" formControlName="Institution" />
</div>
<div class="form-group">
<span>Department*</span>
<input type="text" class="form-control" placeholder="Department" formControlName="Department" />
</div>
<div class="form-group">
<span>NHS Trust*</span>
<select formControlName="NHSTrust">
<option *ngFor="let trustfield of trustfields"
[value]="trustfield"
[selected]="trustfield.Description === userFrm.value.NHSTrust.Description">
{{trustfield.Description}}
</option>
</select>
</div>
<div class="form-group">
<span>Region*</span><br />
<select formControlName="Region">
<option *ngFor="let regionfield of regionfields"
[value]="regionfield"
[selected]="regionfield.Description === userFrm.value.Region.Description">
{{regionfield.Description}}
</option>
</select>
</div>
<div class="form-group">
<span>Primary Research Field*</span><br />
<select formControlName="PrimaryResearchField">
<option *ngFor="let priResearchField of researchfields"
[value]="priResearchField"
[selected]="priResearchField.Description === userFrm.value.PrimaryResearchField.Description">
{{priResearchField.Description}}
</option>
</select>
</div>
<div class="form-group">
<span>Secondary Research Field*</span><br />
<select formControlName="SecondaryResearchField">
<option *ngFor="let secResearchField of researchfields"
[value]="secResearchField"
[selected]="secResearchField.Description === userFrm.value.SecondaryResearchField.Description">
{{secResearchField.Description}}
</option>
</select>
</div>
<br />
<div class="form-group">
<accordion>
<accordion-group heading="Biography">
<input type="text" class="form-control" placeholder="Biography" formControlName="Biography" />
</accordion-group>
</accordion>
</div>
</bs-modal-body>
<bs-modal-footer>
<div>
<a class="btn btn-default" (click)="editModal.close()">Cancel</a>
<button type="submit" [disabled]="userFrm.invalid" class="btn btn-primary">{{modalBtnTitle}}</button>
</div>
</bs-modal-footer>
</form>
</bs-modal>
</code></pre>
<p>Any ideas on this would be greatly appreciated.</p>
<p>Many thanks in advance</p>
<p>Lewis</p> | 0 | 6,429 |
Javascript slide in slide out div | <p>I'm trying to create a replica of this site:</p>
<p><a href="http://liko0312.wix.com/wildfireimages" rel="nofollow">http://liko0312.wix.com/wildfireimages</a></p>
<p>I've made it to slide in and out from the same direction using CSS and placing the div outside with 100% and then bringing it in with 0, very much a toggle effect.</p>
<p>However, I'm trying to make the pages slide in and out just like in the model site but CSS does not allow me to. I have good skills with HTML/CSS but am low on Javascript. So far I found <a href="http://jsfiddle.net/jPneT/208/" rel="nofollow">this fiddle</a>, but it's a toggle animation while I need it to slide in from the right and slide out to the left and after it has to reset. Also, the animation of the current div sliding out and the next div sliding in have to be in the same time.</p>
<p>Here is <a href="http://jsfiddle.net/5EaP8/" rel="nofollow">Fiddle with code</a> as requested</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>.panel{
width:0px;
height:0px;
overflow: hidden;
position:relative;
left:100%;
background: none;
z-index: 2;
-moz-transition: all .8s ease-in-out, width 0s ease 1s, border-width 0s ease 1s;
-webkit-transition: all .8s ease-in-out, width 0s ease 1s, border-width 0s ease 1s;
-o-transition: all .8s ease-in-out, width 0s ease 1s, border-width 0s ease 1s;
transition: all .8s ease;
transition-delay:0s;
margin:0px;
}
.panel:target{
width:100%;
height:auto;
margin:0px 0 0;
padding:0;
background-color: transparent;
position:relative;
left:0;
z-index:3;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="overall-wrap">
<!-- Header with Navigation -->
<div id="header">
<a href="#home"><img class="header" src="images/logo.png" width="133" height="86" alt="Wildfire Images"></a>
<nav>
<ul id="navigation">
<li><a class="scroll" href="#home">Home</a></li>
<li><a class="scroll" href="#about">About Us</a>
<ul>
<li><a class="scroll" href="#contact">Contact Us</a></li>
</ul>
</li>
</ul>
</nav>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
<div id="home" class="panel"></div>
<!-- About Us -->
<div id="about" class="panel">
<div class="content">
<div class="bg-about effect2">
<div class="about-wrapper">
<div class="about-text">
<h2> About Us</h2>
<p>Wildfire Images is a Sydney based boutique Portrait Photography Studio dedicated to candidly capturing all that is beautiful, fun and elegant about you and your loved ones.</p>
<p>At Wildfire Images, we tailor every shoot to you, your trade mark smile, your rapturous laugh, your devotion to those you love, the cheeky, the serious and all those gorgeous things in between that will always be unmistakably you.</p>
<p>Call us to start the story. You bring the characters and the stories and we'll take the photos that tell them.</p>
<p class="strong">Contact us today on 9150 6275.</p>
</div>
<div class="about-image"><img src="images/aboutme.jpg" width="200" height="300" alt="WildFire Studios"></div>
</div>
</div>
<!-- ... -->
</div>
<div class="clearfix"></div>
</div>
<!-- /About Us -->
<!-- Contact -->
<div id="contact" class="panel">
<div class="content">
<div class="bg-contact effect2">
<img src="images/contact-image.jpg" width="900" height="419" alt="Contact Wildfire"/>
<div id="form-wrapper">
<div id="form-outer">
<div id="text-wrap">
<div id="contact-left">
<h2>Contact</h2>
<div id="phone">
<h3>Phone</h3><p>9150 6275</p></div>
<div id="email">
<h3>Email</h3><p>info@wildfireimages.com.au<p></div>
</div>
<div id="contact-right"><h3>Address</h3><p>Studio 18,</p><p>442-444 King Georges Rd</p><p>BEVERLY HILLS NSW 2209</p></div>
</div>
<div class="clear"></div>
<div id="form-inner">
<form name="contact" action="contact.php" method="post" onBlur="MM_validateForm('name','','R','email','','RisEmail','subject','','R','message','','R');return document.MM_returnValue">
<input name="name" type="text" class="field" id="name" placeholder="Name"/>
<input name="email" type="email" class="field" id="email" placeholder="Email"/>
<input name="subject" type="text" class="field" id="subject" placeholder="Subject" />
<textarea name="message" class="field_textarea" id="message" placeholder="Message"></textarea>
<input type="submit" value="Send" name="submit" class="submit"/>
</form>
</div>
</div>
</div>
</div>
<!-- ... -->
</div>
</div>
<!-- /Contact -->
<!-- Portraits -->
<div id="portraits" class="panel">
<div class="content">
<div class="gallery-big effect2">
<div id="gallery-big-text-wrap">
<h2>Portraits</h2>
<p>Call us to start the story. You bring the characters and the stories and we'll take the photos that tell them.</p>
<p>Contact us today on 9150 6275.</p>
</div>
<!--k gallery start-->
<img src="images/baby-06-portrait-gallery.jpg" width="798" height="531">
<img src="k/ki_galleries/all-about-me/AEP_0486.jpg" width="798" height="1200">
<img src="k/ki_galleries/all-about-me/AEP_0653.jpg" width="798" height="1200">
<img src="k/ki_galleries/all-about-me/DSC_0548.jpg" width="799" height="1200">
<img src="k/ki_galleries/all-about-me/DSC_2652-edit.jpg" width="799" height="1200">
<img src="images/family.jpg" width="798" height="532">
<img src="k/ki_galleries/all-about-me/DSC_4052.jpg" width="799" height="1200">
</div>
</div>
</div>
<!-- /Portraits -->
</div></code></pre>
</div>
</div>
</p>
<p>Also, the new site can be seen at wixwebsite.seobrasov.com</p>
<p>Please note that the slide in and out should work for more than two divs and be able to jump from tiv 1 to div 3 without showing div 2.</p> | 0 | 3,450 |
How do you apply a style to only one div in the HTML? | <p>I had working code until I tried to make the style.css page apply only to a certain div on the index.html file. This is the current code I have: <a href="http://codepen.io/anon/pen/LEXxeM" rel="nofollow">http://codepen.io/anon/pen/LEXxeM</a></p>
<p>All that I did (which made it stop working) was completely wrap the style.css page in "adder { }", and put all the code in the body in a div tag.</p>
<p>Any ideas as to why this was an incorrect step?</p>
<p>In case codepen can't be accessed, below is the code.</p>
<p>HTML:</p>
<pre><code><!DOCTYPE html>
<!--
-->
<html lang="en">
<head>
<link type="text/css" rel="stylesheet" href="css/styleok.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/init.js"></script>
</head>
<body>
<div class="adder">
<div id="container">
<header>
<h1>Task ListO</h1>
<a href="#" id="clear">Clear all</a>
</header>
<section id="taskIOSection">
<div id="formContainer">
<form id="taskEntryForm">
<input id="taskInput" placeholder="Add your interests here..." />
</form>
</div>
<ul id="taskList"></ul>
</section>
</div>
</div>
</body>
</html>
</code></pre>
<p>CSS</p>
<pre><code> @import url(http://fonts.googleapis.com/css?family=Open+Sans:400, 300, 600);
adder {
* {
padding:0;
margin:0;
}
body {
background:url('');
background-color:#2a2a2a;
font-family:'Open Sans', sans-serif;
}
#container {
background-color: #111216;
color:#999999;
width:350px;
margin: 50px auto auto auto;
padding-bottom:12px;
}
#formContainer {
padding-top:12px
}
#taskIOSection {
}
#taskInput {
font-size:14px;
font-family:'Open Sans', sans-serif;
height:36px;
width:311px;
border-radius:100px;
background-color:#202023;
border:0;
color:#fff;
display:block;
padding-left:15px;
-webkit-transition: all 0.30s ease-in-out;
-moz-transition: all 0.30s ease-in-out;
-ms-transition: all 0.30s ease-in-out;
-o-transition: all 0.30s ease-in-out;
}
#taskInput:focus{
box-shadow: 0px 0px 1pt 1pt #999999;
background-color:#111216;
outline:none;
}
::-webkit-input-placeholder {
color: #333333;
font-style:italic;
/* padding-left:10px; */
}
:-moz-placeholder {
/* Firefox 18- */
color: #333333;
font-style:italic;
}
::-moz-placeholder {
/* Firefox 19+ */
color: #333333;
font-style:italic;
}
:-ms-input-placeholder {
color: #333333;
font-style:italic;
}
header {
margin-top:0;
background-color:#F94D50;
width:338px;
height:48px;
padding-left:12px;
}
header h1 {
font-size:25px;
font-weight:300;
color:#fff;
line-height:48px;
width:50%;
display:inline;
}
header a{
width:40%;
display:inline;
line-height:48px;
}
#taskEntryForm {
background-color:#111216;
width:326px;
height: 48px;
border-width:0px;
padding: 0px 12px 0px 12px;
font-size:0px;
}
#taskList {
width: 350px;
margin:auto;
font-size:16px;
font-weight:600;
}
ul li {
background-color:#17181D;
height:48px;
width:314px;
padding-left:12px;
margin:0 auto 10px auto;
line-height:48px;
list-style:none;
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
}
}
</code></pre>
<p>JS:</p>
<pre><code> $(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var taskID = "task-" + i;
$('#taskList').append("<li id='" + taskID + "'>" + localStorage.getItem(taskID) + "</li>");
}
$('#clear').click(function () {
localStorage.clear();
});
$('#taskEntryForm').submit(function () {
if ($('#taskInput').val() !== "") {
var taskID = "task-" + i;
var taskMessage = $('#taskInput').val();
localStorage.setItem(taskID, taskMessage);
$('#taskList').append("<li class='task' id='" + taskID + "'>" + taskMessage + "</li>");
var task = $('#' + taskID);
task.css('display', 'none');
task.slideDown();
$('#taskInput').val("");
i++;
}
return false;
});
$('#taskList').on("click", "li", function (event) {
self = $(this);
taskID = self.attr('id');
localStorage.removeItem(taskID);
self.slideUp('slow', function () {
self.remove();
});
});
});
</code></pre>
<p>Thank you.</p> | 0 | 3,224 |
Nullable object must have a value. VB.NET | <p>I need help. I'm having problem in my program. This is my code on my Business logic layer.</p>
<pre><code>Function Load_ItemDetails(ByVal ItemID As String) As Items
Dim objItemEnt As New tblitem
Dim objitem As New Items
Try
Using da = New DataAccess
objItemEnt = da.Load_ItemDetails(ItemID)
With objitem
.ItemCode = objItemEnt.ItemCode
.ItemName = objItemEnt.ItemName
.Description = objItemEnt.Description
.NameofType = objItemEnt.NameofType
.TypeofPricing = objItemEnt.TypeofPricing
.OnStock = objItemEnt.OnStock
.ItemPrice = objItemEnt.ItemPrice
.DateModified = objItemEnt.DateModified
End With
Return objitem
End Using
Catch ex As Exception
Throw
End Try
End Function
</code></pre>
<p>This code is for my data access layer.</p>
<pre><code>Public Function Load_ItemDetails(ByVal ItemCode As String)
Dim objitem As New tblitem
Try
Using entItem = New DAL.systemdbEntities1
Dim qryUsers = From p In entItem.tblitems
Where p.ItemCode = ItemCode
Select p
Dim luser As List(Of tblitem) = qryUsers.ToList
If luser.Count > 0 Then
Return luser.First
Else
Return objitem
End If
End Using
Catch ex As Exception
Throw
End Try
End Function`
</code></pre>
<p>For my Presentation layer:</p>
<pre><code>Private Sub Load_Item_Detail(ByVal ItemCode As String)
objItem = New Items
Using objLogic = New LogicalLayer
objItem = objLogic.Load_ItemDetails(ItemCode)
With objItem
Me.ItemCodetxt.Text = .ItemCode
Me.ItemNametxt.Text = .ItemName
Me.ItemDesctxt.Text = .Description
Me.ItemTypetxt.Text = .NameofType
Me.ItemPricetxt.Text = .TypeofPricing
Me.ItemOnstocktxt.Text = CStr(.OnStock)
Me.ItemPricetxt.Text = CStr(.ItemPrice)
Me.TextBox1.Text = CStr(.DateModified)
Me.ItemCodetxt.Tag = .ItemCode
End With
End Using
End Sub`
</code></pre>
<p>and after I run, I get this error <code>Nullable object must have a value</code> help me. I'm stuck. I don't know what to do guys. I new in n tier architecture.</p> | 0 | 1,131 |
How to correctly bind checkbox to the object list in thymeleaf? | <p>My domain model consist of an <code>Employee</code> and <code>Certificate</code>. One Employee can reference/have many certificates (one-to-many relationship). The full list of certificates could be get from the <code>certificateService</code>. </p>
<p>To assign some special certificate to the employee I used <code>th:checkbox</code> element from thymeleaf as follow: </p>
<pre><code><form action="#" th:action="@{/employee/add}" th:object="${employee}" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" th:field="*{name}"></td>
</tr>
<tr>
<td>Certificate</td>
<td>
<th:block th:each="certificate , stat : ${certificates}">
<input type="checkbox" th:field="*{certificates}" name="certificates" th:value="${certificate.id]}"/>
<label th:text="${certificate.name}" ></label>
</th:block>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add"/></td>
</tr>
</table>
</form>
</code></pre>
<p>Now when I'm trying to submit the HTML form I always get following error:</p>
<blockquote>
<p>400 - The request sent by the client was syntactically incorrect.</p>
</blockquote>
<p>My question is: How to correctly bind checkbox elements to the object list with thymeleaf?</p>
<p><strong>Controller</strong></p>
<pre><code>@RequestMapping(value = "/add" , method = RequestMethod.GET)
public String add(Model model) {
model.addAttribute("employee",new Employee());
model.addAttribute("certificates",certificateService.getList());
return "add";
}
@RequestMapping(value = "/add" , method = RequestMethod.POST)
public String addSave(@ModelAttribute("employee")Employee employee) {
System.out.println(employee);
return "list";
}
</code></pre>
<p><strong>Employee Entity</strong></p>
<pre><code>@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private int id;
@Column(name = "Name")
private String name;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "emp_cert",
joinColumns = {@JoinColumn(name = "employee_id")},
inverseJoinColumns = {@JoinColumn(name = "certificate_id")})
private List<Certificate> certificates;
public Employee() {
if (certificates == null)
certificates = new ArrayList<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Certificate> getCertificates() {
return certificates;
}
public void setCertificates(List<Certificate> certificates) {
this.certificates = certificates;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "certificates size = " + certificates.size() + " ]";
}
}
</code></pre>
<p><strong>Certificate Entity</strong></p>
<pre><code>@Entity
@Table(name = "certificate")
public class Certificate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id")
private int id;
@Column(name = "name")
private String name;
@ManyToMany(mappedBy = "certificates")
private List<Employee> employees;
public Certificate() {
if (employees == null)
employees = new ArrayList<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Certificate other = (Certificate) obj;
if (id != other.id)
return false;
return true;
}
}
</code></pre> | 0 | 2,062 |
Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name defined in class path resource | <p>There was a mySql DB connection in my application, i need to crate another connection for different mySql DB for that i replicate the already created connection's steps with some different name in order to create the new mySQL DB connection but im facing the following exception, can any one help me by giving some hint where did i make the mistake. </p>
<pre><code>01 Sep 2014 01:34:41,931 ERROR [localhost-startStop-1] context.ContextLoader:227 - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcTemplatePivotDB' defined in class path resource [application-context-dao.xml]: Cannot resolve reference to bean 'dataSourcePivotDBJNDI' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourcePivotDBJNDI' defined in class path resource [application-context-dao.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: Name [${jdbc.pivotDB.jndi.name}] is not bound in this Context. Unable to find [${jdbc.pivotDB.jndi.name}].
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:616)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:618)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:650)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1582)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourcePivotDBJNDI' defined in class path resource [application-context-dao.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: Name [${jdbc.pivotDB.jndi.name}] is not bound in this Context. Unable to find [${jdbc.pivotDB.jndi.name}].
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
... 31 more
Caused by: javax.naming.NameNotFoundException: Name [${jdbc.pivotDB.jndi.name}] is not bound in this Context. Unable to find [${jdbc.pivotDB.jndi.name}].
at org.apache.naming.NamingContext.lookup(NamingContext.java:820)
at org.apache.naming.NamingContext.lookup(NamingContext.java:168)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:158)
at javax.naming.InitialContext.lookup(Unknown Source)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 38 more
</code></pre>
<p>Here are code chunks.</p>
<p>in java file where i need to use the DB Object:</p>
<pre><code>@Resource(name = "jdbcTemplatePivotDB")
private JdbcTemplate jdbcTemplatePivotDB;
</code></pre>
<p>Application-context.xml</p>
<pre><code> <bean id="jdbcTemplatePivotDB" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg index="0">
<ref bean="dataSourcePivotDB${jdbc.ds.type}" />
</constructor-arg>
</bean>
<bean id="txManagerPivotDB"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourcePivotDB${jdbc.ds.type}" />
</bean>
<bean id="dataSourcePivotDBCustom" class="org.apache.commons.dbcp.BasicDataSource"
lazy-init="true">
<property name="driverClassName" value="${jdbc.pivotDB.driverClassName}" />
<property name="url" value="${jdbc.pivotDB.url}" />
<property name="username" value="${jdbc.pivotDB.username}" />
<property name="password" value="${jdbc.pivotDB.password}" />
<property name="maxActive" value="${jdbc.pool.maxActive}" />
<property name="maxIdle" value="${jdbc.pool.maxIdle}" />
<property name="validationQuery" value="${jdbc.pool.validate}" />
</bean>
</code></pre>
<p>Here is .properties file details having DB details:</p>
<pre><code>jdbc.pivotDB.driverClassName=com.mysql.jdbc.Driver
jdbc.pivotDB.username=pivotuser
jdbc.pivotDB.password=pivotPass
jdbc.pivotDB.url=jdbc:mysql://ServerIP:3306/DBName
jdbc.pool.maxActive=10
jdbc.pool.maxIdle=10
jdbc.pool.validate=SELECT 1
</code></pre>
<p><strong>EDIT dataSourcePivotDBJNDI</strong></p>
<pre><code><bean id="dataSourcePivotDBJNDI" class="org.springframework.jndi.JndiObjectFactoryBean"
lazy-init="true">
<property name="jndiName" value="${jdbc.pivotDB.jndi.name}" />
</bean>
</code></pre> | 0 | 3,297 |
java.lang.ClassNotFoundException: org.hibernate.engine.transaction.spi.TransactionContext | <p>I am developing <code>Spring MVC Hibernate</code> Integration example. In this example I'm using <code>Spring 4.1.9.RELEASE</code> and <code>Hibernate 5.1.0.Final</code>. If I downgrade Hibernate version to <code>4.3.5.Final</code> then it works. Now inorder to use hibernate 5 what else configuration do I need to change. Please refer more details below.</p>
<p>Please find below the exception I see</p>
<pre><code>java.lang.ClassNotFoundException: org.hibernate.engine.transaction.spi.TransactionContext
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
at org.springframework.orm.hibernate4.HibernateTransactionManager.isSameConnectionForEntireSession(HibernateTransactionManager.java:711)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:445)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy26.listPersons(Unknown Source)
at com.journaldev.spring.PersonController.listPersons(PersonController.java:29)
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:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>The configuration which I used are:</p>
<pre><code><!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- DataSource -->
<beans:property name="dataSource" ref="dataSource" />
<!-- Annotated Class -->
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.journaldev.spring.model.Person</beans:value>
</beans:list>
</beans:property>
<!-- Hibernate Properties -->
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</beans:prop>
<beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
<beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
</code></pre>
<p>And other configurations are:</p>
<pre><code><beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</code></pre>
<p>It looks to me that this package <code>org.springframework.orm.</code> don't have configurations for the <code>hibernate 5</code> yet, please guide what configurations I need to change in order to use <code>hibernate 5</code>?</p>
<p>pom.xml</p>
<pre><code><properties>
<java.version>1.7</java.version>
<org.springframework-version>4.1.9.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
<hibernate.version>5.1.0.Final</hibernate.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Hibernate Entity Manager-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<!-- LOG4J -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- JSP API -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Junit Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
</dependencies>
</code></pre> | 0 | 6,360 |
jQuery.Deferred exception: Cannot read property 'on' of undefined TypeError: Cannot read property 'on' of undefined | <p>I know there are many questions related to this problem. I have read them all but I am not still able to fix my problem. I am getting this error:</p>
<blockquote>
<p>jQuery.Deferred exception: Cannot read property 'on' of undefined TypeError: Cannot read property 'on' of undefined<br>
at initCustomDropdown (<a href="http://localhost/wordpress/wp-content/themes/" rel="nofollow noreferrer">http://localhost/wordpress/wp-content/themes/</a>****/lib/js/custom.js:116:15)<br>
at HTMLDocument. (<a href="http://localhost/wordpress/wp-content/themes/" rel="nofollow noreferrer">http://localhost/wordpress/wp-content/themes/</a>****/lib/js/custom.js:45:2)<br>
at l (<a href="http://localhost/wordpress/wp-content/themes/jessica/lib/js/jquery-3.3.1.min.js:2:29375" rel="nofollow noreferrer">http://localhost/wordpress/wp-content/themes/jessica/lib/js/jquery-3.3.1.min.js:2:29375</a>)<br>
at c (<a href="http://localhost/wordpress/wp-content/themes/" rel="nofollow noreferrer">http://localhost/wordpress/wp-content/themes/</a>****/lib/js/jquery-3.3.1.min.js:2:29677) undefined </p>
</blockquote>
<p>However I am not able to get the point. My <code>custom.js</code> line number 116 is like this:</p>
<pre><code>$(document).ready(function() {
"use strict";
/*
1. Vars and Inits
*/
var menuActive = false;
var header = $('.header');
setHeader();
initCustomDropdown();
initPageMenu();
initDealsSlider();
initTabLines();
initFeaturedSlider();
featuredSliderZIndex();
initPopularSlider();
initBanner2Slider();
initFavs();
initArrivalsSlider();
arrivalsSliderZIndex();
bestsellersSlider();
initTabs();
initTrendsSlider();
initReviewsSlider();
initViewedSlider();
initBrandsSlider();
initTimer();
$(window).on('resize', function() {
setHeader();
featuredSliderZIndex();
initTabLines();
});
/*
2. Set Header
*/
function setHeader() {
//To pin main nav to the top of the page when it's reached
//uncomment the following
// var controller = new ScrollMagic.Controller(
// {
// globalSceneOptions:
// {
// triggerHook: 'onLeave'
// }
// });
// var pin = new ScrollMagic.Scene(
// {
// triggerElement: '.main_nav'
// })
// .setPin('.main_nav').addTo(controller);
if (window.innerWidth > 991 && menuActive) {
closeMenu();
}
}
/*
3. Init Custom Dropdown
*/
function initCustomDropdown() {
var placeholder;
if ($('.custom_dropdown_placeholder').length && $('.custom_list').length) {
placeholder = $('.custom_dropdown_placeholder');
var list = $('.custom_list');
}
if (placeholder) {
placeholder.on('click', function(ev) {
if (list.hasClass('active')) {
list.removeClass('active');
} else {
list.addClass('active');
}
$(document).one('click', function closeForm(e) {
if ($(e.target).hasClass('clc')) {
$(document).one('click', closeForm);
} else {
list.removeClass('active');
}
});
});
}
$('.custom_list a').on('click', function(ev) {
ev.preventDefault();
var index = $(this).parent().index();
placeholder.text($(this).text()).css('opacity', '1');
if (list.hasClass('active')) {
list.removeClass('active');
} else {
list.addClass('active');
}
});
$('select').on('change', function(e) {
placeholder.text(this.value);
$(this).animate({
width: placeholder.width() + 'px'
});
});
}
/*
4. Init Page Menu
*/
function initPageMenu() {
if ($('.page_menu').length && $('.page_menu_content').length) {
var menu = $('.page_menu');
var menuContent = $('.page_menu_content');
var menuTrigger = $('.menu_trigger');
//Open / close page menu
menuTrigger.on('click', function() {
if (!menuActive) {
openMenu();
} else {
closeMenu();
}
});
//Handle page menu
if ($('.page_menu_item').length) {
var items = $('.page_menu_item');
items.each(function() {
var item = $(this);
if (item.hasClass("has-children")) {
item.on('click', function(evt) {
evt.preventDefault();
evt.stopPropagation();
var subItem = item.find('> ul');
if (subItem.hasClass('active')) {
subItem.toggleClass('active');
TweenMax.to(subItem, 0.3, {
height: 0
});
} else {
subItem.toggleClass('active');
TweenMax.set(subItem, {
height: "auto"
});
TweenMax.from(subItem, 0.3, {
height: 0
});
}
});
}
});
}
}
}
function openMenu() {
var menu = $('.page_menu');
var menuContent = $('.page_menu_content');
TweenMax.set(menuContent, {
height: "auto"
});
TweenMax.from(menuContent, 0.3, {
height: 0
});
menuActive = true;
}
function closeMenu() {
var menu = $('.page_menu');
var menuContent = $('.page_menu_content');
TweenMax.to(menuContent, 0.3, {
height: 0
});
menuActive = false;
}
/*
5. Init Deals Slider
*/
function initDealsSlider() {
if ($('.deals_slider').length) {
var dealsSlider = $('.deals_slider');
dealsSlider.owlCarousel({
items: 1,
loop: false,
navClass: ['deals_slider_prev', 'deals_slider_next'],
nav: false,
dots: false,
smartSpeed: 1200,
margin: 30,
autoplay: false,
autoplayTimeout: 5000
});
if ($('.deals_slider_prev').length) {
var prev = $('.deals_slider_prev');
prev.on('click', function() {
dealsSlider.trigger('prev.owl.carousel');
});
}
if ($('.deals_slider_next').length) {
var next = $('.deals_slider_next');
next.on('click', function() {
dealsSlider.trigger('next.owl.carousel');
});
}
}
}
/*
6. Init Tab Lines
*/
function initTabLines() {
if ($('.tabs').length) {
var tabs = $('.tabs');
tabs.each(function() {
var tabsItem = $(this);
var tabsLine = tabsItem.find('.tabs_line span');
var tabGroup = tabsItem.find('ul li');
var posX = $(tabGroup[0]).position().left;
tabsLine.css({
'left': posX,
'width': $(tabGroup[0]).width()
});
tabGroup.each(function() {
var tab = $(this);
tab.on('click', function() {
if (!tab.hasClass('active')) {
tabGroup.removeClass('active');
tab.toggleClass('active');
var tabXPos = tab.position().left;
var tabWidth = tab.width();
tabsLine.css({
'left': tabXPos,
'width': tabWidth
});
}
});
});
});
}
}
/*
7. Init Tabs
*/
function initTabs() {
if ($('.tabbed_container').length) {
//Handle tabs switching
var tabsContainers = $('.tabbed_container');
tabsContainers.each(function() {
var tabContainer = $(this);
var tabs = tabContainer.find('.tabs ul li');
var panels = tabContainer.find('.panel');
var sliders = panels.find('.slider');
tabs.each(function() {
var tab = $(this);
tab.on('click', function() {
panels.removeClass('active');
var tabIndex = tabs.index(this);
$($(panels[tabIndex]).addClass('active'));
sliders.slick("unslick");
sliders.each(function() {
var slider = $(this);
// slider.slick("unslick");
if (slider.hasClass('bestsellers_slider')) {
initBSSlider(slider);
}
if (slider.hasClass('featured_slider')) {
initFSlider(slider);
}
if (slider.hasClass('arrivals_slider')) {
initASlider(slider);
}
});
});
});
});
}
}
/*
8. Init Featured Slider
*/
function initFeaturedSlider() {
if ($('.featured_slider').length) {
var featuredSliders = $('.featured_slider');
featuredSliders.each(function() {
var featuredSlider = $(this);
initFSlider(featuredSlider);
});
}
}
function initFSlider(fs) {
var featuredSlider = fs;
featuredSlider.on('init', function() {
var activeItems = featuredSlider.find('.slick-slide.slick-active');
for (var x = 0; x < activeItems.length - 1; x++) {
var item = $(activeItems[x]);
item.find('.border_active').removeClass('active');
if (item.hasClass('slick-active')) {
item.find('.border_active').addClass('active');
}
}
}).on({
afterChange: function(event, slick, current_slide_index, next_slide_index) {
var activeItems = featuredSlider.find('.slick-slide.slick-active');
activeItems.find('.border_active').removeClass('active');
for (var x = 0; x < activeItems.length - 1; x++) {
var item = $(activeItems[x]);
item.find('.border_active').removeClass('active');
if (item.hasClass('slick-active')) {
item.find('.border_active').addClass('active');
}
}
}
})
.slick({
rows: 2,
slidesToShow: 4,
slidesToScroll: 4,
infinite: false,
arrows: false,
dots: true,
responsive: [{
breakpoint: 768,
settings: {
rows: 2,
slidesToShow: 3,
slidesToScroll: 3,
dots: true
}
},
{
breakpoint: 575,
settings: {
rows: 2,
slidesToShow: 2,
slidesToScroll: 2,
dots: false
}
},
{
breakpoint: 480,
settings: {
rows: 1,
slidesToShow: 1,
slidesToScroll: 1,
dots: false
}
}
]
});
}
/*
9. Init Favorites
*/
function initFavs() {
// Handle Favorites
var items = document.getElementsByClassName('product_fav');
for (var x = 0; x < items.length; x++) {
var item = items[x];
item.addEventListener('click', function(fn) {
fn.target.classList.toggle('active');
});
}
}
/*
10. Init ZIndex
*/
function featuredSliderZIndex() {
// Hide slider dots on item hover
var items = document.getElementsByClassName('featured_slider_item');
for (var x = 0; x < items.length; x++) {
var item = items[x];
item.addEventListener('mouseenter', function() {
$('.featured_slider .slick-dots').css('display', "none");
});
item.addEventListener('mouseleave', function() {
$('.featured_slider .slick-dots').css('display', "block");
});
}
}
/*
11. Init Popular Categories Slider
*/
function initPopularSlider() {
if ($('.popular_categories_slider').length) {
var popularSlider = $('.popular_categories_slider');
popularSlider.owlCarousel({
loop: true,
autoplay: false,
nav: false,
dots: false,
responsive: {
0: {
items: 1
},
575: {
items: 2
},
640: {
items: 3
},
768: {
items: 4
},
991: {
items: 5
}
}
});
if ($('.popular_categories_prev').length) {
var prev = $('.popular_categories_prev');
prev.on('click', function() {
popularSlider.trigger('prev.owl.carousel');
});
}
if ($('.popular_categories_next').length) {
var next = $('.popular_categories_next');
next.on('click', function() {
popularSlider.trigger('next.owl.carousel');
});
}
}
}
/*
12. Init Banner 2 Slider
*/
function initBanner2Slider() {
if ($('.banner_2_slider').length) {
var banner2Slider = $('.banner_2_slider');
banner2Slider.owlCarousel({
items: 1,
loop: true,
nav: false,
dots: true,
dotsContainer: '.banner_2_dots',
smartSpeed: 1200
});
}
}
/*
13. Init Arrivals Slider
*/
function initArrivalsSlider() {
if ($('.arrivals_slider').length) {
var arrivalsSliders = $('.arrivals_slider');
arrivalsSliders.each(function() {
var arrivalsSlider = $(this);
initASlider(arrivalsSlider);
});
}
}
function initASlider(as) {
var arrivalsSlider = as;
arrivalsSlider.on('init', function() {
var activeItems = arrivalsSlider.find('.slick-slide.slick-active');
for (var x = 0; x < activeItems.length - 1; x++) {
var item = $(activeItems[x]);
item.find('.border_active').removeClass('active');
if (item.hasClass('slick-active')) {
item.find('.border_active').addClass('active');
}
}
}).on({
afterChange: function(event, slick, current_slide_index, next_slide_index) {
var activeItems = arrivalsSlider.find('.slick-slide.slick-active');
activeItems.find('.border_active').removeClass('active');
for (var x = 0; x < activeItems.length - 1; x++) {
var item = $(activeItems[x]);
item.find('.border_active').removeClass('active');
if (item.hasClass('slick-active')) {
item.find('.border_active').addClass('active');
}
}
}
})
.slick({
rows: 2,
slidesToShow: 5,
slidesToScroll: 5,
infinite: false,
arrows: false,
dots: true,
responsive: [{
breakpoint: 768,
settings: {
rows: 2,
slidesToShow: 3,
slidesToScroll: 3,
dots: true
}
},
{
breakpoint: 575,
settings: {
rows: 2,
slidesToShow: 2,
slidesToScroll: 2,
dots: false
}
},
{
breakpoint: 480,
settings: {
rows: 1,
slidesToShow: 1,
slidesToScroll: 1,
dots: false
}
}
]
});
}
/*
14. Init Arrivals Slider ZIndex
*/
function arrivalsSliderZIndex() {
// Hide slider dots on item hover
var items = document.getElementsByClassName('arrivals_slider_item');
for (var x = 0; x < items.length; x++) {
var item = items[x];
item.addEventListener('mouseenter', function() {
$('.arrivals_slider .slick-dots').css('display', "none");
});
item.addEventListener('mouseleave', function() {
$('.arrivals_slider .slick-dots').css('display', "block");
});
}
}
/*
15. Init Best Sellers Slider
*/
function bestsellersSlider() {
if ($('.bestsellers_slider').length) {
var bestsellersSliders = $('.bestsellers_slider');
bestsellersSliders.each(function() {
var bestsellersSlider = $(this);
initBSSlider(bestsellersSlider);
})
}
}
function initBSSlider(bss) {
var bestsellersSlider = bss;
bestsellersSlider.slick({
rows: 2,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
arrows: false,
dots: true,
autoplay: true,
autoplaySpeed: 6000,
responsive: [{
breakpoint: 1199,
settings: {
rows: 2,
slidesToShow: 2,
slidesToScroll: 2,
dots: true
}
},
{
breakpoint: 991,
settings: {
rows: 2,
slidesToShow: 1,
slidesToScroll: 1,
dots: true
}
},
{
breakpoint: 575,
settings: {
rows: 1,
slidesToShow: 1,
slidesToScroll: 1,
dots: false
}
}
]
});
}
/*
16. Init Trends Slider
*/
function initTrendsSlider() {
if ($('.trends_slider').length) {
var trendsSlider = $('.trends_slider');
trendsSlider.owlCarousel({
loop: false,
margin: 30,
nav: false,
dots: false,
autoplayHoverPause: true,
autoplay: false,
responsive: {
0: {
items: 1
},
575: {
items: 2
},
991: {
items: 3
}
}
});
trendsSlider.on('click', '.trends_fav', function(ev) {
$(ev.target).toggleClass('active');
});
if ($('.trends_prev').length) {
var prev = $('.trends_prev');
prev.on('click', function() {
trendsSlider.trigger('prev.owl.carousel');
});
}
if ($('.trends_next').length) {
var next = $('.trends_next');
next.on('click', function() {
trendsSlider.trigger('next.owl.carousel');
});
}
}
}
/*
17. Init Reviews Slider
*/
function initReviewsSlider() {
if ($('.reviews_slider').length) {
var reviewsSlider = $('.reviews_slider');
reviewsSlider.owlCarousel({
items: 3,
loop: true,
margin: 30,
autoplay: false,
nav: false,
dots: true,
dotsContainer: '.reviews_dots',
responsive: {
0: {
items: 1
},
768: {
items: 2
},
991: {
items: 3
}
}
});
}
}
/*
18. Init Recently Viewed Slider
*/
function initViewedSlider() {
if ($('.viewed_slider').length) {
var viewedSlider = $('.viewed_slider');
viewedSlider.owlCarousel({
loop: true,
margin: 30,
autoplay: true,
autoplayTimeout: 6000,
nav: false,
dots: false,
responsive: {
0: {
items: 1
},
575: {
items: 2
},
768: {
items: 3
},
991: {
items: 4
},
1199: {
items: 6
}
}
});
if ($('.viewed_prev').length) {
var prev = $('.viewed_prev');
prev.on('click', function() {
viewedSlider.trigger('prev.owl.carousel');
});
}
if ($('.viewed_next').length) {
var next = $('.viewed_next');
next.on('click', function() {
viewedSlider.trigger('next.owl.carousel');
});
}
}
}
/*
19. Init Brands Slider
*/
function initBrandsSlider() {
if ($('.brands_slider').length) {
var brandsSlider = $('.brands_slider');
brandsSlider.owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 5000,
nav: false,
dots: false,
autoWidth: true,
items: 8,
margin: 42
});
if ($('.brands_prev').length) {
var prev = $('.brands_prev');
prev.on('click', function() {
brandsSlider.trigger('prev.owl.carousel');
});
}
if ($('.brands_next').length) {
var next = $('.brands_next');
next.on('click', function() {
brandsSlider.trigger('next.owl.carousel');
});
}
}
}
/*
20. Init Timer
*/
function initTimer() {
if ($('.deals_timer_box').length) {
var timers = $('.deals_timer_box');
timers.each(function() {
var timer = $(this);
var targetTime;
var target_date;
// Add a date to data-target-time of the .deals_timer_box
// Format: "Feb 17, 2018"
if (timer.data('target-time') !== "") {
targetTime = timer.data('target-time');
target_date = new Date(targetTime).getTime();
} else {
var date = new Date();
date.setDate(date.getDate() + 2);
target_date = date.getTime();
}
// variables for time units
var days, hours, minutes, seconds;
var h = timer.find('.deals_timer_hr');
var m = timer.find('.deals_timer_min');
var s = timer.find('.deals_timer_sec');
setInterval(function() {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
console.log(seconds_left);
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
hours = hours + days * 24;
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
if (hours.toString().length < 2) {
hours = "0" + hours;
}
if (minutes.toString().length < 2) {
minutes = "0" + minutes;
}
if (seconds.toString().length < 2) {
seconds = "0" + seconds;
}
// display results
h.text(hours);
m.text(minutes);
s.text(seconds);
}, 1000);
});
}
}
});
</code></pre>
<p>My <code>custom.js</code> line number 45 is and all the functions have been defined with these names. </p>
<pre><code>initCustomDropdown();
initPageMenu();
initDealsSlider();
initTabLines();
initFeaturedSlider();
featuredSliderZIndex();
initPopularSlider();
initBanner2Slider();
initFavs();
initArrivalsSlider();
arrivalsSliderZIndex();
bestsellersSlider();
initTabs();
initTrendsSlider();
initReviewsSlider();
initViewedSlider();
initBrandsSlider();
initTimer();
</code></pre>
<p>Any recommendations? Thanks in advance</p> | 0 | 11,070 |
Xcode 5 and phonegap: linker errors on building for device but not for simulator | <p>Our phonegap app builds fine for the iphone simulator but generates linker errors when building the app on an iphone. the only thing that changed was installing testflight and a test app.</p>
<p>We already removed testflight and the test app, but the linker errors remain.</p>
<p>Any ideas on how to fix this?</p>
<p>We're on xcode 5 and phonegap 3.4.</p>
<p>Errors:</p>
<pre><code>ld: warning: ignoring file /Users/c/Library/Developer/Xcode/DerivedData/s-fhgxmhdprdjvwahdbgwuagoragit/Build/Products/Debug-iphoneos/libCordova.a, file was built for archive which is not the architecture being linked (arm64): /Users/c/Library/Developer/Xcode/DerivedData/s-fhgxmhdprdjvwahdbgwuagoragit/Build/Products/Debug-iphoneos/libCordova.a
Undefined symbols for architecture arm64:
"_OBJC_CLASS_$_CDVWebViewDelegate", referenced from:
objc-class-ref in CDVInAppBrowser.o
"_OBJC_METACLASS_$_CDVViewController", referenced from:
_OBJC_METACLASS_$_MainViewController in MainViewController.o
"_OBJC_CLASS_$_CDVPlugin", referenced from:
_OBJC_CLASS_$_CDVDevice in CDVDevice.o
_OBJC_CLASS_$_CDVConnection in CDVConnection.o
_OBJC_CLASS_$_LowLatencyAudio in LowLatencyAudio.o
_OBJC_CLASS_$_CDVLogger in CDVLogger.o
_OBJC_CLASS_$_CDVInAppBrowser in CDVInAppBrowser.o
_OBJC_CLASS_$_InAppPurchase in InAppPurchase.o
"_OBJC_METACLASS_$_CDVPlugin", referenced from:
_OBJC_METACLASS_$_CDVDevice in CDVDevice.o
_OBJC_METACLASS_$_CDVConnection in CDVConnection.o
_OBJC_METACLASS_$_LowLatencyAudio in LowLatencyAudio.o
_OBJC_METACLASS_$_CDVLogger in CDVLogger.o
_OBJC_METACLASS_$_CDVInAppBrowser in CDVInAppBrowser.o
_OBJC_METACLASS_$_InAppPurchase in InAppPurchase.o
"_OBJC_CLASS_$_CDVViewController", referenced from:
_OBJC_CLASS_$_MainViewController in MainViewController.o
objc-class-ref in CDVDevice.o
"_CDVLocalNotification", referenced from:
-[AppDelegate application:didReceiveLocalNotification:] in AppDelegate.o
"_OBJC_METACLASS_$_CDVCommandDelegateImpl", referenced from:
_OBJC_METACLASS_$_MainCommandDelegate in MainViewController.o
"_OBJC_CLASS_$_CDVPluginResult", referenced from:
objc-class-ref in CDVDevice.o
objc-class-ref in CDVConnection.o
objc-class-ref in LowLatencyAudio.o
objc-class-ref in CDVInAppBrowser.o
objc-class-ref in InAppPurchase.o
"_OBJC_CLASS_$_CDVCommandDelegateImpl", referenced from:
_OBJC_CLASS_$_MainCommandDelegate in MainViewController.o
"_OBJC_CLASS_$_CDVUserAgentUtil", referenced from:
objc-class-ref in CDVInAppBrowser.o
"_OBJC_CLASS_$_CDVCommandQueue", referenced from:
_OBJC_CLASS_$_MainCommandQueue in MainViewController.o
"_OBJC_METACLASS_$_CDVCommandQueue", referenced from:
_OBJC_METACLASS_$_MainCommandQueue in MainViewController.o
"_CDVPluginHandleOpenURLNotification", referenced from:
-[AppDelegate application:handleOpenURL:] in AppDelegate.o
-[CDVInAppBrowser openInSystem:] in CDVInAppBrowser.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre> | 0 | 1,254 |
ASP.NET MVC - Displaying a list of items which each have a list of items | <p>I hope this is the best way of explaining this...</p>
<p>I have 3 view objects: School, Courses, and Classes. Each school has multiple courses, and each course can have multiple classes (think of a course as a program of study, with classes being the actual classes). In my main View, I display all schools, and click one to go to it. On that "CourseView" page, it displays the name of the school as well as all courses associated with that school. What I'm trying to do, is also have all classes associated with each course listed also. Is this possible (without a ton of jQuery/JSON wizardry, which I am still learning)?</p>
<pre><code>public class School
{
public int Id { get; set; }
public string SchoolName { get; set; }
public string WelcomeMsg { get; set; }
public string SchoolLogo { get; set; }
public List<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string CourseCode { get; set; }
public string CourseName { get; set; }
public int SchoolId { get; set; }
public List<Class> Classes { get; set; }
}
public class Class
{
public int Id { get; set; }
public string ClassNumer { get; set; }
public int CourseId { get; set; }
public int InstructorId { get; set; }
}
</code></pre>
<p>In my SchoolDAO.cs, I have the following:</p>
<pre><code> {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SchoolId", SchoolId);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
// fill school object in another method.
school = readRecord(dr);
}
}
// Get all courses available for this school.
school.Courses = CoursesDAO.GetCourses(SchoolId);
return school;
}
</code></pre>
<p>Which also calls a method in the CourseDAO.cs to get the courses available at that school:</p>
<pre><code> {
SqlCommand cmd = new SqlCommand("Courses.GetCourses", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SchoolId", SchoolId);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
courses.Add(readRecord(dr));
}
}
// Get all classes available for each course.
foreach (var course in courses)
{
course.Classes = ClassDAO.GetClasses(course.Id);
}
return courses;
}
</code></pre>
<p>Which then calls the ClassDAO method to get all classes for each course:</p>
<pre><code> {
SqlCommand cmd = new SqlCommand("Courses.GetCourses", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SchoolId", courseId);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
classes.Add(readRecord(dr));
}
}
return classes;
}
</code></pre>
<p>So finally, my question is this: How do I display the list of schools, courses, and classes in a View, from the Model?</p>
<p>My View has the following, which displays which school I'm looking at, and the list of courses for that school:</p>
<pre><code><div class="display-field">
<h1><%: Model.SchoolName %></h1>
<h3><%: Model.WelcomeTitle %></h3>
<blockquote> <i><%: Model.WelcomeText %></i></blockquote>
</div>
<!-- Courses -->
<div class="display-field">
<table id="courses">
<thead>
<th>Course Code</th>
<th>Course Name</th>
</thead>
<tbody>
<%
foreach (var item in Model.Courses) {
%>
<tr>
<td><%: Html.DisplayFor(model => item.CourseCode) %></td>
<td><%: Html.DisplayFor(model => item.CourseName) %></td>
</tr>
<% } %></tbody>
</table>
</div>
</code></pre>
<p>After that table, I wanted to put another table with id="classes", but sadly when I try to do:</p>
<pre><code> <%
foreach (var class in Model.Courses) {
%>
<tr>
<td><%: Html.DisplayFor(model => item.ClassNumber) %></td>
</tr>
<% } %>
</code></pre>
<p>It won't work - I'm assuming because I either don't know how to access a list belonging to a list, or because that's not the way the Model works.</p>
<p>Any insight into this would be appreciated greatly. Thanks!</p>
<p>PS - The information is passed from the DAO -> Business -> Controller by simple methods such as:</p>
<p>SchoolController:</p>
<pre><code> public ActionResult ViewSchool(int Id)
{
School school = SchoolBusiness.GetSchool(Id);
return View(school);
}
</code></pre>
<p>SchoolBusiness.GetSchool:</p>
<pre><code> public static School GetSchool(int Id)
{
School school = SchoolDAO.GetSchool(Id);
return school;
}
</code></pre> | 0 | 2,776 |
AddressSanitizer:DEADLYSIGNAL when trying to use a user input | <p>here is the code that i have:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <assert.h>
#include <time.h>
const int Win = 0, Lose = 1, Draw = 2;
const int Rock = 0, Paper = 1, Scissors = 2;
int input(int n, char i[n]){
if (i[0] == 'R' || i[0] == 'r') return Rock;
else if (i[0] == 'P' || i[0] == 'p') return Paper;
else if (i[0] == 'S' || i[0] == 's') return Scissors;
else return -1;
}
int game(int n){
srand(time(NULL));
int r = rand() % 2;
if (r == n) return Draw;
else if (r == 0 && n == 1) return Win;
else if (r == 0 && n == 2) return Lose;
else if (r == 1 && n == 0) return Lose;
else if (r == 1 && n == 2) return Win;
else if (r == 2 && n == 0) return Win;
else if (r == 2 && n == 1) return Lose;
else return 0;
}
void print(int game){
if (game == Draw && input == Rock) printf ("i chose rock, its a draw\n");
else if (game == Draw && input == Paper) printf ("i chose paper, its a draw\n");
else if (game == Draw && input == Scissors) printf ("i chose scissors, its a draw\n");
else if (game == Win && input == Rock) printf ("i chose scissors, you win\n");
else if (game == Win && input == Paper) printf ("i chose rock, you win\n");
else if (game == Win && input == Scissors) printf ("i chose paper, you win\n");
else if (game == Lose && input == Rock) printf ("i chose paper, you lose\n");
else if (game == Lose && input == Paper) printf ("i chose scissors, you lose\n");
else printf ("i chose rock, you lose\n");
}
// void checkInput(){
// assert(input(1, 'R') == 1);
// assert(input(1, 'r') == 1);
// assert(input(1, 'P') == 2);
// assert(input(1, 'p') == 2);
// assert(input(1, 'S') == 3);
// assert(input(1, 's') == 3);
// printf("all tests pass\n");
// }
int main(){
setbuf(stdout, NULL);
char *j[1];
for(int a = 0; a >= 0; a++){
printf("pick rock, paper, scissors (R/P/S) 'e' to exit\n");
scanf("%s", &*j[0]);
if (j[0] == 'e') break;
print(game(input(strlen(j[0]), j[0])));
}
return 0;
}
</code></pre>
<p>when i run it prints out the line and lets me input something after which it gives me this error</p>
<pre><code>pick rock, paper, scissors (R/P/S) 'e' to exit
R
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4029==ERROR: AddressSanitizer: SEGV on unknown address 0x7f5ca33d6787 (pc 0x7f5ca328ffdd bp 0x7ffca0431550 sp 0x7ffca0430e70 T0)
==4029==The signal is caused by a WRITE memory access.
#0 0x7f5ca328ffdc (/lib/x86_64-linux-gnu/libc.so.6+0x6cfdc)
#1 0x7f5ca329f12b (/lib/x86_64-linux-gnu/libc.so.6+0x7c12b)
#2 0x4a724c (/home/student/Documents/extra+0x4a724c)
#3 0x4a734e (/home/student/Documents/extra+0x4a734e)
#4 0x512a5e (/home/student/Documents/extra+0x512a5e)
#5 0x7f5ca3244b96 (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
#6 0x419e19 (/home/student/Documents/extra+0x419e19)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/lib/x86_64-linux-gnu/libc.so.6+0x6cfdc)
==4029==ABORTING
</code></pre>
<p>how can i stop this from happening as this error means nothing to me, and cant see anything that could be wrong with it. I know i have pasted a lot of code but i figure you need to see all of it to have an idea where it is crashing from.</p> | 0 | 1,481 |
How to reset Password Using PHP Codeigniter | <p>Am working on a Password reset system whereby the user who forgot his password can request for password reset link by submitting his email used in registration. I successfully create the email, it sent the link and I test the link by clicking on it. The link went through and load the reset page but my problem is how to make the system recognise the user who click through and get all the details including Name, Token, email with which the system will confirm that the user is the user who requested the link.</p>
<p>The following is what I have done so far:</p>
<p>Controller</p>
<pre><code> public function preset(){
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_error_delimiters("<div class='alert alert-warning'><span type='button' class='close' data-dismiss='alert'>&times</span>","</div>");
if($this->form_validation->run() == false){
$this->load->view('passwordrecovery.php', $data);
}
else{
$eMail = $this->input->post('email');
$this->db->where("email = '$eMail'");
$this->db->from("useraccount");
$countResult = $this->db->count_all_results();
if($countResult >=1){
// $data['firstName'] = '';
// $data['lastName'] = '';
$this->db->where("email = '$eMail'");
$getUserData =$this->db->get("useraccount")->result();
foreach($getUserData as $userD){
$data['firstName'] = $userD->firstname;
$data['lastName'] = $userD->lastname;
}
$sender_email = 'xxx@gmail.com';
$user_password = 'xxxxxx';
$token = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 50);
$subject = 'Password Reset';
$message = '';
$message .= "<h2>You are receiving this message in response to your request for password reset</h2>"
. "<p>Follow this link to reset your password <a href='".site_url()."/authenticate/resetpassword/.$token' >Reset Password</a> </p>"
. "<p>If You did not make this request kindly ignore!</p>"
. "<P class='pj'><h2>Kind Regard: Votemate</h2></p>"
. "<style>"
. ".pj{"
. "color:green;"
. "}"
. "</style>"
. "";
// Configure email library
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = $sender_email;
$config['smtp_pass'] = $user_password;
$config['mailtype'] = 'html';
// Load email library and passing configured values to email library
$this->load->library('email', $config);
//$this->email->set_newline("rn");
$this->email->set_mailtype("html");
// Sender email address
$this->email->from($sender_email);
// Receiver email address
$this->email->to($eMail);
// Subject of email
$this->email->subject($subject);
// Message in email
$this->email->message($message);
if ($this->email->send()) {
$eMail = $this->input->post('email');
$ipadd = $this->input->ip_address();
$insert = array(
'email' => $eMail,
'ipaddress' => $ipadd,
'token' => $token
);
$this->db->insert('passwordreset', $insert);
$mail = $this->session->set_userdata('email');
$data['success'] = 'Email Successfully Send !';
$this->load->view('linksent.php', $data);
} else {
$data['error'] = '<p class="error_msg">Invalid Gmail Account or Password !
</p>';
}
$this->load->view('passwordrecovery.php', $data);
}
if($countResult <= 0){
//user already registered
$data['error'] = "<div class='alert alert-warning'> Invalid
email address<span type='button' class='close' data-
dismiss='alert'>&times</span></div>";
$this->load->view('passwordrecovery.php',$data);
}
}
}
</code></pre>
<p>View</p>
<pre><code> <div>
<h1>Password Recovery</h1>
<h3>Enter your email to receive the password reset link in
your Inbox</h3>
<br/>
<?php echo form_open('authenticate/preset');?>
<?php echo $error;?>
<div class="form-group">
<input type="text" name="email" required="required">
</div>
<div class="form-group">
<input type="submit" value="Send" class="btn-success
btn" >
</div>
<?php echo form_close()?>
<br/><br/><br/>
</div>
</code></pre>
<p>Database: The following is database where I store the info:</p>
<pre><code> CREATE TABLE `passwordreset` (
`resetid` int(11) NOT NULL,
`email` varchar(150) NOT NULL,
`ipaddress` varchar(25) NOT NULL,
`token` varchar(512) NOT NULL
) ENGINE
</code></pre>
<p>The help I need is how to get the details (Name, email, token) of the user who click the link from his email and use it to validate and also use it to update his password. Thanks</p> | 0 | 2,639 |
Installation failed with message Error: android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space | <p>I was getting the message </p>
<pre><code>> Installation failed with message Failed to establish session.
</code></pre>
<p>so following some responses to the problem I disabled Instant Run and I started getting</p>
<pre><code>> Installation failed with message Error: android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space.
</code></pre>
<p>I´ve tried rebuilding, cleaning the project, to disable and enable Instant Run and to build APK but nothing solves the problem.</p>
<p>This is my build.gradle (Module:app).</p>
<pre><code> apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.gabriel.justmeet"
minSdkVersion 21
targetSdkVersion 28
versionCode 9
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
useLibrary 'org.apache.http.legacy'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.volley:volley:1.1.0'
}
</code></pre>
<p>and this is the build.gradle(Project)</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven { url 'http://repo1.maven.org/maven2' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'http://repo1.maven.org/maven2' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>This started when I modified my RegisterActivity, so it might help</p>
<pre><code>package com.example.gabriel.paska;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {
public static final String REGISTER_URL ="http://justmeet.000webhostapp.com/php/register.php";
public static final String KEY_USERNAME ="username";
public static final String KEY_PASSWORD="password";
public static final String KEY_NAME ="name";
public static final String KEY_AGE="age";
public static final String REGISTER_SUCCESS ="RegisterSuccess";
public static final String SHARED_PREF_NAME="tech";
public static final String USERNAME_SHARED_PREF="username";
public static final String LOGGEDIN_SHARED_PREF="loggedin";
private boolean loggedIn=false;
EditText etAge;
EditText etName;
EditText etPassword;
EditText etUsername;
Button bRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etAge = findViewById(R.id.etAgeR);
etName = findViewById(R.id.etNameR);
etPassword = findViewById(R.id.etPwordR);
etUsername = findViewById(R.id.etUsernameR);
bRegister = findViewById(R.id.btRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
register();
}
});
}
private void register() {
final String name = etName.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
final String username = etUsername.getText().toString().trim();
final String age = etAge.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(response.trim().equalsIgnoreCase(REGISTER_SUCCESS)){
SharedPreferences sharedPreferences = RegisterActivity.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(USERNAME_SHARED_PREF, name);
editor.apply();
Intent intent = new Intent(RegisterActivity.this, UserActivity.class);
startActivity(intent);
}else{
Toast.makeText(RegisterActivity.this, "Register Failed" + response.trim(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> prams = new HashMap<>();
prams.put(KEY_USERNAME, username);
prams.put(KEY_PASSWORD, password);
prams.put(KEY_NAME, name);
prams.put(KEY_AGE, age);
return prams;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME,Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(LOGGEDIN_SHARED_PREF, false);
if(loggedIn){
Intent intent = new Intent(RegisterActivity.this, UserActivity.class);
startActivity(intent);
}
}
}
</code></pre> | 0 | 3,068 |
TypeError: Failed to execute 'fetch' on 'Window': Invalid value | <p>I've tried to use fetch to call from backend using react, without libs (such as Axios). So I created this function:</p>
<pre><code>export function api(url, method, body, isHeaderContentType,isRequestHeaderAuthentication,header, succesHandler, errorHandler) {
const prefix = 'link';
console.log("url:",prefix+url);
const contentType = isHeaderContentType ? {
'Content-Type': 'application/json',
} : {};
const auth = isRequestHeaderAuthentication
? {
Authorization: `Bearer ${AuthUtils.getTokenUser}`,
}
: {};
fetch(prefix + url, {
method,
headers: {
...contentType,
...auth,
...header,
},
protocol:'http:',
body,
})
.then(response => {
response.json().then(json => {
if (response.ok) {
console.log("method", json);
if (succesHandler) {
succesHandler(json)
}
} else {
return Promise.reject(json)
}
})
})
.catch(err => {
console.log("error",`${url} ${err}`);
if (errorHandler) {
errorHandler(err);
}
})
</code></pre>
<p>}
and call it like this</p>
<pre><code>api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);
</code></pre>
<p>i call my api() inside this function:</p>
<pre><code>getProfileUser = () =>{
if (!isUserAuthenticated()){
history.push('/signin')
}else {
api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);
}
};
</code></pre>
<p>this is my full component:</p>
<pre><code>export default class Profile extends Component {
constructor(props) {
super(props);
this.state = {
profile:[]
}
}
getProfileUser = () =>{
if (!isUserAuthenticated()){
someCode
}else {
api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);
}
};
componentDidMount() {
this.getProfileUser();
}
render(){
return(
<div>
hello
</div>
)
}
</code></pre>
<p>}</p>
<p>but when i tried to run it, i got an error like this</p>
<blockquote>
<p>TypeError: Failed to execute 'fetch' on 'Window': Invalid value</p>
</blockquote>
<p>Is there anyone who knows what's wrong with my code? The function works when I use the "POST" method, but it doesn't work when I use "GET" method</p> | 0 | 1,635 |
faultString: java.lang.IllegalArgumentException: argument type mismatch | <p>I am trying to give web service call using Axis genrated stub.</p>
<p>It is running giving below exception when it tryies to get respons.</p>
<p>and when i view my response message using :</p>
<pre><code>String responseMsg = stub._getCall().getMessageContext().getResponseMessage().getSOAPEnvelope().toString();
</code></pre>
<p>System.out.println(responseMsg);</p>
<p>it is giving the correct response in SOAP format. can anybody help me where it is creating issue thanks in Advance.</p>
<p>Zuned</p>
<pre><code> AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.lang.IllegalArgumentException: argument type mismatch
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:java.lang.IllegalArgumentException: argument type mismatch
at org.apache.axis.encoding.ser.BeanPropertyTarget.set(BeanPropertyTarget.java:157)
at org.apache.axis.encoding.DeserializerImpl.valueComplete(DeserializerImpl.java:249)
at org.apache.axis.encoding.DeserializerImpl.endElement(DeserializerImpl.java:509)
at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
at org.apache.axis.message.SAX2EventRecorder.replay(SAX2EventRecorder.java:171)
at org.apache.axis.message.MessageElement.publishToHandler(MessageElement.java:1141)
at org.apache.axis.message.RPCElement.deserialize(RPCElement.java:236)
at org.apache.axis.message.RPCElement.getParams(RPCElement.java:384)
at org.apache.axis.client.Call.invoke(Call.java:2467)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.hps.webservice.SOAPInterfaceBindingStub.getStatus(SOAPInterfaceBindingStub.java:852)
at com.hps.ws.HPSStatusManagerJob.getApplicationStatusResponse(HPSStatusManagerJob.java:265)
at com.hps.ws.HPSStatusManagerJob.updateStatus(HPSStatusManagerJob.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:264)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:525)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.axis.utils.BeanPropertyDescriptor.set(BeanPropertyDescriptor.java:142)
at org.apache.axis.encoding.ser.BeanPropertyTarget.set(BeanPropertyTarget.java:75)
... 22 more
{http://xml.apache.org/axis/}hostname:admin-PC
java.lang.IllegalArgumentException: argument type mismatch
at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
at org.apache.axis.client.Call.invoke(Call.java:2470)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.hps.webservice.SOAPInterfaceBindingStub.getStatus(SOAPInterfaceBindingStub.java:852)
at com.hps.ws.HPSStatusManagerJob.getApplicationStatusResponse(HPSStatusManagerJob.java:265)
at com.hps.ws.HPSStatusManagerJob.updateStatus(HPSStatusManagerJob.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:264)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:525)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at org.apache.axis.encoding.ser.BeanPropertyTarget.set(BeanPropertyTarget.java:157)
at org.apache.axis.encoding.DeserializerImpl.valueComplete(DeserializerImpl.java:249)
at org.apache.axis.encoding.DeserializerImpl.endElement(DeserializerImpl.java:509)
at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
at org.apache.axis.message.SAX2EventRecorder.replay(SAX2EventRecorder.java:171)
at org.apache.axis.message.MessageElement.publishToHandler(MessageElement.java:1141)
at org.apache.axis.message.RPCElement.deserialize(RPCElement.java:236)
at org.apache.axis.message.RPCElement.getParams(RPCElement.java:384)
at org.apache.axis.client.Call.invoke(Call.java:2467)
... 14 more
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.axis.utils.BeanPropertyDescriptor.set(BeanPropertyDescriptor.java:142)
at org.apache.axis.encoding.ser.BeanPropertyTarget.set(BeanPropertyTarget.java:75)
... 22 more
</code></pre> | 0 | 2,088 |
jQueryUI autocomplete 'select' does not work on mouse click but works on key events | <p><strong>JS/JQuery:</strong></p>
<pre><code>$this.find('input').autocomplete({
source: "/autocomplete_tc_testcasename",
minLength: 2,
focus: function(e,ui){
$(this).val(ui.item.label);
return false;
},
select: function(e, ui) {
console.log("Selected: "+ui.item.value);
}
});
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code> .ui-autocomplete {
max-height: 200px;
overflow-y: auto;
padding: 5px;
}
.ui-menu {
list-style: none;
background-color: #FFFFEE;
width: 50%;
padding: 0px;
border-bottom: 1px solid #DDDDDD;
border-radius: 6px;
-webkit-box-shadow: 0 8px 6px -6px black;
-moz-box-shadow: 0 0px 0px -0px black;
box-shadow: 0px 2px 2px 0px #999999;
}
.ui-menu .ui-menu {
}
.ui-menu .ui-menu-item {
color: #990000;
font-family:"Verdana";
font-size: 12px;
border-top: 3px solid #DDDDDD;
background-color: #FFFFFF;
padding: 10px;
}
</code></pre>
<p><strong>Problem Summary:</strong></p>
<ul>
<li>AJAX works fine, I get all the entries correctly in the autocomplete menu.</li>
<li>I am able to use key up/down arrows to select menu items and once I hit return, select event is fired correctly and console message is displayed.</li>
<li>I can focus on ui-menu-items successfully and capture mouse over events to change value of input text.</li>
<li>I cannot seem to click on menu item and fire a select event. i.e when I click on a menu item, console message is never displayed.</li>
<li>It is as if the click event is dismissing the menu and closing it instead of actually firing a select event. Any idea on how to get over this issue?</li>
<li>I tried "appendTo : $this" instead to input's parent div, and then mouse click works fine! - select event gets fired and console message is displayed successfully. But that is not what I want since the menu is appended within the parent div which distorts the UI since they probably share the same z-index. Even if I change z-index to a higehr number in this case, it didn't quite help. So I'm looking for a solution where I don't 'have' to use appendTo if possible.</li>
</ul>
<p>I found various other questions quite in the ballpark, but none of these seem to address my question.</p>
<p><a href="https://stackoverflow.com/questions/7961708/jquery-autocomplete-left-mouse-click-not-firing-select-event">jQuery Autocomplete - Left Mouse Click not firing Select event</a></p>
<p><a href="https://stackoverflow.com/questions/7315556/jquery-ui-autocomplete-select-event-not-working-with-mouse-click">jQuery UI autocomplete select event not working with mouse click</a></p>
<p>Thanks!</p> | 0 | 1,161 |
File Upload to aws S3 Laravel 5.1 | <p>I am getting the Following Error:</p>
<blockquote>
<p>FatalErrorException in FilesystemManager.php line 179: Class
'League\Flysystem\AwsS3v3\AwsS3Adapter' not found</p>
</blockquote>
<p><strong>Code:</strong></p>
<pre><code>//Composer.json
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.1.*",
"laravel/socialite": "~2.0",
"guzzlehttp/guzzle": "~4.0",
"predis/predis": "^1.0",
"tymon/jwt-auth": "0.5.*",
"league/flysystem-aws-s3-v2": "^1.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~4.0",
"phpspec/phpspec": "~2.1"
}
//config/filesystem.php
'default' => 's3',
'cloud' => 's3',
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
's3' => [
'driver' => 's3',
'key' => '***********',
'secret' => '**************************************',
'region' => '*****',
'bucket' => '************',
],
],
//FileController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Contracts\Filesystem\Filesystem;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
public function postProfilePhoto(Request $request)
{
$token=JWTAuth::getToken();
$user = JWTAuth::toUser($token);
$image = $request->file('image');
//return $image;
$id=$user->id;
if($image)
{
$imageFileName = time() . '.' . $image->getClientOriginalExtension();
//return $imageFileName;
$s3 = \Storage::disk('s3');
$filePath = '/profilePhotos/'.$id . $imageFileName;
$s3->put($filePath, file_get_contents($image), 'public');
try{
ProfilePhoto::create(['userId'=>$id,'imgUrl'=>$filePath]);
return json_encode(['message'=>'Done!','Id'=>200,'Response'=>'']);
}
catch(Exception $e)
{
return json_encode(['message'=>'Not Allowed!','Id'=>402,'Response'=>'']);
}
}
else
{
return json_encode(['message'=>'No Pic!','Id'=>404,'Response'=>'']);
}
}
</code></pre> | 0 | 1,492 |
Vite / Vue 3 : "require is not defined" when using image source as props | <p>I switched from the Vue CLI to <a href="https://vitejs.dev/" rel="noreferrer">Vite CLI</a>, and from the Composition API of Vue 3 to <a href="https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup" rel="noreferrer">SFC Script setup</a> API.</p>
<h3>How it previously worked for me</h3>
<p>When I was using the official Vue CLI, I could import an image source by passing the filename of the path by the props :</p>
<pre class="lang-html prettyprint-override"><code><template>
<img :src="require(`@/assets/${imagePath}`)"/>
<template/>
<script>
export default {
props: {
imagePath: { type: String },
},
setup() {
// ...
}
}
<script/>
</code></pre>
<p>And then call it like this :</p>
<pre class="lang-html prettyprint-override"><code><template>
<Image imagePath="icon.png" />
</template>
</code></pre>
<h3>The error I get since I migrated to Vite</h3>
<p>But since I migrated to the Vite CLI, I have an error "Uncaught ReferenceError: require is not defined". My file now use the script setup syntax and looks like this :</p>
<pre class="lang-html prettyprint-override"><code><script setup>
const props = defineProps({
imagePath: { type: String },
})
</script>
<template>
<img :src="require(`@/assets/${props.imagePath}`)"/>
</template>
</code></pre>
<p><a href="https://i.stack.imgur.com/6Y5kL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6Y5kL.png" alt="require is not define error" /></a></p>
<h3>What I tried</h3>
<p>I already tried to import the file directly from the assets folder with a relative path, and it worked. But I cannot specify the path from props with the import statement.</p>
<pre class="lang-html prettyprint-override"><code><script setup>
// Works but do not use the props, so the component is not reusable
import logo from "./../assets/logo.png"
</script>
<template>
<img :src="logo"/>
</template>
</code></pre>
<pre class="lang-html prettyprint-override"><code><script setup>
// Component is reusable but the import statement has illegal argument I guess
const props = defineProps({
imagePath: { type: String },
})
import logo from `./../assets/${props.imagePath}`
</script>
<template>
<img :src="logo"/>
</template>
</code></pre>
<p>I also tried the import statement in the template but it cannot even compile the code :</p>
<pre class="lang-html prettyprint-override"><code><script setup>
const props = defineProps({
imagePath: { type: String },
})
</script>
<template>
<img :src="import `./../assets/${props.iconPath}`" />
</template>
</code></pre>
<p>Am I missing something ? Maybe a plugin exists and can help me achieve this ?</p> | 0 | 1,084 |
how to set unread notification count in NavigationView of DrawerLayout? | <p>I have created one <a href="https://developer.android.com/reference/android/support/design/widget/NavigationView.html" rel="noreferrer">NavigationView</a> inside <a href="https://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html" rel="noreferrer">DrawerLayout</a> using <a href="http://android-developers.blogspot.in/2015/05/android-design-support-library.html" rel="noreferrer">Android Design Support Library </a></p>
<pre><code> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- other views -->
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/my_navigation_items" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p><strong>my_navigation_items.xml</strong></p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/bookmarks_drawer"
android:icon="@drawable/ic_drawer_bookmarks"
android:title="@string/bookmarks" />
<item
android:id="@+id/alerts_drawer"
android:icon="@drawable/ic_drawer_alerts"
android:title="@string/alerts" />
<item
android:id="@+id/settings_drawer"
android:icon="@drawable/ic_drawer_settings"
android:title="@string/settings" />
</group>
</menu>
</code></pre>
<p>Now, I want to set unread notification counter for each item of <code>NavigationView</code> like below image:</p>
<p><a href="https://i.stack.imgur.com/TlsFf.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/TlsFf.jpg" alt="unread notification counter" /></a></p>
<p>how to set unread notification counter on item of <code>NavigationView</code> ?</p> | 0 | 1,104 |
How should I use GCD dispatch_barrier_async in iOS (seems to execute before and not after other blocks) | <p>I'm trying to synchronize the following code in iOS5:</p>
<ol>
<li>an object has a method which makes an HTTP request from which it
gets some data, including an URL to an image</li>
<li>once the data arrives, the textual data is used to populate a
CoreData model</li>
<li>at the same time, a second thread is dispatched async to download
the image; this thread will signal via KVO to a viewController when
the image is already cached and available in the CoreData model.</li>
<li>since the image download will take a while, we immediately return
the CoreData object which has all attributes but for the image to
the caller.</li>
<li>Also, when the second thread is done downloading, the CoreData model
can be saved.</li>
</ol>
<p>This is the (simplified) code:</p>
<pre><code>- (void)insideSomeMethod
{
[SomeHTTPRequest withCompletionHandler:
^(id retrievedData)
{
if(!retrievedData)
{
handler(nil);
}
// Populate CoreData model with retrieved Data...
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSURL* userImageURL = [NSURL URLWithString:[retrievedData valueForKey:@"imageURL"]];
aCoreDataNSManagedObject.profileImage = [NSData dataWithContentsOfURL:userImageURL];
});
handler(aCoreDataNSManagedObject);
[self shouldCommitChangesToModel];
}];
}
- (void)shouldCommitChangesToModel
{
dispatch_barrier_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSError *error = nil;
if(![managedObjectContext save:&error])
{
// Handle error
}
});
}
</code></pre>
<p>But what's going on is that the barrier-based save-block is always executed before the the image-loading block. That is,</p>
<pre><code>dispatch_barrier_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSError *error = nil;
if(![managedObjectContext save:&error])
{
// Handle error
}
});
</code></pre>
<p>Executes before:</p>
<pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSURL* userImageURL = [NSURL URLWithString:[retrievedData valueForKey:@"imageURL"]];
aCoreDataNSManagedObject.profileImage = [NSData dataWithContentsOfURL:userImageURL];
});
</code></pre>
<p>So obviously I'm not really dispatching the image-loading block before the barrier, or the barrier would wait until the image-loading block is done before executing (which was my intention).</p>
<p>What am I doing wrong? how do I make sure the image-loading block is enqueued before the barrier block?</p> | 0 | 1,103 |
Symfony 3.4 - Make sure annotations are installed and enabled | <p>I am trying to implement a forgot password feature to an existing Symfony app. So fare I have the password request done. The user puts in it's email and an email is sent with a token. The return URL looks like this:</p>
<p>/intranet/password-change/f74eab6dca8b5ed6fd46e7893221254b655f94799589e0b83c</p>
<p>Normally a forme should show but when i visite that URL i get this message:</p>
<blockquote>
<p>Class App\Controller\ResettingController does not exist in
/public_html/intranet/src/AppBundle/Controller/ (which is
being imported from "/public_html/intranet/app/config/routing.yml").
Make sure annotations are installed and enabled.</p>
</blockquote>
<p>I don't get it ... I have the controller set up at the right place and the route should be taken care of by the annotations.</p>
<p>My routing file:</p>
<pre><code>app:
resource: "@AppBundle/Controller/"
type: annotation
coop_tilleuls_forgot_password.reset:
path: '/api/forgot-password'
defaults: { _controller: coop_tilleuls_forgot_password.controller.forgot_password:resetPasswordAction}
methods: [POST]
coop_tilleuls_forgot_password.update:
path: '/api/reset-password/{tokenValue}'
defaults: { _controller: coop_tilleuls_forgot_password.controller.forgot_password:updatePasswordAction}
</code></pre>
<p>as for my resseting class it's in
/public_html/intranet/src/AppBundle/Controller</p>
<p>And looks like this:</p>
<pre><code><?php
// src/Controller/ResettingController.php
namespace App\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Form\FormErrorIterator;
use App\Entity\User;
use App\Services\Mailer;
use App\Form\ResettingType;
/**
* @Route("/password-change")
*/
class ResettingController extends Controller
{
/**
* @Route("/{id}/{token}", name="resetting")
*/
public function resetting(User $user, $token, Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
// interdit l'accès à la page si:
// le token associé au membre est null
// le token enregistré en base et le token présent dans l'url ne sont pas égaux
// le token date de plus de 10 minutes
if ($user->getToken() === null || $token !== $user->getToken() || !$this->isRequestInTime($user->getPasswordRequestedAt()))
{
throw new AccessDeniedHttpException();
}
$form = $this->createForm(ResettingType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
// réinitialisation du token à null pour qu'il ne soit plus réutilisable
$user->setToken(null);
$user->setPasswordRequestedAt(null);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$request->getSession()->getFlashBag()->add('success', "Votre mot de passe a été modifié.");
return $this->redirectToRoute('security_login_form');
}
return $this->render('security/resetting.html.twig', [
'form' => $form->createView()
]);
}
}
</code></pre>
<p>I am new to symfony so I might be missing something obvious ... I just don't see it lol thx in advance</p> | 0 | 1,636 |
Segmentation faults occur when I run a parallel program with Open MPI | <p>on my previous post I needed to distribute data of pgm files among 10 computers. With help from Jonathan Dursi and Shawn Chin, I have integrate the code.
I can compile my program but it got segmentation fault. I ran but nothing happen </p>
<p><code>mpirun -np 10 ./exmpi_2 balloons.pgm output.pgm</code></p>
<p>The result is</p>
<pre><code>[ubuntu:04803] *** Process received signal ***
[ubuntu:04803] Signal: Segmentation fault (11)
[ubuntu:04803] Signal code: Address not mapped (1)
[ubuntu:04803] Failing at address: 0x7548d0c
[ubuntu:04803] [ 0] [0x86b410]
[ubuntu:04803] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0x186b00]
[ubuntu:04803] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04803] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x141bd6]
[ubuntu:04803] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04803] *** End of error message ***
--------------------------------------------------------------------------
mpirun noticed that process rank 1 with PID 4803 on node ubuntu exited on signal 11 (Segmentation fault).
--------------------------------------------------------------------------
</code></pre>
<p>Then i try run with valgrind to debug the program and the output.pgm is generated</p>
<p><code>valgrind mpirun -np 10 ./exmpi_2 balloons.pgm output.pgm</code></p>
<p>The result is</p>
<pre><code>==4632== Memcheck, a memory error detector
==4632== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==4632== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==4632== Command: mpirun -np 10 ./exmpi_2 2.pgm 10.pgm
==4632==
==4632== Syscall param sched_setaffinity(mask) points to unaddressable byte(s)
==4632== at 0x4215D37: syscall (syscall.S:31)
==4632== by 0x402B335: opal_paffinity_linux_plpa_api_probe_init (plpa_api_probe.c:56)
==4632== by 0x402B7CC: opal_paffinity_linux_plpa_init (plpa_runtime.c:37)
==4632== by 0x402B93C: opal_paffinity_linux_plpa_have_topology_information (plpa_map.c:494)
==4632== by 0x402B180: linux_module_init (paffinity_linux_module.c:119)
==4632== by 0x40BE2C3: opal_paffinity_base_select (paffinity_base_select.c:64)
==4632== by 0x40927AC: opal_init (opal_init.c:295)
==4632== by 0x4046767: orte_init (orte_init.c:76)
==4632== by 0x804A82E: orterun (orterun.c:540)
==4632== by 0x804A3EE: main (main.c:13)
==4632== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==4632==
[ubuntu:04638] *** Process received signal ***
[ubuntu:04639] *** Process received signal ***
[ubuntu:04639] Signal: Segmentation fault (11)
[ubuntu:04639] Signal code: Address not mapped (1)
[ubuntu:04639] Failing at address: 0x7548d0c
[ubuntu:04639] [ 0] [0xc50410]
[ubuntu:04639] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0xde4b00]
[ubuntu:04639] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04639] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0xd9fbd6]
[ubuntu:04639] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04639] *** End of error message ***
[ubuntu:04640] *** Process received signal ***
[ubuntu:04640] Signal: Segmentation fault (11)
[ubuntu:04640] Signal code: Address not mapped (1)
[ubuntu:04640] Failing at address: 0x7548d0c
[ubuntu:04640] [ 0] [0xdad410]
[ubuntu:04640] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0xe76b00]
[ubuntu:04640] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04640] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0xe31bd6]
[ubuntu:04640] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04640] *** End of error message ***
[ubuntu:04641] *** Process received signal ***
[ubuntu:04641] Signal: Segmentation fault (11)
[ubuntu:04641] Signal code: Address not mapped (1)
[ubuntu:04641] Failing at address: 0x7548d0c
[ubuntu:04641] [ 0] [0xe97410]
[ubuntu:04641] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0x1e8b00]
[ubuntu:04641] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04641] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x1a3bd6]
[ubuntu:04641] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04641] *** End of error message ***
[ubuntu:04642] *** Process received signal ***
[ubuntu:04642] Signal: Segmentation fault (11)
[ubuntu:04642] Signal code: Address not mapped (1)
[ubuntu:04642] Failing at address: 0x7548d0c
[ubuntu:04642] [ 0] [0x92d410]
[ubuntu:04642] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0x216b00]
[ubuntu:04642] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04642] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x1d1bd6]
[ubuntu:04642] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04642] *** End of error message ***
[ubuntu:04643] *** Process received signal ***
[ubuntu:04643] Signal: Segmentation fault (11)
[ubuntu:04643] Signal code: Address not mapped (1)
[ubuntu:04643] Failing at address: 0x7548d0c
[ubuntu:04643] [ 0] [0x8f4410]
[ubuntu:04643] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0x16bb00]
[ubuntu:04643] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04643] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x126bd6]
[ubuntu:04643] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04643] *** End of error message ***
[ubuntu:04638] Signal: Segmentation fault (11)
[ubuntu:04638] Signal code: Address not mapped (1)
[ubuntu:04638] Failing at address: 0x7548d0c
[ubuntu:04638] [ 0] [0x4f6410]
[ubuntu:04638] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0x222b00]
[ubuntu:04638] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04638] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x1ddbd6]
[ubuntu:04638] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04638] *** End of error message ***
[ubuntu:04644] *** Process received signal ***
[ubuntu:04644] Signal: Segmentation fault (11)
[ubuntu:04644] Signal code: Address not mapped (1)
[ubuntu:04644] Failing at address: 0x7548d0c
[ubuntu:04644] [ 0] [0x61f410]
[ubuntu:04644] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0x1a3b00]
[ubuntu:04644] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04644] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x15ebd6]
[ubuntu:04644] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04644] *** End of error message ***
[ubuntu:04645] *** Process received signal ***
[ubuntu:04645] Signal: Segmentation fault (11)
[ubuntu:04645] Signal code: Address not mapped (1)
[ubuntu:04645] Failing at address: 0x7548d0c
[ubuntu:04645] [ 0] [0x7a3410]
[ubuntu:04645] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0x1d5b00]
[ubuntu:04645] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04645] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x190bd6]
[ubuntu:04645] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04645] *** End of error message ***
[ubuntu:04647] *** Process received signal ***
[ubuntu:04647] Signal: Segmentation fault (11)
[ubuntu:04647] Signal code: Address not mapped (1)
[ubuntu:04647] Failing at address: 0x7548d0c
[ubuntu:04647] [ 0] [0xf54410]
[ubuntu:04647] [ 1] /lib/tls/i686/cmov/libc.so.6(fclose+0x1a0) [0x2bab00]
[ubuntu:04647] [ 2] ./exmpi_2(main+0x78e) [0x80492c2]
[ubuntu:04647] [ 3] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x275bd6]
[ubuntu:04647] [ 4] ./exmpi_2() [0x8048aa1]
[ubuntu:04647] *** End of error message ***
--------------------------------------------------------------------------
mpirun noticed that process rank 2 with PID 4639 on node ubuntu exited on signal 11 (Segmentation fault).
--------------------------------------------------------------------------
6 total processes killed (some possibly by mpirun during cleanup)
==4632==
==4632== HEAP SUMMARY:
==4632== in use at exit: 158,751 bytes in 1,635 blocks
==4632== total heap usage: 10,443 allocs, 8,808 frees, 15,854,537 bytes allocated
==4632==
==4632== LEAK SUMMARY:
==4632== definitely lost: 81,655 bytes in 112 blocks
==4632== indirectly lost: 5,108 bytes in 91 blocks
==4632== possibly lost: 1,043 bytes in 17 blocks
==4632== still reachable: 70,945 bytes in 1,415 blocks
==4632== suppressed: 0 bytes in 0 blocks
==4632== Rerun with --leak-check=full to see details of leaked memory
==4632==
==4632== For counts of detected and suppressed errors, rerun with: -v
==4632== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 96 from 9)
</code></pre>
<p>Could someone help me to solve this problem. This is my source code</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mpi.h"
#include <syscall.h>
#define SIZE_X 640
#define SIZE_Y 480
int main(int argc, char **argv)
{
FILE *FR,*FW;
int ierr;
int rank, size;
int ncells;
int greys[SIZE_X][SIZE_Y];
int rows,cols, maxval;
int mystart, myend, myncells;
const int IONODE=0;
int *disps, *counts, *mydata;
int *data;
int i,j,temp1;
char dummy[50]="";
ierr = MPI_Init(&argc, &argv);
if (argc != 3) {
fprintf(stderr,"Usage: %s infile outfile\n",argv[0]);
fprintf(stderr,"outputs the negative of the input file.\n");
return -1;
}
ierr = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
ierr = MPI_Comm_size(MPI_COMM_WORLD, &size);
if (ierr) {
fprintf(stderr,"Catastrophic MPI problem; exiting\n");
MPI_Abort(MPI_COMM_WORLD,1);
}
if (rank == IONODE) {
//if (read_pgm(argv[1], &greys, &rows, &cols, &maxval)) {
// fprintf(stderr,"Could not read file; exiting\n");
// MPI_Abort(MPI_COMM_WORLD,2);
rows=SIZE_X;
cols=SIZE_Y;
maxval=255;
FR=fopen(argv[1], "r+");
fgets(dummy,50,FR);
do{ fgets(dummy,50,FR); } while(dummy[0]=='#');
fgets(dummy,50,FR);
for (j = 0; j <cols; j++)
{
for (i = 0; i <rows; i++)
{
fscanf(FR,"%d",&temp1);
greys[i][j] = temp1;
}
}
}
ncells = rows*cols;
disps = (int *)malloc(size * sizeof(int));
counts= (int *)malloc(size * sizeof(int));
data = &(greys[0][0]); /* we know all the data is contiguous */
/* everyone calculate their number of cells */
ierr = MPI_Bcast(&ncells, 1, MPI_INT, IONODE, MPI_COMM_WORLD);
myncells = ncells/size;
mystart = rank*myncells;
myend = mystart + myncells - 1;
if (rank == size-1) myend = ncells-1;
myncells = (myend-mystart)+1;
mydata = (int *)malloc(myncells * sizeof(int));
/* assemble the list of counts. Might not be equal if don't divide evenly. */
ierr = MPI_Gather(&myncells, 1, MPI_INT, counts, 1, MPI_INT, IONODE, MPI_COMM_WORLD);
if (rank == IONODE) {
disps[0] = 0;
for (i=1; i<size; i++) {
disps[i] = disps[i-1] + counts[i-1];
}
}
/* scatter the data */
ierr = MPI_Scatterv(data, counts, disps, MPI_INT, mydata, myncells, MPI_INT, IONODE, MPI_COMM_WORLD);
/* everyone has to know maxval */
ierr = MPI_Bcast(&maxval, 1, MPI_INT, IONODE, MPI_COMM_WORLD);
for (i=0; i<myncells; i++)
mydata[i] = maxval-mydata[i];
/* Gather the data */
ierr = MPI_Gatherv(mydata, myncells, MPI_INT, data, counts, disps, MPI_INT, IONODE, MPI_COMM_WORLD);
if (rank == IONODE)
{
// write_pgm(argv[2], greys, rows, cols, maxval);
FW=fopen(argv[2], "w");
fprintf(FW,"P2\n%d %d\n255\n",rows,cols);
for(j=0;j<cols;j++)
for(i=0;i<rows;i++)
fprintf(FW,"%d ", greys[i][j]);
}
free(mydata);
if (rank == IONODE) {
free(counts);
free(disps);
//free(&(greys[0][0]));
//free(greys);
}
fclose(FR);
fclose(FW);
MPI_Finalize();
return 0;
}
</code></pre>
<p>This is the input image <a href="http://orion.math.iastate.edu/burkardt/data/pgm/balloons.pgm" rel="noreferrer">http://orion.math.iastate.edu/burkardt/data/pgm/balloons.pgm</a></p> | 0 | 5,178 |
ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit. .POST_MODULE | <p>Help!
I want deployed im have this error:</p>
<blockquote>
<p>22:50:45,854 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-1) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./opciondefensa.UndertowDeploymentInfoService: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./opciondefensa.UndertowDeploymentInfoService: java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet from [Module "deployment.opciondefensa.war:main" from Service Module Loader]
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.createServletConfig(UndertowDeploymentInfoService.java:1066)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.start(UndertowDeploymentInfoService.java:281)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet from [Module "deployment.opciondefensa.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.createServletConfig(UndertowDeploymentInfoService.java:721)
... 6 more</p>
</blockquote>
<p>22:50:45,860 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "opciondefensa.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.undertow.deployment.default-server.default-host./opciondefensa.UndertowDeploymentInfoService" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./opciondefensa.UndertowDeploymentInfoService: java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet from [Module \"deployment.opciondefensa.war:main\" from Service Module Loader]
Caused by: java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet from [Module \"deployment.opciondefensa.war:main\" from Service Module Loader]"}}</p>
<hr>
<p>**</p>
<blockquote>
<p>MY POM BELOW follow the same trouble.</p>
</blockquote>
<p>**</p>
<hr>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cl.legal</groupId>
<artifactId>opciondefensa</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>opciondefensa Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.2.5.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<tiles.version>3.0.1</tiles.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.6.1</slf4j.version>
<logback.version>0.9.26</logback.version>
<postgresql.version>9.4.1208</postgresql.version>
<javax.version>3.1.0</javax.version>
<jsp.version>2.1</jsp.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>provided</scope>
</dependency>
<!-- SERVLET -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
<scope>provided</scope>
</dependency>
<!-- SPRING FRAMEWORK -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.springframework</groupId> -->
<!-- <artifactId>spring-test</artifactId> -->
<!-- <version>${spring.version}</version> -->
<!-- <scope>provided</scope> -->
<!-- </dependency> -->
<!-- ORM HIBERNATE [JPA] -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.1.0.Final</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>dom4j</groupId> -->
<!-- <artifactId>dom4j</artifactId> -->
<!-- <version>1.6.1</version> -->
<!-- <scope>provided</scope> -->
<!-- </dependency> -->
<!-- postgres Connector-->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
<scope>provided</scope>
</dependency>
<!-- Tiles -->
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-extras</artifactId>
<version>${tiles.version}</version>
</dependency>
<!-- Apache Commons Upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>2.4.4</version>
</dependency>
<!-- Log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
<finalName>opciondefensa</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre> | 0 | 6,774 |
Set custom layout in popup window in android | <p>I have a problem with popup window. I want to create popup window with my own layout.
This is code:</p>
<pre><code>public class PopupWindowView extends PopupWindow{
PopupWindow popup;
boolean click = true;
LayoutParams params;
RelativeLayout mainLayout;
TextView tv;
LinearLayout layout;
ImageView chooseFlag;
public void createPopupWindow(Activity act){
popup = new PopupWindow(act);
chooseFlag = (ImageView) act.findViewById(R.id.login_choose_flag);
mainLayout = (RelativeLayout) act.findViewById(R.id.login_layout);
tv = new TextView(act);
layout = new LinearLayout(act);
//layout = (LinearLayout) findViewById(R.id.popuplayout);
chooseFlag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (click) {
int[] values = new int[2];
v.getLocationOnScreen(values);
popup.showAtLocation(mainLayout, Gravity.NO_GRAVITY, 10, 10);
popup.update(values[0], values[1], 300, 80);
click = false;
} else {
popup.dismiss();
click = true;
}
}
});
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
tv.setText("Hi this is a sample text for popup window");
layout.addView(tv, params);
popup.setContentView(layout);
}
}
</code></pre>
<p>and this is layout which I want to set in my popup window:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="@+id/popuplayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/patient_button_bg">
</LinearLayout>
</LinearLayout>
</code></pre>
<p>In my class I can't use <code>findbyid</code> method because this is not Activity. How I can set my own layout in popup widow in my class?</p>
<p>Edit:
this is stack trace where I get error:</p>
<pre><code>03-01 09:48:48.761: E/AndroidRuntime(16776): FATAL EXCEPTION: main
03-01 09:48:48.761: E/AndroidRuntime(16776): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.view.ViewGroup.addViewInner(ViewGroup.java:3337)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.view.ViewGroup.addView(ViewGroup.java:3208)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.view.ViewGroup.addView(ViewGroup.java:3188)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.widget.PopupWindow.preparePopup(PopupWindow.java:969)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.widget.PopupWindow.showAtLocation(PopupWindow.java:840)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.widget.PopupWindow.showAtLocation(PopupWindow.java:813)
03-01 09:48:48.761: E/AndroidRuntime(16776): at pl.asseco.amms.mobile.tools.PopupWindowView$1.onClick(PopupWindowView.java:44)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.view.View.performClick(View.java:3558)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.view.View$PerformClick.run(View.java:14152)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.os.Handler.handleCallback(Handler.java:605)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.os.Handler.dispatchMessage(Handler.java:92)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.os.Looper.loop(Looper.java:137)
03-01 09:48:48.761: E/AndroidRuntime(16776): at android.app.ActivityThread.main(ActivityThread.java:4514)
03-01 09:48:48.761: E/AndroidRuntime(16776): at java.lang.reflect.Method.invokeNative(Native Method)
03-01 09:48:48.761: E/AndroidRuntime(16776): at java.lang.reflect.Method.invoke(Method.java:511)
03-01 09:48:48.761: E/AndroidRuntime(16776): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
03-01 09:48:48.761: E/AndroidRuntime(16776): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
03-01 09:48:48.761: E/AndroidRuntime(16776): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Edit
Activity which use popup:</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getActionBar().hide();
mainMenuGenerator = new MainMenuGenerator();
mainMenuGenerator.generateMainMenu(this);
mainMenuGenerator.hideIcons();
popup = new PopupWindowView();
popup.createPopupWindow(this);
}
</code></pre> | 0 | 2,107 |
Spring Issues: Error creating beans and Injection of autowired dependencies failed | <p>So i'm trying to learn spring and i've been reading a lot of tutorials and trying copying some code from a project that I have in a flash drive.</p>
<p>I already set up tomcat and it works find but i'm still having some problems here.
The thing is I can normally access a controller's action from my browser without a problem, but when I started adding annotations and ContextLoaderListener it gave me a 404 status all the time. I don't know what I did, but by tweaking some things around, my browser at least tries to reach the controller again. But throws a huge error log which I will share at the end of this post.</p>
<p>These are my dependencies:</p>
<blockquote>
<ul>
<li>junit 4.12</li>
<li>spring-webmvc 4.1.6.RELEASE </li>
<li>spring-context 4.1.6.RELEASE</li>
<li>spring-web 4.1.6.RELEASE</li>
<li>spring-beans 4.1.6.RELEASE</li>
<li>spring-data-jpa 1.8.0.RELEASE</li>
<li>spring-jdbc 4.1.6.RELEASE</li>
<li>mysql-connector-java 5.1.35</li>
<li>jstl 1.2</li>
<li>javax.servlet-api 3.1.0 (scope provided)</li>
<li>javax.servlet.jsp-api 3.1.0 (scope provided)</li>
<li>jackson-databind 2.5.4</li>
<li>jackson-core 2.5.4</li>
<li>jackson-core-asl 1.9.13</li>
<li>jackson-datatype-hibernate4 2.5.4</li>
<li>hibernate-annotations 3.5.6-Final</li>
<li>hibernate-commons-annotations 3.2.0.Final</li>
<li>hibernate-entitymanager 4.3.10.Final</li>
<li>jsondoc-core 1.1.15</li>
<li>jsondoc-springmvc 1.1.15</li>
<li>jsondoc-ui-webjar 1.1.15</li>
<li>commons-logging 1.2</li>
<li>commons-logging-api 1.1</li>
<li>commons-dbcp 1.4</li>
</ul>
</blockquote>
<p>My build plugins are:</p>
<blockquote>
<ul>
<li>maven-compiler-plugin 3.1 (source and target 1.8)</li>
<li>maven-war-plugin 2.4</li>
</ul>
</blockquote>
<p><strong>My web.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Spring Web MVC Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:WEB-INF/application-context.xml
classpath*:WEB-INF/persistence-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</code></pre>
<p></p>
<p><strong>My mvc-dispatcher-servlet</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.ve" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.ve.main.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="documentationController" class="org.jsondoc.springmvc.controller.JSONDocController">
<constructor-arg name="version" value="1.0"/>
<constructor-arg name="basePath" value="http://localhost:4848/spring2"/>
<constructor-arg name="packages">
<list>
<value>com.ve</value>
</list>
</constructor-arg>
</bean>
</code></pre>
<p></p>
<p><strong>My application-context.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.ve" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
</code></pre>
<p></p>
<p><strong>My persistence-context.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/my_database" />
<property name="username" value="my_actual_db_user" />
<property name="password" value="my_actual_db_password" />
</bean>
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="dataSource" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="persistenceUnit" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<jpa:repositories base-package="com.ve" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" />
</code></pre>
<p></p>
<p>And just for information i will also quote my classes code and my project structure</p>
<p><strong>StockController</strong></p>
<pre><code>package com.ve.common.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ve.common.service.StockService;
@Controller
@RequestMapping("/stock")
public class StockController {
@Autowired
private StockService stockService;
public StockController(){}
@RequestMapping(value="/list", method = RequestMethod.GET, produces={"application/json","application/xml"})
@ResponseBody
public String findAllStocks(){
return "stocks";
}
}
</code></pre>
<p><strong>StockService</strong></p>
<pre><code>package com.ve.common.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ve.common.model.Stock;
import com.ve.common.repo.StockRepository;
@Service
public class StockService {
@Autowired
private StockRepository stockRepository;
StockService(){}
List<Stock> findStock(){
return (List<Stock>) stockRepository.findAll();
}
}
</code></pre>
<p><strong>StockRepository</strong></p>
<pre><code>package com.ve.common.repo;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.ve.common.model.Stock;
@Repository
public interface StockRepository extends CrudRepository<Stock, Integer> {
List<Stock> findByStockName(String stockName);
Stock findByStockId(Integer stockId);
}
</code></pre>
<p>My model is a basic Entity class that implements Serializable (created by JPA tools).
Now this is my project structure, I'm sorry I couldn't make the image smaller (i'm in a ruch at the moment).
<img src="https://i.stack.imgur.com/EfyIF.png" alt="Project Structure"></p>
<p>And here is a quote of that huge error i get in my browser when i access "<a href="http://localhost:4848/spring2/api/welcome/hi" rel="noreferrer">http://localhost:4848/spring2/api/welcome/hi</a>" or "<a href="http://localhost:4848/spring2/api/stock/list" rel="noreferrer">http://localhost:4848/spring2/api/stock/list</a>"</p>
<blockquote>
<p>HTTP Status 500 - Servlet.init() for servlet mvc-dispatcher threw
exception</p>
<p>type Exception report</p>
<p>message Servlet.init() for servlet mvc-dispatcher threw exception</p>
<p>description The server encountered an internal error that prevented it
from fulfilling this request.</p>
<p>exception</p>
<p>javax.servlet.ServletException: Servlet.init() for servlet
mvc-dispatcher threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)</p>
<p>root cause</p>
<p>org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'stockController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.ve.common.service.StockService
com.ve.common.controller.StockController.stockService; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.ve.common.service.StockService] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)</p>
<p>root cause</p>
<p>org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.ve.common.service.StockService
com.ve.common.controller.StockController.stockService; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.ve.common.service.StockService] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)</p>
<p>root cause</p>
<p>org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.ve.common.service.StockService] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)</p>
</blockquote>
<p>I apologize for the excessive code blocking and blockquoting, but I think the more information I provide, the better help I can get. And I thank in advance whoever can give me a hand.</p> | 0 | 8,459 |
How to map function address to function in *.so files | <p>backtrace function give set of backtrace how to map it with function name/file name/line number?</p>
<pre><code>for ex:-
backtrace() returned 8 addresses
./libtst.so(myfunc5+0x2b) [0xb7767767]
./libtst.so(fun4+0x4a) [0xb7767831]
./libtst.so(fun3+0x48) [0xb776787f]
./libtst.so(fun2+0x35) [0xb77678ba]
./libtst.so(fun1+0x35) [0xb77678f5]
./a.out() [0x80485b9]
/lib/libc.so.6(__libc_start_main+0xe5) [0xb75e9be5]
./a.out() [0x80484f1]
</code></pre>
<p>From the above stack how can I get the file name and line number?
I did following things, but no luck. Correct me if I am wrong :)</p>
<pre><code>for ex:-
./libtst.so(fun2+0x35) [0xb77dc887]
0xb77dc887(fun2 addr+offset)-0xb77b6000 (lib starting addr) = 0x26887 (result)
result is no way related to function in nm output.
I used addr2line command:-
addr2line -f -e libtst.so 0xb77dc887
??
??:0
</code></pre>
<p>So, how can I resolve either at runtime or post runtime?
Thanks in advance...</p>
<pre><code>nm:-
00000574 T _init
00000680 t __do_global_dtors_aux
00000700 t frame_dummy
00000737 t __i686.get_pc_thunk.bx
0000073c T myfunc5
000007e7 T fun4
00000837 T fun3
00000885 T fun2
000008c0 T fun1
00000900 t __do_global_ctors_aux
00000938 T _fini
000009b4 r __FRAME_END__
00001efc d __CTOR_LIST__
00001f00 d __CTOR_END__
00001f04 d __DTOR_LIST__
00001f08 d __DTOR_END__
00001f0c d __JCR_END__
00001f0c d __JCR_LIST__
00001f10 a _DYNAMIC
00001ff4 a _GLOBAL_OFFSET_TABLE_
00002030 d __dso_handle
00002034 A __bss_start
00002034 A _edata
00002034 b completed.5773
00002038 b dtor_idx.5775
0000203c B funptr
00002040 A _end
U backtrace@@GLIBC_2.1
U backtrace_symbols@@GLIBC_2.1
U free@@GLIBC_2.0
U __isoc99_scanf@@GLIBC_2.7
U perror@@GLIBC_2.0
U printf@@GLIBC_2.0
U puts@@GLIBC_2.0
w __cxa_finalize@@GLIBC_2.1.3
w __gmon_start__
w _Jv_RegisterClasses
pmap:-
START SIZE RSS PSS DIRTY SWAP PERM MAPPING
08048000 4K 4K 4K 0K 0K r-xp /home/test/libtofun/a.out
08049000 4K 4K 4K 4K 0K r--p /home/test/libtofun/a.out
0804a000 4K 4K 4K 4K 0K rw-p /home/test/libtofun/a.out
...
b7767000 4K 4K 4K 0K 0K r-xp /home/test/libtofun/libtst.so
b7768000 4K 4K 4K 4K 0K r--p /home/test/libtofun/libtst.so
b7769000 4K 4K 4K 4K 0K rw-p /home/test/libtofun/libtst.so
....
Total: 1688K 376K 82K 72K 0K
</code></pre>
<p>128K writable-private, 1560K readonly-private, 0K shared, and 376K referenced</p>
<pre><code>libtst.c:-
void myfunc5(void){
int j, nptrs;
#define SIZE 100
void *buffer[100];
char **strings;
nptrs = backtrace(buffer, SIZE);
printf("backtrace() returned %d addresses\n", nptrs);
strings = backtrace_symbols(buffer, nptrs);
if (strings == NULL) {
perror("backtrace_symbols");
}
for (j = 0; j < nptrs; j++)
printf("%s\n", strings[j]);
free(strings);
}
void fun4(){
char ip;
char *fun = "fun4\0";
printf("Fun name %s\n",fun);
scanf("%c",&ip);
myfunc5();
}
void fun3(){
char *fun = "fun3\0";
printf("Fun name %s\n",fun);
funptr = fun4;
funptr();
}
void fun2(){
char *fun = "fun2\0";
printf("Fun name %s\n",fun);
fun3();
}
void fun1(){
char *fun = "fun1\0";
printf("Fun name %s\n",fun);
fun2();
}
main.c:-
int main(){
char ip;
funptr = &fun1;
scanf("%c",&ip);
funptr();
return 0;
}
</code></pre>
<p>Let me know if need more information...</p> | 0 | 1,718 |
composer update without dependencies | <p><a href="https://i.stack.imgur.com/PKlCN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PKlCN.png" alt="enter image description here"></a>I am using yii2 framework since last few weeks. But now I am getting some issues with composer itself.</p>
<p>Just for info, I am using ubuntu 14.04</p>
<p>When I require some new package / extensions, I do the composer add by using composer require command. But I noticed that sometimes it's removing few of the existing packages from my vendor and project.</p>
<p>I tried with following commands.</p>
<pre><code>composer require dmstr/yii2-adminlte-asset "*"
composer require 2amigos/yii2-file-upload-widget:~1.0
</code></pre>
<p>And also tried with some googling.</p>
<p><a href="http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/" rel="nofollow noreferrer">http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/</a></p>
<p>But it's not working.</p>
<p>Is there a way to add a new package / extension into your existing yii 2 project without removing existing packages or without any composer update command?</p>
<p><strong>Composer.json</strong></p>
<pre><code>{
"name": "sganz/yii2-advanced-api-template",
"description": "Improved Yii 2 Advanced Application Template By Sandy Ganz, Original by Nenad Zivkovic",
"keywords": ["yii2", "framework", "advanced", "improved", "application template", "nenad", "sganz"],
"type": "project",
"license": "BSD-3-Clause",
"support": {
"tutorial": "http://www.freetuts.org/tutorial/view?id=6",
"source": "https://github.com/sganz/yii2-advanced-api-template.git"
},
"minimum-stability": "dev",
"prefer-stable":true,
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "*",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "*",
"nenad/yii2-password-strength": "*",
"mihaildev/yii2-ckeditor": "*",
"dmstr/yii2-adminlte-asset": "*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
"yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"codeception/specify": "*",
"codeception/verify": "*"
},
"config": {
"vendor-dir": "protected/vendor",
"process-timeout": 1800
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "protected/vendor/npm",
"bower-asset-library": "protected/vendor/bower"
}
}
}
</code></pre>
<p>Any help on this would be greatly appreciated.</p> | 0 | 1,128 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.