Add 3.1.1 in to properties like below than fix issue
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
Just Update Project => right click => Maven=> Update Project
You need to set JDK 1.5 to your project and also all dependent project or jar file should also compiled with JDK 1.5
Worked by lowering the spring boot starter parent to 1.5.13
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
the problem is in url pattern of servlet-mapping.
<url-pattern>/DispatcherServlet</url-pattern>
let's say our controller is
@Controller
public class HomeController {
@RequestMapping("/home")
public String home(){
return "home";
}
}
when we hit some URL on our browser. the dispatcher servlet will try to map this url.
the url pattern of our serlvet currently is /Dispatcher
which means resources are served from {contextpath}/Dispatcher
but when we request http://localhost:8080/home
we are actually asking resources from /
which is not available.
so either we need to say dispatcher servlet to serve from /
by doing
<url-pattern>/</url-pattern>
our make it serve from /Dispatcher by doing /Dispatcher/*
E.g
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>springsecuritydemo</display-name>
<servlet>
<description></description>
<display-name>offers</display-name>
<servlet-name>offers</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>offers</servlet-name>
<url-pattern>/Dispatcher/*</url-pattern>
</servlet-mapping>
</web-app>
and request it with http://localhost:8080/Dispatcher/home
or put just /
to request like
http://localhost:8080/home
If you are running on a linux environment, basically your app does not have rights for the default port.
Try 8181 by giving the following option on VM.
-Dserver.port=8181
It looks like the problem is request to server is not a multi-part request. Basically you need to modify your client-side form. For example:
<form action="..." method="post" enctype="multipart/form-data">
<input type="file" name="file" />
</form>
Hope this helps.
I solved mine by updating spring dependencies versions from 2.0.4 to 2.1.6
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
to
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
You have to specify any one of the above phase to resolve the above error. In most of the situations, this would have occurred due to running the build from the eclipse environment.
instead of mvn clean package or mvn package you can try only package its work fine for me
fade's answer worked for me. I moved from 8.0.30 to 8.5.5 and the difference was the valve in <8.0.30>/manager/META-INF/context.xml was already commented out from the tar file but was uncommented in 8.5.5 tar.
I failed to read this important message in the 403 response:
By default the Manager is only accessible from a browser running on the same machine as Tomcat. If you wish to modify this restriction, you'll need to edit the Manager's context.xml file.
And failed to read this too:
Since r1734267 a RemoteAddrValve.is configured by default in Manager and HostManager web applications. This feature is present in 9.0.0.M4 and 8.5.0 onwards.
3 years already, but the same thing happened to me and I wanted to contribute with my case. Using the @nikk solution I got better results, but other errors still appeared, although yes, I was allowed to package.
However, my task was to implement the code of a co-worker on the server and it did not happen to him in his test environment, so I decided to investigate a little more since the code was functional and did not correspond to me touching anything .
In the end it turned out that his application inserted mysql tables into a database that did not exist. The solution was as easy as creating such a database and the error disappeared.
security.ignored is deprecated since Spring Boot 2.
For me simply extend the Annotation of your Application class did the Trick:
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
you are trying to inject the restTemplate but you need to create configuration class . then there you need to create bean that return you new RestTemplate see the below example.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class YourConfigClass {
@Bean
public RestTemplate restTesmplate() {
return new RestTemplate();
}
}
I have this problem when using STS. After edited something, I see that, some workspaces when create a project will happen this problem, and others will not. So I just create a new project in workspaces will not happen.
boardRepo.deleteByBoardId(id);
Faced the same issue. GOT javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread
I resolved it by adding @Transactional annotation above the controller/service.
SpringBoot developers recommend to locate your main application class in a root package above other classes. Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute. Detailed info But be sure that the custom root package exists.
As other people have commented, because the return type of your method is String
Spring won't feel need to do anything with the result.
If you change your signature so that the return type is something that needs marshalling, that should help:
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Map<String, Object> bar() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("test", "jsonRestExample");
return map;
}
The MySQL dependency should be like the following syntax in the pom.xml file.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
Make sure the syntax, groupId, artifactId, Version has included in the dependancy.
To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode
. The appropriate converter is automatically configured.
@PostMapping(value="/process")
public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
System.out.println(payload);
}
You forgot @Service annotation in your service class.
If you have config file transforms then ensure you have the correct config selected within your publish profile. (Publish > Settings > Configuration)
On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize
printed : uintx MaxHeapSize := 266338304
, which is approx 266MB and is 1/4th of my total RAM.
This link has solution of how to get it working. Removing "pom.xml" from the "Profiles:" line and then click "Run".
For an Ant project:
Make sure, you have servlet-api.jar in the lib
folder.
For a Maven project:
Make sure, you have the dependency added in POM.xml
.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Another way to do it is: Update the project facets to pick up the right server.
Check this box in this location:
Project ? Properties ? Target Runtimes ? Apache Tomcat (any server)
Put your css/js files in folder src/main/webapp/resources
. Don't put them in WEB-INF
or src/main/resources
.
Then add this line to spring-dispatcher-servlet.xml
<mvc:resources mapping="/resources/**" location="/resources/" />
Include css/js files in jsp pages
<link href="<c:url value="/resources/style.css" />" rel="stylesheet">
Don't forget to declare taglib in your jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Below should be in your pom.xml above other jersy/jackson dependencies. In my case it as below jersy-client dep-cy and i got MessageBodyWriter not found for media type=application/json.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
Add transaction-manager
to your <annotation-driven/>
in spring-servlet.xml:
<tx:annotation-driven transaction-manager="yourTransactionBeanID"/>
You seems to be missing implementation for interface UserDao. If you look at the exception closely it says
No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency:
The way @Autowired
works is that it would automatically look for implementation of a dependency you inject via an interface. In this case since there is no valid implementation of interface UserDao you get the error.Ensure you have a valid implementation for this class and your error should go.
Hope that helps.
Error message while running the code:
javax.persistence.TransactionRequiredException: Executing an update/delete query
Begin the entityManager transaction -> createNativeQuery -> execute update -> entityManager transaction commit to save it in your database. It is working fine for me with Hibernate and postgresql.
Code
entityManager.getTransaction().begin();
Query query = entityManager.createNativeQuery("UPDATE tunable_property SET tunable_property_value = :tunable_property_value WHERE tunable_property_name = :tunable_property_name");
query.setParameter("tunable_property_name", tunablePropertyEnum.eEnableJobManager.getName());
query.setParameter("tunable_property_value", tunable_property_value);
query.executeUpdate();
entityManager.getTransaction().commit();
I've just had the same problem on a CentOS 7 box.
Seems I'd hit selinux. Putting selinux into permissive mode (setenforce permissive
) has worked round the problem for now. I'll try and get back with a proper fix.
I am using Spring STS 3.8.3. I had a similar problem. I fixed it by using information from this thread And also by fixing some maven settings. click Spring Tool Suite -> Preferences -> Maven and uncheck the box that says "Do not automatically update dependencies from remote depositories" Also I checked the boxes that say "Download Artifact Sources" and "download Artifact javadoc".
Update nginx config /etc/nginx/sites-available/default or your config file
if you are using php7 use this
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
if you are using php5 use this
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
Visit here for complete detail Detail here
You need just to follow those steps:
After which, if the build fails when you do Maven Install, it means there is no web.xml file under WEB-INF or some problem associated with it. it really works
Also, after you've updated your repository ids, make sure you run clean as release:prepare
will pick up where it left off. So you can do:
mvn release:prepare -Dresume=false
or
mvn release:clean release:prepare
Here is a simple solution
try adding this dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
For me, adding the following block of code under <dependency management><dependencies>
solved the problem.
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b06</version>
</dependency>
Had this issue when migrated spring boot 1.5.2 to 2.0.4.
Instead of creating bean I've used @EnableAutoConfiguration
in the main class and it solved my problem.
org.springframework.core.io.Resource
is part of spring-core-<version>.jar
But this lib is already in your lib folder. So I guess it is just a Deployment Problem. -- Try to clean your server and redeploy your application.
I faced this exception while I was doing APIs for ElasticSearch using Spring Data. I did the following and it worked.
@SpringDataApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
Correct way to exclude default logging, and configure log4j for logging.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
Refer Spring Logging - How To.
In gradle, I needed to do this with several other dependencies:
configurations {
all*.exclude module : 'spring-boot-starter-logging'
all*.exclude module : 'logback-classic'
}
Copied from the stacktrace:
BeanInstantiationException: Could not instantiate bean class [com.gestEtu.project.model.dao.CompteDAOHib]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.gestEtu.project.model.dao.CompteDAOHib.<init>()
By default, Spring will try to instantiate beans by calling a default (no-arg) constructor. The problem in your case is that the implementation of the CompteDAOHib
has a constructor with a SessionFactory
argument. By adding the @Autowired
annotation to a constructor, Spring will attempt to find a bean of matching type, SessionFactory
in your case, and provide it as a constructor argument, e.g.
@Autowired
public CompteDAOHib(SessionFactory sessionFactory) {
// ...
}
Override service method like this:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
And Voila!
You are missing spring-security-web-3.1.X.RELEASE.jar
from your classpath
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
It's an eclipse setup issue, not a Jersey issue.
From this thread ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
Right click your eclipse project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Gradle Dependencies -> Finish.
So Eclipse wasn't using the Gradle dependencies when Apache was starting .
I had same issue while creating new spring project in eclipse using Maven.
The main reason for this issue is that the proxy settings was not there.
I used the following approach to reslove it:
1) create settings.xml with the below content
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>Your proxy</host>
<port>Your port</port>
</proxy>
</proxies>
<profiles/>
<activeProfiles/>
</settings>
2) Save the settings.xml file under local C:\Users\<<your user account>>\.m2
3) Then Right click project pom.XML in eclipse and select "Update Project". It always give precedence to settings.XML
Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;
Also this looks wierd to me :
@ContextConfiguration("classpath*:conf/components.xml")
Here is an example that works fine for me :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {
@Autowired
OwnerService ownerService;
@Before
public void setup() {
ownerService.cleanList();
}
@Test
public void testOwners() {
Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
owner = ownerService.createOwner(owner);
assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
assertTrue("Check that Id exist: ", owner.getId() > 0);
owner.setLastName("Larsson");
ownerService.updateOwner(owner);
owner = ownerService.getOwner(owner.getId());
assertEquals("Name is changed", "Larsson", owner.getLastName());
}
Check that doPost()
method of servlet is called from the jsp form and remove conn.commit
.
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
Adding below to pom.xml solved my problem
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
Using IntelliJ, I got this error when I tried to run a Spring app while there was one app already running. I had to stop the first one. After that, running the second app didn't return any errors.
One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.12</version>
</dependency>
Since your server already includes the sites-enabled
folder ( notice the include /etc/nginx/sites-enabled/*
line ), then you better use that.
Create a file inside /etc/nginx/sites-available
and call it whatever you want, I'll call it django
since it's a djanog server
sudo touch /etc/nginx/sites-available/django
Then create a symlink that points to it
sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
Then edit that file with whatever file editor you use, vim
or nano
or whatever and create the server inside it
server {
# hostname or ip or multiple separated by spaces
server_name localhost example.com 192.168.1.1; #change to your setting
location / {
root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
}
}
Restart or reload nginx settings
sudo service nginx reload
Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server
Correct way shall be to autowire AbstractManager, as Max suggested, but this should work fine as well.
@Autowired
@Qualifier(value="mailService")
public MailManager mailManager;
and
@Component("mailService")
@Transactional
public class MailManager extends AbstractManager {
}
My solution was to add a space between the $ and the {.
For example:
@Value("${project.ftp.adresse}")
becomes
@Value("$ {project.ftp.adresse}")
Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.
Try installing the required verison.
If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.
also remove the lines
<fork>true</fork>
<executable>${JAVA_1_7_HOME}/bin/javac</executable>
from the pom.xml
This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.
I did the following :
I would not build or clean build it. Hope that helps you out.
The error message which you specified is nothing but you are not specifying goal for maven build.
you can specify any goal in your run configuration for maven build like clear, compile, install, package.
please following below step to resolve it.
<form onsubmit="myFunction(event)">
Name : <input type="text"/>
<input class="submit" type="submit">
</form>
<script>
function myFunction(event){
event.preventDefault();
//code here
}
</script>
Add one more slash after file://
in the value of xsi:schemaLocation
. (You have two; you need three. Think protocol://host/path
where protocol
is 'file'
and host
is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path
. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.
xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"
Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:
file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd
If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.
If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.
Most likely, you ran out of memory, so the Kernel killed your process.
Have you heard about OOM Killer?
Here's a log from a script that I developed for processing a huge set of data from CSV files:
Mar 12 18:20:38 server.com kernel: [63802.396693] Out of memory: Kill process 12216 (python3) score 915 or sacrifice child
Mar 12 18:20:38 server.com kernel: [63802.402542] Killed process 12216 (python3) total-vm:9695784kB, anon-rss:7623168kB, file-rss:4kB, shmem-rss:0kB
Mar 12 18:20:38 server.com kernel: [63803.002121] oom_reaper: reaped process 12216 (python3), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB
It was taken from /var/log/syslog
.
Basically:
PID 12216 elected as a victim (due to its use of +9Gb of total-vm), so oom_killer reaped it.
Here's a article about OOM behavior.
@Produces({"text/plain","application/xml","application/json"})
change this to @Produces("text/plain")
and try,
Faced the same issue and resolved by upgrading my Maven from 3.0.4 to 3.1.1. Please try with v3.1.1 or any higher version if available
To generate classes from WSDL, all you need is build-helper-maven-plugin and jaxws-maven-plugin in your pom.xml
Make sure you have placed wsdl under folder src/main/resources/wsdl and corresponding schema in src/main/resources/schema, run command "mvn generate-sources" from Project root directory.
C:/Project root directory > mvn generate-sources
generated java classes can be located under folder
target/generated/src/main/java/com/raps/code/generate/ws.
pom.xml snippet
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.9</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals><goal>add-source</goal></goals>
<configuration>
<sources>
<source>${project.build.directory}/generated/src/main/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>1.12</version>
<configuration>
<wsdlDirectory>${project.basedir}/src/main/resources/wsdl</wsdlDirectory>
<packageName>com.raps.code.generate.ws</packageName>
<keep>true</keep>
<sourceDestDir>${project.build.directory}/generated/src/main/java</sourceDestDir>
</configuration>
<executions>
<execution>
<id>myImport</id>
<goals><goal>wsimport</goal></goals>
</execution>
</executions>
</plugin>
HTML Code
<html>
<body>
<head>
<title></title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
//============================= DATABASE CONNECTIVITY d ====================
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
//============================= DATABASE CONNECTIVITY u ====================
//============================= Retrieve data from DB d ====================
$sql = "SELECT name, size, type FROM videos";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
$path = "uploaded/" . $row["name"];
echo $path . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
//============================= Retrieve data from DB d ====================
?>
</body>
</html>
you need to add jersey-bundle-1.17.1.jar
to lib of project
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<!-- <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> -->
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<!-- <param-name>jersey.config.server.provider.packages</param-name> -->
<param-value>package.package.test</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.
I use this
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2</version>
</plugin>
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}
or you could wrap in foreach loop to print each value
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
foreach(XmlNode curr in n) {
Console.WriteLine(curr.InnerText);
}
}
Sometimes this issue comes because the java.version which you have mentioned in POM.xml is not the one installed in your machine.
<properties>
<java.version>1.7</java.version>
</properties>
Ensure you exactly mention the same version in your pom.xml as the jdk and jre version present in your machine.
You don't need both hibernate.cfg.xml
and persistence.xml
in this case. Have you tried removing hibernate.cfg.xml
and mapping everything in persistence.xml
only?
But as the other answer also pointed out, this is not okay like this:
@Id
@JoinColumn(name = "categoria")
private String id;
Didn't you want to use @Column
instead?
ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib
Generally you don't want to value only the source
version (javac -source 1.8
for example) but you want to value both the source
and the target
version (javac -source 1.8 -target 1.8
for example).
Note that from Java 9, you have a way to convey both information and in a more robust way for cross-compilation compatibility (javac -release 9
).
Maven that wraps the javac
command provides multiple ways to convey all these JVM standard options.
Using maven-compiler-plugin
or maven.compiler.source
/maven.compiler.target
properties to specify the source
and the target
are equivalent.
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
and
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
are equivalent according to the Maven documentation of the compiler plugin
since the <source>
and the <target>
elements in the compiler configuration use the properties maven.compiler.source
and maven.compiler.target
if they are defined.
The
-source
argument for the Java compiler.
Default value is:1.6
.
User property is:maven.compiler.source
.
The
-target
argument for the Java compiler.
Default value is:1.6
.
User property is:maven.compiler.target
.
About the default values for source
and target
, note that
since the 3.8.0
of the maven compiler, the default values have changed from 1.5
to 1.6
.
<release>
tag — new way to specify Java version in maven-compiler-plugin
3.6You can use the release
argument :
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>9</release>
</configuration>
</plugin>
You could also declare just the user property maven.compiler.release
:
<properties>
<maven.compiler.release>9</maven.compiler.release>
</properties>
But at this time the last one will not be enough as the maven-compiler-plugin
default version you use doesn't rely on a recent enough version.
The Maven release
argument conveys release
to the Java compiler to access the JVM standard option newly added to Java 9, JEP 247: Compile for Older Platform Versions.
Compiles against the public, supported and documented API for a specific VM version.
This way provides a standard way to specify the same version for the source
, the target
and the bootstrap
JVM options.
Note that specifying the bootstrap
is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.
Neither maven.compiler.source
/maven.compiler.target
properties or using the maven-compiler-plugin
is better.
It changes nothing in the facts since finally the two ways rely on the same properties and the same mechanism : the maven core compiler plugin.
Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
The release
argument (third point) is a way to strongly consider if you want to use the same version for the source
and the target
.
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
That should be the problem. JSON is served as application/json
. If you set the Accept header accordingly, you should get the proper response. (There are browser plugins that let you set headers, I like "Poster" for Firefox best)
I got here with a similar problem with my Gradle build and fixed it in a similar way:
Unable to load class hudson.model.User due to missing dependency javax/servlet/ServletException
fixed with:
dependencies {
implementation('javax.servlet:javax.servlet-api:3.0.1')
}
The servlet class should be in the WEB-INF/classes not WEB-INF/src.
Thanks to everyone above, but this is now fixed. For the benefit of others the most significant error was in aligning the three namespaces as suggested by Ian.
For completeness, here is the corrected XML and XSD
Here is the XML, with the typos corrected (sorry for any confusion caused by tardiness)
<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="urn:Test.Namespace"
xsi:schemaLocation="urn:Test.Namespace Test1.xsd">
<element1 id="001">
<element2 id="001.1">
<element3 id="001.1" />
</element2>
</element1>
</Root>
and, here is the Schema
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:Test.Namespace"
xmlns="urn:Test.Namespace"
elementFormDefault="qualified">
<xsd:element name="Root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="element1" maxOccurs="unbounded" type="element1Type"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="element1Type">
<xsd:sequence>
<xsd:element name="element2" maxOccurs="unbounded" type="element2Type"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="element2Type">
<xsd:sequence>
<xsd:element name="element3" type="element3Type"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="element3Type">
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>
Thanks again to everyone, I hope this is of use to somebody else in the future.
There is similar issue. I added listener as given here
https://stackoverflow.com/questions/3145936/spring-security-j-spring-security-logout-problem
It worked for me adding below lines to web.xml. Posting it very late, should help someone looking for answer.
<listener>
<listener-class> org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
If none of the above works then try and go this question and answer: Maven error "Failure to transfer..."
and delete your .lastUpdated
files.
First off, you have to specify you wish to use Document Literal style:
$client = new SoapClient(NULL, array(
'location' => 'https://example.com/path/to/service',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL)
);
Then, you need to transform your data into a SoapVar; I've written a simple transform function:
function soapify(array $data)
{
foreach ($data as &$value) {
if (is_array($value)) {
$value = soapify($value);
}
}
return new SoapVar($data, SOAP_ENC_OBJECT);
}
Then, you apply this transform function onto your data:
$data = soapify(array(
'Acquirer' => array(
'Id' => 'MyId',
'UserId' => 'MyUserId',
'Password' => 'MyPassword',
),
));
Finally, you call the service passing the Data parameter:
$method = 'Echo';
$result = $client->$method(new SoapParam($data, 'Data'));
I have encountered this with Maven projects too. This is what I had to do to get around the problem:
First update your web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Servlet 3.0 Web Application</display-name>
Then right click on your project and select Properties -> Project Facets In there you will see the version of your Dynamic Web Module. This needs to change from version 2.3 or whatever to version 2.5 or above (I chose 3.0).
However to do this I had to uncheck the tick box for Dynamic Web Module -> Apply, then do a Maven Update on the project. Go back into the Project Facets window and it should already match your web.xml configuration - 3.0 in my case. You should be able to change it if not.
If this does not work for you then try right-clicking on the Dynamic Web Module Facet and select change version (and ensure it is not locked).
Or you can follow this steps:
don't forget to update your project
Hope that works!
You map your dispatcher on *.do:
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
but your controller is mapped on an url without .do:
@RequestMapping("/editPresPage")
Try changing this to:
@RequestMapping("/editPresPage.do")
Quote from the Spring reference doc:
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there...
Your servlet is called spring-dispatcher
, so it looks for /WEB-INF/spring-dispatcher-servlet.xml
. You need to have this servlet configuration, and define web related beans in there (like controllers, view resolvers, etc). See the linked documentation for clarification on the relation of servlet contexts to the global application context (which is the app-config.xml
in your case).
One more thing, if you don't like the naming convention of the servlet config xml, you can specify your config explicitly:
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
You have to decompose the full object to reach the entry
array.
Assuming REPONSE_JSON_OBJECT
is already a parsed JSONObject
.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
For Controllers, @SpringBootApplication(scanBasePackages = {"com.school.controllers"})
For Respositories, @EnableJpaRepositories(basePackages = {"com.school.repos"})
For Entities, @EntityScan(basePackages = {"com.school.models"})
This will slove
"Can't Autowire @Repository annotated interface"
problem as well as
Not an managed Type
problem. Sample configuration below
package com.school.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication(scanBasePackages = {"com.school.controllers"})
@EnableJpaRepositories(basePackages = {"com.school.repos"})
@EntityScan(basePackages = {"com.school.models"})
public class SchoolApplication {
public static void main(String[] args) {
SpringApplication.run(SchoolApplication.class, args);
}
}
I had a similar issue using the JAXB reference implementation and JBoss AS 7.1. I was able to write an integration test that confirmed JAXB worked outside of the JBoss environment (suggesting the problem might be the class loader in JBoss).
This is the code that was giving the error (i.e. not working):
private static final JAXBContext JC;
static {
try {
JC = JAXBContext.newInstance("org.foo.bar");
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
and this is the code that worked (ValueSet is one of the classes marshaled from my XML).
private static final JAXBContext JC;
static {
try {
ClassLoader classLoader = ValueSet.class.getClassLoader();
JC = JAXBContext.newInstance("org.foo.bar", classLoader);
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
In some cases I got the Class nor any of its super class is known to this context. In other cases I also got an exception of org.foo.bar.ValueSet cannot be cast to org.foo.bar.ValueSet (similar to the issue described here: ClassCastException when casting to the same class).
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
For me the problem was my file encoding...I used powershell to write the xml file and this was not UTF-8 ... It seems that spring requires UTF8 because as soon as I changed the encoding (using notepad++) it works again without any errors
Now i Use in my powershellscript the following line to output the xml file in UTF-8: [IO.File]::WriteAllLines($fname_dataloader_xml_config_file, $dataloader_configfile)
instead of using the redirection operator > to create my file
Note: I didn't put any xml parameters in my beans tag and it works
I recently had same issue with Spring 4.0.
It was caused by a collision in names from spring-beans-4.0.xsd
and spring-context-4.0.xsd
.
Opening spring-context-4.0.xsd
you can see that spring-beans-4.0.xsd
is imported like follow:
<xsd:import namespace="http://www.springframework.org/schema/beans"
schemaLocation="http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"/>
These name's collisions make Eclipse complain about "...A schema cannot contain two global components with the same name..."
A noteworthy aspect is that I hadn't this problem with Eclipse Kepler SR2 but Eclipse Luna SR1, comparing both preferences about XML Validation, they were the same.
It was solved by removing spring-context-4.0.xsd from xsi:schemaLocation attribute:
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
After this everything worked as expected.
<context:component-scan base-package="" />
tells Spring to scan those packages for Annotations.
<mvc:annotation-driven>
registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.
This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.
You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.
Check out the 3.1 documentation to learn more.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config
This path of the schema location is wrong:
http://www.springframework.org/schema/beans
The correct path should end with /
:
http://www.springframework.org/schema/beans/
I had the same issue. Fixed by adding a pom.xml in parent folder with <modules>
listed.
For me changing the Jenkins version helped.
<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>1.642.4</version><!-- which version of Jenkins is this plugin built against? -->
</parent>
In my case, the reason was a simple typo.
<parent>
<groupId>org.sringframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
A missing character in the groupId
org.s(p)ringframework lead to this error.
This is my aproximation:
Declare
Variableclob Clob;
Temp_Save Varchar2(32767); //whether it is greater than 4000
Begin
Select reportClob Into Temp_Save From Reporte Where Id=...;
Variableclob:=To_Clob(Temp_Save);
Dbms_Output.Put_Line(Variableclob);
End;
Since version 1.6 we have new annotation JsonSerialize (in version 1.9.9 for example).
Example:
@JsonSerialize(include=Inclusion.NON_NULL)
public class Test{
...
}
Default value is ALWAYS.
In old versions you can use JsonWriteNullProperties, which is deprecated in new versions. Example:
@JsonWriteNullProperties(false)
public class Test{
...
}
Well there's a problem with the creation of the ContactServiceImpl
bean. First, make sure that the class is actually instantiated by debugging the no-args constructor when the Spring context is initiated and when an instance of ContactController
is created.
If the ContactServiceImpl
is actually instantiated by the Spring context, but it's simply not matched against your @Autowire
annotation, try being more explicit in your annotation injection. Here's a guy dealing with a similar problem as yours and giving some possible solutions:
http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/
If you ask me, I think you'll be ok if you replace
@Autowired
private ContactService contactService;
with:
@Resource
@Qualifier("contactService")
private ContactService contactService;
Add bean declaration in bean.xml file or in any other configuration file . It will resolve the error
<bean class="com.demo.dao.RailwayDao"></bean>
<bean class="com.demo.service.RailwayService"></bean>
<bean class="com.demo.model.RailwayReservation"></bean>
As these answers are old, I found this alternative. It is very clean and works with just java annotations:
To fix it, create a “none static setter” to assign the injected value for the static variable. For example :
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/
This solves the problem for me. It's easy and pretty simply explained.
Step 1
Step 2
Step 3
Step 4
Step 5
when I try to run it, I get NoClassDefFoundError
Run it how? You're probably trying to run it with eclipse without having correctly imported your maven classpath. See the m2eclipse plugin for integrating maven with eclipse for that.
To verify that your maven config is correct, you could run your app with the exec plugin using:
mvn exec:java -D exec.mainClass=<your main class>
Update: First, regarding your error when running exec:java
, your main class is tr.edu.hacettepe.cs.b21127113.bil138_4.App
. When talking about class names, they're (almost) always dot-separated. The simple class name is just the last part: App
in your case. The fully-qualified name is the full package plus the simple class name, and that's what you give to maven or java when you want to run something. What you were trying to use was a file system path to a source file. That's an entirely different beast. A class name generally translates directly to a class file that's found in the class path, as compared to a source file in the file system. In your specific case, the class file in question would probably be at target/classes/tr/edu/hacettepe/cs/b21127113/bil138_4/App.class
because maven compiles to target/classes
, and java traditionally creates a directory for each level of packaging.
Your original problem is simply that you haven't put the Jackson jars on your class path. When you run a java program from the command line, you have to set the class path to let it know where it can load classes from. You've added your own jar, but not the other required ones. Your comment makes me think you don't understand how to manually build a class path. In short, the class path can have two things: directories containing class files and jars containing class files. Directories containing jars won't work. For more details on building a class path, see "Setting the class path" and the java and javac tool documentation.
Your class path would need to be at least, and without the line feeds:
target/bil138_4-0.0.1-SNAPSHOT.jar:
/home/utdemir/.m2/repository/org/codehaus/jackson/jackson-core-asl/1.9.6/jackson-core-asl-1.9.6.jar:
/home/utdemir/.m2/repository/org/codehaus/jackson/jackson-mapper-asl/1.9.6/jackson-mapper-asl-1.9.6.jar
Note that the separator on Windows is a semicolon (;).
I apologize for not noticing it sooner. The problem was sitting there in your original post, but I missed it.
Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
This is what i have been facing for long time.
This happened last time and figured out that one case could be a bad war deployment, which came after i update library/maven dependencies on pom and re installed it.
SOLUTION:
right click on the server > remove the war and
right click on the server again > clean
make sure the maven dependencies are added to deployment assembly
right click on the project > Run As > maven clean
right click on the project again > Run As > maven install
and finally deploy the project on to the server. This helped me to solve the issue
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
Actually, I solved the problem. I run it by eclipse jetty plugin.
I didn't have the JDK lib in my eclipse, that's why the message keep showing that I need the full JDK installed, that's the main reason.
I installed two versions of jetty plugin, wich is jetty7 and jetty8. I think they conflict with each other or something, so I removed the jetty7, and it works!
1: Add the following line into the AssemblyInfo class
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
2: Make sure you don't use .Net Framework 4 Client Profile
as Target Framework
(I think this is OK on your side because otherwise it even wouldn't compile)
3: Make sure you log very early in your program. Otherwise, in some scenarios, it will not be initialized properly (read more on log4net FAQ).
So log something during application startup in the Global.asax
public class Global : System.Web.HttpApplication
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Global));
protected void Application_Start(object sender, EventArgs e)
{
Log.Info("Startup application.");
}
}
4: Make sure you have permission to create files and folders on the given path (if the folder itself also doesn't exist)
5: The rest of your given information looks ok
# create uniform spiral grid
numOfPoints = varargin[0]
vxyz = zeros((numOfPoints,3),dtype=float)
sq0 = 0.00033333333**2
sq2 = 0.9999998**2
sumsq = 2*sq0 + sq2
vxyz[numOfPoints -1] = array([(sqrt(sq0/sumsq)),
(sqrt(sq0/sumsq)),
(-sqrt(sq2/sumsq))])
vxyz[0] = -vxyz[numOfPoints -1]
phi2 = sqrt(5)*0.5 + 2.5
rootCnt = sqrt(numOfPoints)
prevLongitude = 0
for index in arange(1, (numOfPoints -1), 1, dtype=float):
zInc = (2*index)/(numOfPoints) -1
radius = sqrt(1-zInc**2)
longitude = phi2/(rootCnt*radius)
longitude = longitude + prevLongitude
while (longitude > 2*pi):
longitude = longitude - 2*pi
prevLongitude = longitude
if (longitude > pi):
longitude = longitude - 2*pi
latitude = arccos(zInc) - pi/2
vxyz[index] = array([ (cos(latitude) * cos(longitude)) ,
(cos(latitude) * sin(longitude)),
sin(latitude)])
You can automatically HTML encode field in custom Model Binder. My solution some different, I put error in ModelState and display error message near the field. It`s easy to modify this code for automatically encode
public class AppModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
try
{
return base.CreateModel(controllerContext, bindingContext, modelType);
}
catch (HttpRequestValidationException e)
{
HandleHttpRequestValidationException(bindingContext, e);
return null; // Encode here
}
}
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,
PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
{
try
{
return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
}
catch (HttpRequestValidationException e)
{
HandleHttpRequestValidationException(bindingContext, e);
return null; // Encode here
}
}
protected void HandleHttpRequestValidationException(ModelBindingContext bindingContext, HttpRequestValidationException ex)
{
var valueProviderCollection = bindingContext.ValueProvider as ValueProviderCollection;
if (valueProviderCollection != null)
{
ValueProviderResult valueProviderResult = valueProviderCollection.GetValue(bindingContext.ModelName, skipValidation: true);
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
}
string errorMessage = string.Format(CultureInfo.CurrentCulture, "{0} contains invalid symbols: <, &",
bindingContext.ModelMetadata.DisplayName);
bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);
}
}
In Application_Start:
ModelBinders.Binders.DefaultBinder = new AppModelBinder();
Note that it works only for form fields. Dangerous value not passed to controller model, but stored in ModelState and can be redisplayed on form with error message.
Dangerous chars in URL may be handled this way:
private void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
HttpContext httpContext = HttpContext.Current;
HttpException httpException = exception as HttpException;
if (httpException != null)
{
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
var httpCode = httpException.GetHttpCode();
switch (httpCode)
{
case (int)HttpStatusCode.BadRequest /* 400 */:
if (httpException.Message.Contains("Request.Path"))
{
httpContext.Response.Clear();
RequestContext requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
requestContext.RouteData.Values["action"] ="InvalidUrl";
requestContext.RouteData.Values["controller"] ="Error";
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(requestContext, "Error");
controller.Execute(requestContext);
httpContext.Server.ClearError();
Response.StatusCode = (int)HttpStatusCode.BadRequest /* 400 */;
}
break;
}
}
}
ErrorController:
public class ErrorController : Controller
{
public ActionResult InvalidUrl()
{
return View();
}
}
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
I had a similar case for the default groovy compiler plugin
The solution was to install ME2 provided by Springsource according to this answer
Plugin execution not covered by lifecycle configuration maven error
This immediately solved the "Plugin execution not covered by lifecycle configuration" problem in Eclispe Juno.
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>
The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .
When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'
You could do the following
Remove @Component from your Service and depend on mapping via XML - Easiest
Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.
Use @Resource instead of @Autowired to pick the bean by its name .
@Resource(name="suggestionService")
private SuggestionService service;
or
@Resource(name="SuggestionService")
private SuggestionService service;
both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.
You should use LoadXml method, not Load:
xmlDoc.LoadXml(myXML);
Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
}
Problem is system is not able to find the file tools.jar
So first check that the file is there in the JDK installation of the directory.
Make the below entry in POM.xml as rightly pointed by others
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.8.0_241\lib\tools.jar</systemPath>
</dependency>
then Follow the below steps also to remove the problem
1) Right Click on your project
2) Click on Build path
As per the below image, select the workspace default JRE and click on finish.
JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:
"SELECT r FROM FooBar r"
<form class="upload-form">
<input class="upload-file" data-max-size="2048" type="file" >
<input type=submit>
</form>
<script>
$(function(){
var fileInput = $('.upload-file');
var maxSize = fileInput.data('max-size');
$('.upload-form').submit(function(e){
if(fileInput.get(0).files.length){
var fileSize = fileInput.get(0).files[0].size; // in bytes
if(fileSize>maxSize){
alert('file size is more then' + maxSize + ' bytes');
return false;
}else{
alert('file size is correct- '+fileSize+' bytes');
}
}else{
alert('choose file, please');
return false;
}
});
});
</script>
As my experience, you can add another domain which listens different port than 7001, and use this domain in to deploy app.
Here's an example: http://st-curriculum.oracle.com/obe/fmw/wls/10g/r3/installconfig/install_wls/install_wls.htm
HTH.
public class Organization {
@Id
@Column(name="org_id")
@GeneratedValue
private int id;
@Column(name="org_name")
private String name;
@Column(name="org_office_address1")
private String address1;
@Column(name="org_office_addres2")
private String address2;
@Column(name="city")
private String city;
@Column(name="state")
private String state;
@Column(name="country")
private String country;
@JsonIgnore
@OneToOne
@JoinColumn(name="pkg_id")
private int pkgId;
public int getPkgId() {
return pkgId;
}
public void setPkgId(int pkgId) {
this.pkgId = pkgId;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="pincode")
private String pincode;
@OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);
@Column(name="status")
private String status = "ACTIVE";
@Column(name="project_id")
private int redmineProjectId;
public int getRedmineProjectId() {
return redmineProjectId;
}
public void setRedmineProjectId(int redmineProjectId) {
this.redmineProjectId = redmineProjectId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set<OrganizationBranch> getOrganizationBranch() {
return organizationBranch;
}
public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
this.organizationBranch = organizationBranch;
}
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 String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired
To configure a message converter in plain spring-web, in this case to enable the Java 8 JSR-310 JavaTimeModule, you first need to implement WebMvcConfigurer
in your @Configuration
class and then override the configureMessageConverters
method:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(new JavaTimeModule(), new Jdk8Module()).build()
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}
Like this you can register any custom defined ObjectMapper
in a Java-based Spring configuration.
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxy.somewhere.com</host>
<port>8080</port>
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
</proxy>
</proxies>
</settings>
Window > Preferences > Maven > User Settings
In my case, this was caused by custom manifest entries added by the maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<git>${buildNumber}</git>
<build-time>${timestamp}</build-time>
</manifestEntries>
</archive>
</configuration>
</plugin>
Removing the following entries fixed the problem
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
easiest way to append class name using javascript.
It can be useful when .siblings()
are misbehaving.
document.getElementById('myId').className += ' active';
JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.
What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");
Here is IBM's reference page.
If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
Some context additional about basic authentication, it consists in a header which contains the key/value pair:
Authorization: Basic Z2VybWFuOmdlcm1hbg==
where "Authorization" is the headers key, and the headers value has a string ( "Basic" word plus blank space) concatenated to "Z2VybWFuOmdlcm1hbg==", which are the user and password in base 64 joint by double dot
String name = "username";
String password = "secret";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
...
objectXXX.header("Authorization", "Basic " + authStringEnc);
According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource
, as per this line:
java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource
class in it.
You need to configure class ModeleREP
as well with @XmlAccessorType(XmlAccessType.FIELD)
as you did with class TimeSeries
.
Have al look at OOXS
Besides changing it to Console (/SUBSYSTEM:CONSOLE)
as others have said, you may need to change the entry point in Properties -> Linker -> Advanced -> Entry Point. Set it to mainCRTStartup.
It seems that Visual Studio might be searching for the WinMain function instead of main, if you don't specify otherwise.
It's really simple. It's a new feature introduced in J2SE 5. Specifying angular brackets after the class name means you are creating a temporary data type which can hold any type of data.
Example:
class A<T>{
T obj;
void add(T obj){
this.obj=obj;
}
T get(){
return obj;
}
}
public class generics {
static<E> void print(E[] elements){
for(E element:elements){
System.out.println(element);
}
}
public static void main(String[] args) {
A<String> obj=new A<String>();
A<Integer> obj1=new A<Integer>();
obj.add("hello");
obj1.add(6);
System.out.println(obj.get());
System.out.println(obj1.get());
Integer[] arr={1,3,5,7};
print(arr);
}
}
Instead of <T>
, you can actually write anything and it will work the same way. Try writing <ABC>
in place of <T>
.
This is just for convenience:
<T>
is referred to as any type<E>
as element type<N>
as number type<V>
as value<K>
as keyBut you can name it anything you want, it doesn't really matter.
Moreover, Integer
, String
, Boolean
etc are wrapper classes of Java which help in checking of types during compilation. For example, in the above code, obj
is of type String
, so you can't add any other type to it (try obj.add(1)
, it will cast an error). Similarly, obj1
is of the Integer
type, you can't add any other type to it (try obj1.add("hello")
, error will be there).
Just like you do for getting something from the CNode
you also need to do for the ANode
XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
XmlNode anode = xn.SelectSingleNode("ANode");
if (anode!= null)
{
string id = anode["ID"].InnerText;
string date = anode["Date"].InnerText;
XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
foreach (XmlNode node in CNodes)
{
XmlNode example = node.SelectSingleNode("Example");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
}
}
TL;DR To fix this issue, invoke packaging plugin before, e.g. for jar
packaging use maven-jar-plugin
, as following:
mvn jar:jar install:install
Or
mvn jar:jar deploy:deploy
If you actually needed to deploy.
Gotcha This approach won't work if you have multi-module project with different packagings (ear/war/jar/zip) – even worse, wrong artifacts will be installed/deployed! In such case use reactor options to only build the deployable module (e.g. the war
).
Explanation
In some cases you actually want to run directly a install:install
or deploy:deploy
goal (that is, from the maven-deploy-plugin
, the deploy
goal, not the Maven deploy
phase) and you would end up in the annoying The packaging for this project did not assign a file to the build artifact
.
A classic example is a CI job (a Jenkins or Bamboo job, e.g.) where in different steps you want to execute/care about different aspects:
mvn clean install
, performing tests and test coveragemvn sonar:sonar
plus further optionsmvn deploy
, because it would again execute previous phases (and compile, test, etc.) and you want your build to be effective but yet fast.Yes, you could speed up this last step at least skipping tests (compilation and execution, via -Dmaven.test.skip=true
) or play with a particular profile (to skip as many plugins as possible), but it is much easier and clear to simply run mvn deploy:deploy
then.
But it would fail with the error above, because as also specified by the plugin FAQ:
During the packaging-phase all gathered and placed in context. With this mechanism Maven can ensure that the
maven-install-plugin
andmaven-deploy-plugin
are copying/uploading the same set of files. So when you only executedeploy:deploy
, then there are no files put in the context and there is nothing to deploy.
Indeed, the deploy:deploy
needs some runtime information placed in the build context by previous phases (or previous plugins/goals executions).
It has also reported as a potential bug: MDEPLOY-158
: deploy:deploy does not work for only Deploying artifact to Maven Remote repo
But then rejected as not a problem.
The deployAtEnd
configuration option of the maven-deploy-plugin
won't help neither in certain scenarios because we have intermediate job steps to execute:
Whether every project should be deployed during its own deploy-phase or at the end of the multimodule build. If set to
true
and the build fails, none of the reactor projects is deployed. (experimental)
So, how to fix it?
Simply run the following in such a similar third/last step:
mvn jar:jar deploy:deploy
The maven-jar-plugin
will not re-create any jar as part of your build, thanks to its forceCreation
option set to false
by default:
Require the jar plugin to build a new JAR even if none of the contents appear to have changed. By default, this plugin looks to see if the output jar exists and inputs have not changed. If these conditions are true, the plugin skips creation of the jar.
But it will nicely populate the build context for us and make deploy:deploy
happy. No tests to skip, no profiles to add. Just what you need: speed.
Additional note: if you are using the build-helper-maven-plugin
, buildnumber-maven-plugin
or any other similar plugin to generate meta-data later on used by the maven-jar-plugin
(e.g. entries for the Manifest file), you most probably have executions linked to the validate
phase and you still want to have them during the jar:jar
build step (and yet keep a fast execution). In this case the almost harmless overhead is to invoke the validate
phase as following:
mvn validate jar:jar deploy:deploy
Yet another additional note: if you have not jar
but, say, war
packaging, use war:war
before install/deploy instead.
Gotcha as pointed out above, check behavior in multi module projects.
Another thing that can cause Maven to not find the tests if if the module's packaging is not declared correctly.
In a recent case, someone had <packaging>pom</packaging>
and my tests never ran. I changed it to <packaging>jar</packaging>
and now it works fine.
I'm learning from udemy. I followed every step that my instructor show me to do. In spring mvc crud section while setting up the devlopment environment i had the same error for:
<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" />
then i just replaced
http://www.springframework.org/schema/mvc/spring-mvc.xsd
with
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
and
http://www.springframework.org/schema/tx/spring-tx.xsd
with
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
actually i visited these two sites http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/ and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd and spring-tx-4.2.xsd
So, i suggest to try this. Hope this helps. Thank you.
In Visual Studio 2019 WinForm Projects, it is available under
Project Properties -> Application -> View Windows Settings (button)
For me, this was something as simple as a missing version for my artifact - "1.1-SNAPSHOT"
An xmlns
is a unique identifier within the document - it doesn't have to be a URI to the schema:
XML namespaces provide a simple method for qualifying element and attribute names used in Extensible Markup Language documents by associating them with namespaces identified by URI references.
xsi:schemaLocation
is supposed to give a hint as to the actual schema location:
can be used in a document to provide hints as to the physical location of schema documents which may be used for assessment.
you can specify fields like this:
LOAD XML LOCAL INFILE '/pathtofile/file.xml'
INTO TABLE my_tablename(personal_number, firstname, ...);
The urls are different.
http://localhost/AccountSvc/DataInquiry.asmx
vs.
/acctinqsvc/portfolioinquiry.asmx
Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.
You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx
, and specify the desired method/operation in the SOAPAction header.
The SOAPAction header values are different.
http://localhost/AccountSvc/DataInquiry.asmx/ + methodName
vs.
http://tempuri.org/GetMyName
You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl
There should be a <soap:operation>
tag underneath the <wsdl:operation>
tag that matches the operation you are attempting to execute, which appears to be GetMyName
.
There is no XML declaration in the request body that includes your SOAP XML.
You specify text/xml
in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii
, but there's no telling if you aren't specifying them!
The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8
Hope that helps!
One way to achieve it, is by map your welcome-file to your controller request path in the web.xml
file:
[web.xml]
<web-app ...
<!-- Index -->
<welcome-file-list>
<welcome-file>home</welcome-file>
</welcome-file-list>
</web-app>
[LoginController.java]
@Controller("loginController")
public class LoginController{
@RequestMapping("/home")
public String homepage2(ModelMap model, HttpServletRequest request, HttpServletResponse response){
System.out.println("blablabla2");
model.addAttribute("sigh", "lesigh");
return "index";
}
It sets how the database server sorts (compares pieces of text). in this case:
SQL_Latin1_General_CP1_CI_AS
breaks up into interesting parts:
latin1
makes the server treat strings using charset latin 1, basically asciiCP1
stands for Code Page 1252CI
case insensitive comparisons so 'ABC' would equal 'abc'AS
accent sensitive, so 'ü' does not equal 'u'P.S. For more detailed information be sure to read @solomon-rutzky's answer.
I got the following error:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
I fixed this by changing my hibernate properties file
hibernate.current_session_context_class=thread
My code and configuration file as follows
session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.beginTransaction();
session.createQuery(Qry).executeUpdate();
session.getTransaction().commit();
on properties file
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.query_factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory
hibernate.current_session_context_class=thread
on cofiguration file
<properties>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.query.factory_class">${hibernate.query_factory_class}</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
</props>
</property>
</properties>
Thanks,
Ashok
Just had similar problem in Eclipse fixed with:
rightclick on project->Properties->Deployment Assembly->add Maven Dependencies
something kicked it out before, while I was editing my pom.xml
I had all needed jar files, taglib uri and web.xml was ok
If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.
I've got a similar message and my problem were some proxy preferences in my settings.xml. So i disabled them and everything works fine.
Yes, Hibernate can be configured by way of the hibernate.hbm2ddl.auto
property in the hibernate.cfg.xml
file to automatically create tables in your DB in order to store your entities in them if the table doesn't already exist.
This can be handy during development where a new, in-memory,
DB can be used and created a new on every run of the application or during testing.
A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:
from tkinter import Frame, Tk
class MyApp():
def __init__(self):
self.root = Tk()
self.my_frame_red = Frame(self.root, bg='red')
self.my_frame_red.grid(row=0, column=0, sticky='nsew')
self.my_frame_blue = Frame(self.root, bg='blue')
self.my_frame_blue.grid(row=0, column=1, sticky='nsew')
self.root.grid_rowconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.root.mainloop()
if __name__ == '__main__':
app = MyApp()
But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.
if you are using tomcat you may try this
<servlet-mapping>
<http-method>POST</http-method>
</servlet-mapping>
in addition to <servlet-name>
and <url-mapping>
At the package stage, the plugin allows configuration of the imported file names via file mapping:
http://maven.apache.org/plugins/maven-ear-plugin/examples/customize-file-name-mapping.html
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ear-plugin</artifactId>
<version>2.7</version>
<configuration>
[...]
<fileNameMapping>full</fileNameMapping>
</configuration>
</plugin>
http://maven.apache.org/plugins/maven-war-plugin/war-mojo.html#outputFileNameMapping
If you have configured your version to be 'testing' via a profile or something, this would work for a war package:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<encoding>UTF-8</encoding>
<outputFileNameMapping>@{groupId}@-@{artifactId}@-@{baseVersion}@@{dashClassifier?}@.@{extension}@</outputFileNameMapping>
</configuration>
</plugin>
First, we need to filter the XML so as to parse that into an object
$response = strtr($xml_string, ['</soap:' => '</', '<soap:' => '<']);
$output = json_decode(json_encode(simplexml_load_string($response)));
var_dump($output->Body->PaymentNotification->payment);
If you are using Maven you may have both src/{main,test}/resources/META-INF/persistence.xml
. This is a common setup: test your JPA code with h2 or Derby and deploy it with PostgreSQL or some other full DBMS. If you're using this pattern, do make sure the two files have different unit names, else some versions of the Persistence
class will try to load BOTH (because of course your test-time CLASSPATH includes both classes and test-classes); this will cause conflicting definitions of the persistence unit, resulting in the dreaded annoying message that we all hate so much!
Worse: this may "work" with some older versions of e.g., Hibernate, but fail with current versions. Worth getting it right anyway...
I case you are running SpringBoot:
I just had the same problem, that I could not Autowire one of my services from the static main method.
See below an approach in case you are relying on SpringApplication.run:
@SpringBootApplication
public class PricingOnlineApplication {
@Autowired
OrchestratorService orchestratorService;
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);
application.start();
}
private void start() {
orchestratorService.performPricingRequest(null);
}
}
I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)
I had this problem today testing a method that converted an object that contained a Map
to a JSON string. I assume Eclipse and the Maven surefire plugin were using different JREs which had different implementations of HashMap
ordering or something, which caused the tests run through Eclipse to pass and the tests run through surefire to fail (assertEquals
failed). The easiest solution was to use an implementation of Map that had reliable ordering.
There's now a Jackson module (for Jackson 2) specifically designed to handle Hibernate lazy initialization problems when serializing.
https://github.com/FasterXML/jackson-datatype-hibernate
Just add the dependency (note there are different dependencies for Hibernate 3 and Hibernate 4):
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.4.0</version>
</dependency>
and then register the module when intializing Jackson's ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Hibernate4Module());
Documentation currently isn't great. See the Hibernate4Module code for available options.
Maybe I'm not understanding the question but here is my simple solution that works -
# I want to Display total heads bent this machine so I define a label -
TotalHeadsLabel3 = Label(leftFrame)
TotalHeadsLabel3.config(font=Helv12,fg='blue',text="Total heads " + str(TotalHeads))
TotalHeadsLabel3.pack(side=TOP)
# I update the int variable adding the quantity bent -
TotalHeads = TotalHeads + headQtyBent # update ready to write to file & display
TotalHeadsLabel3.config(text="Total Heads "+str(TotalHeads)) # update label with new qty
I agree that labels are not automatically updated but can easily be updated with the
<label name>.config(text="<new text>" + str(<variable name>))
That just needs to be included in your code after the variable is updated.
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
I tried my best to follow the answers given above. But I have below reason for the same.
Note: This is for maven+eclipse+tomcat deployment and issue faced especially with spring mvc.
1- If you are including servlet and jsp dependency please mark them provided in scope.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
Possibly you might be including jstl as dependency. So, jsp-api.jar
and servlet-api.jar
will be included along. So, require to exclude the servlet-api and jsp-api being deployed as required lib in target or in "WEB-INF/lib" as given below.
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<artifactId>servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
<exclusion>
<artifactId>jsp-api</artifactId>
<groupId>javax.servlet.jsp</groupId>
</exclusion>
</exclusions>
</dependency>
I've just spent a while trying to get this to work an have a written a Ruby gem that accesses the API. You can read more on it's project page.
This is working code in Ruby:
require 'savon'
client = Savon::Client.new do
wsdl.document = "http://realtime.nationalrail.co.uk/LDBWS/wsdl.aspx"
end
response = client.request 'http://thalesgroup.com/RTTI/2012-01-13/ldb/GetDepartureBoard' do
namespaces = {
"xmlns:soap" => "http://schemas.xmlsoap.org/soap/envelope/",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd" => "http://www.w3.org/2001/XMLSchema"
}
soap.xml do |xml|
xml.soap(:Envelope, namespaces) do |xml|
xml.soap(:Header) do |xml|
xml.AccessToken do |xml|
xml.TokenValue('ENTER YOUR TOKEN HERE')
end
end
xml.soap(:Body) do |xml|
xml.GetDepartureBoardRequest(xmlns: "http://thalesgroup.com/RTTI/2012-01-13/ldb/types") do |xml|
xml.numRows(10)
xml.crs("BHM")
xml.filterCrs("BHM")
xml.filterType("to")
end
end
end
end
end
p response.body
Hope that's helpful for someone!
I have faced similar problem
So
I just do
1.update Maven Project
2.install maven.
Add the following dependency in your pom.xml file and if you are using IntelliJ then add the same jars to WEB-INF->lib folder.... path is Project Structure -> Atrifacts -> Select jar from Available Elements pane and double click. It will add to respective folder
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
I've had the same problem, was missing a slash in servlet url in web.xml
replace
<servlet-mapping>
<servlet-name>jsonservice</servlet-name>
<url-pattern>jsonservice</url-pattern>
</servlet-mapping>
with
<servlet-mapping>
<servlet-name>jsonservice</servlet-name>
<url-pattern>/jsonservice</url-pattern>
</servlet-mapping>
When m2eclipse is installed properly, it should add dependencies automatically. However, you should generate the eclipse project files by entering:
mvn eclipse:m2eclipse
or, alternatively if you don't use m2eclipse:
mvn eclipse:eclipse
http://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html
I ran into a similar problem using the maven-shade-plugin. I found the solution to my problems in their example page above.
The answer of Pascal Thivent helped me out, too.
But if you manage your plugins within the <pluginManagement>
element, you have to define the assembly again outside of the plugin management, or else the dependencies are not packed in the jar if you run mvn install
.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>main.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins> <!-- did NOT work without this -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<!-- dependencies commented out to shorten example -->
</dependencies>
</project>
So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:
import elementtree.ElementTree as ET
tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')
print thingy.attrib
and got the following back:
{'name': 'NWIS Time Series Instantaneous Values'}
It appears to have found the timeSeries element without needing to use numerical indices.
What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.
for JPA 2+ this does the trick
<jar-file></jar-file>
scan all jars in war for annotated @Entity classes
There is no need to use the classpath: protocol in your schemaLocation URL if the namespace is configured correctly and the XSD file is on your classpath.
Spring doc "Registering the handler and the schema" shows how it should be done.
In your case, the problem was probably that the spring-context jar on your classpath was not 2.1. That was why changing the protocol to classpath: and putting the specific 2.1 XSD in your classpath fixed the problem.
From what I've seen, there are 2 schemas defined for the main XSD contained in a spring-* jar. Once to resolve the schema URL with the version and once without it.
As an example see this part of the spring.schemas contents in spring-context-3.0.5.RELEASE.jar:
http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd
http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd
http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.0.xsd
This means that (in xsi:schemaLocation)
http://www.springframework.org/schema/context/spring-context-2.5.xsd
will be validated against
org/springframework/context/config/spring-context-2.5.xsd
in the classpath.
http://www.springframework.org/schema/context/spring-context-3.0.xsd
or
http://www.springframework.org/schema/context/spring-context.xsd
will be validated against
org/springframework/context/config/spring-context-3.0.xsd
in the classpath.
http://www.springframework.org/schema/context/spring-context-2.1.xsd
is not defined so Spring will look for it using the literal URL defined in schemaLocation.
//get file input
var $el = $('input[type=file]');
//set the next siblings (the span) text to the input value
$el.next().text( $el.val() );
Well... I had the same issue and it was a headache. Since I didn't care much about the namespace or the xml schema, I just deleted this data from my xml and it solved all my issues. May not be the best answer? Probably, but if you don't want to deal with all of this and you ONLY care about the data (and won't be using the xml for some other task) deleting the namespace may solve your problems.
XmlDocument vinDoc = new XmlDocument();
string vinInfo = "your xml string";
vinDoc.LoadXml(vinInfo);
vinDoc.InnerXml = vinDoc.InnerXml.Replace("xmlns=\"http://tempuri.org\/\", "");
Adding my that also cleans out the name of nodes that have namespace prefixes:
public static string RemoveAllNamespaces(XElement element)
{
string tex = element.ToString();
var nsitems = element.DescendantsAndSelf().Select(n => n.ToString().Split(' ', '>')[0].Split('<')[1]).Where(n => n.Contains(":")).DistinctBy(n => n).ToArray();
//Namespace prefix on nodes: <a:nodename/>
tex = nsitems.Aggregate(tex, (current, nsnode) => current.Replace("<"+nsnode + "", "<" + nsnode.Split(':')[1] + ""));
tex = nsitems.Aggregate(tex, (current, nsnode) => current.Replace("</" + nsnode + "", "</" + nsnode.Split(':')[1] + ""));
//Namespace attribs
var items = element.DescendantsAndSelf().SelectMany(d => d.Attributes().Where(a => a.IsNamespaceDeclaration || a.ToString().Contains(":"))).DistinctBy(o => o.Value);
tex = items.Aggregate(tex, (current, xAttribute) => current.Replace(xAttribute.ToString(), ""));
return tex;
}
You use xsi:nil
when your schema semantics indicate that an element has a default value, and that the default value should be used if the element isn't present. I have to assume that there are smart people to whom the preceding sentence is not a self-evidently terrible idea, but it sounds like nine kinds of bad to me. Every XML format I've ever worked with represents null values by omitting the element. (Or attribute, and good luck marking an attribute with xsi:nil
.)
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)
personally I favor validating without a callback:
public bool ValidateSchema(string xmlPath, string xsdPath)
{
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);
xml.Schemas.Add(null, xsdPath);
try
{
xml.Validate(null);
}
catch (XmlSchemaValidationException)
{
return false;
}
return true;
}
(see Timiz0r's post in Synchronous XML Schema Validation? .NET 3.5)
After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer
and custom XML serialization via IXmlSerialiazble
.
To wit, I'll use the same MyTypeWithNamespaces
XML sample that's been used in the answers to this question so far.
[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
// Don't do this!! Microsoft's documentation explicitly says it's not supported.
// It doesn't throw any exceptions, but in my testing, it didn't always work.
// new XmlQualifiedName(string.Empty, string.Empty), // And don't do this:
// new XmlQualifiedName("", "")
// DO THIS:
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
// Add any other namespaces, with prefixes, here.
});
}
// If you have other constructors, make sure to call the default constructor.
public MyTypeWithNamespaces(string label, int epoch) : this( )
{
this._label = label;
this._epoch = epoch;
}
// An element with a declared namespace different than the namespace
// of the enclosing type.
[XmlElement(Namespace="urn:Whoohoo")]
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _label;
// An element whose tag will be the same name as the property name.
// Also, this element will inherit the namespace of the enclosing type.
public int Epoch
{
get { return this._epoch; }
set { this._epoch = value; }
}
private int _epoch;
// Per Microsoft's documentation, you can add some public member that
// returns a XmlSerializerNamespaces object. They use a public field,
// but that's sloppy. So I'll use a private backed-field with a public
// getter property. Also, per the documentation, for this to work with
// the XmlSerializer, decorate it with the XmlNamespaceDeclarations
// attribute.
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
}
That's all to this class. Now, some objected to having an XmlSerializerNamespaces
object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.
Now, when it comes time to serialize the class, you would use the following code:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
/******
OK, I just figured I could do this to make the code shorter, so I commented out the
below and replaced it with what follows:
// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");
******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();
// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.
// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
Once you have done this, you should get the following output:
<MyTypeWithNamespaces>
<Label xmlns="urn:Whoohoo">myLabel</Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces
member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable
.
It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi
and xsd
namespaces generated by the XmlSerializer
.
UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo
. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra
and Whoohoo
. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra
is the defalt namespace. I could inside my MyTypeWithNamespaces
class add a namespace prefix for the Whoohoo
namespace like so:
public MyTypeWithNamespaces
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
new XmlQualifiedName("w", "urn:Whoohoo")
});
}
Now, in my class definition, I indicated that the <Label/>
element is in the namespace "urn:Whoohoo"
, so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:
<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
<w:Label>myLabel</w:Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Because <Label>
is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi
and xsd
namespaces.
You can use the BlockingCollection and ConcurrentQueue in the System.Collections.Concurrent Namespace
public class ProducerConsumerQueue<T> : BlockingCollection<T>
{
/// <summary>
/// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
/// </summary>
public ProducerConsumerQueue()
: base(new ConcurrentQueue<T>())
{
}
/// <summary>
/// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
/// </summary>
/// <param name="maxSize"></param>
public ProducerConsumerQueue(int maxSize)
: base(new ConcurrentQueue<T>(), maxSize)
{
}
}
Have a look at iconv()
or mb_convert_encoding()
.
Just by the way: why don't utf8_encode()
and utf8_decode()
work for you?
utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
utf8_encode — Encodes an ISO-8859-1 string to UTF-8
So essentially
$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');
all should do the same - with utf8_en/decode()
requiring no special extension, mb_convert_encoding()
requiring ext/mbstring and iconv()
requiring ext/iconv.
If you want to remove the namespace you may also want to remove the version, to save you searching I've added that functionality so the below code will do both.
I've also wrapped it in a generic method as I'm creating very large xml files which are too large to serialize in memory so I've broken my output file down and serialize it in smaller "chunks":
public static string XmlSerialize<T>(T entity) where T : class
{
// removes version
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
using (StringWriter sw = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
// removes namespace
var xmlns = new XmlSerializerNamespaces();
xmlns.Add(string.Empty, string.Empty);
xsSubmit.Serialize(writer, entity, xmlns);
return sw.ToString(); // Your XML
}
}
The compiler doesn't know that Environment.Exit() does not return. Why not just "return" from Main()?
It looks like you're not specifying a database name to connect to, should go something like
jdbc:hsqldb:hsql://serverName:port/DBname
This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.
You can find more on MSXML2.DOMDocument at the following sites:
You can use the following command c:\path of you tomcat directory\bin>catalina run
We can also make use of below given dependency and plugin in your pom file - I make use of maven. With the use of these you can generate POJO's as per your JSON Schema and then make use of code given below to populate request JSON object via src object specified as parameter to gson.toJson(Object src) or vice-versa. Look at the code below:
Gson gson = new GsonBuilder().create();
String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());
Gson gson2 = new Gson();
Error expectederr = gson2.fromJson(payloadStr, Error.class);
And the Maven settings:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
<plugin>
<groupId>com.googlecode.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>0.3.7</version>
<configuration>
<sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
<targetPackage>com.example.types</targetPackage>
</configuration>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like
sqlCommand.Transaction = transaction;
And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like
sqlCommand.CommandText = "select * from table1";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "select * from table2";
sqlCommand.ExecuteNonQuery();
The only way to guarentee you're checking an actual HTMLEement, and not just an object with the same properties as an HTML Element, is to determine if it inherits from Node, since its impossible to make a new Node() in JavaScript. (unless the native Node function is overwritten, but then you're out of luck). So:
function isHTML(obj) {_x000D_
return obj instanceof Node;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
isHTML(test),_x000D_
isHTML(ok),_x000D_
isHTML(p),_x000D_
isHTML(o),_x000D_
isHTML({_x000D_
constructor: {_x000D_
name: "HTML"_x000D_
}_x000D_
}),_x000D_
isHTML({_x000D_
__proto__: {_x000D_
__proto__: {_x000D_
__proto__: {_x000D_
__proto__: {_x000D_
constructor: {_x000D_
constructor: { _x000D_
name: "Function"_x000D_
_x000D_
},_x000D_
name: "Node"_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}),_x000D_
)
_x000D_
<div id=test></div>_x000D_
<blockquote id="ok"></blockquote>_x000D_
<p id=p></p>_x000D_
<br id=o>_x000D_
<!--think of anything else you want--!>
_x000D_
Hope not to be late. It is accomplished using only one line!
-webkit-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
-moz-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
-o-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
That works on Chrome. You have to separate the CSS properties with a comma.
Here is a working example: http://jsfiddle.net/H2jet/
If the formulas are identical you can use Find and Replace with Match entire cell contents
checked and Look in: Formulas
. Select the range, go into Find and Replace, make your entries and `Replace All.
Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.
The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.
Function RegexFormulaReplace(formula As String)
Dim regex As New RegExp
regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
' Test if a match is found
If regex.Test(formula) = True Then
RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
Else
RegexFormulaReplace = CVErr(xlErrValue)
End If
Set regex = Nothing
End Function
In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer
tab of the main ribbon, select VBA
and then References
from the main toolbar. Scroll down to find the reference to the library and check the box next to it.
For those who need to preserve the original filename and extension
$origin = 'http://example.com/image.jpg';
$filename = pathinfo($origin, PATHINFO_FILENAME);
$ext = pathinfo($origin, PATHINFO_EXTENSION);
$dest = 'myfolder/' . $filename . '.' . $ext;
copy($origin, $dest);
If your process gives a huge stdout and no stderr, communicate()
might be the wrong way to go due to memory restrictions.
Instead,
process = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# wait for the process to terminate
for line in process.stdout: do_something(line)
errcode = process.returncode
might be the way to go.
process.stdout
is a file-like object which you can treat as any other such object, mainly:
read()
from itreadline()
from it andThe latter is what I do above in order to get its contents line by line.
Also can be done from the environment variable:
export CURL_CA_BUNDLE=""
Use the WebClient
class in System.Net
:
var json = new WebClient().DownloadString("url");
Keep in mind that WebClient
is IDisposable
, so you would probably add a using
statement to this in production code. This would look like:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("url");
}
You can use the root.configure(background='your colour') example:-
import tkinter root=tkiner.Tk() root.configure(background='pink')
In my case, what I concerned about is the C: drive disk space. So what I did is copy the ".avd" folder(not file) to other drive, and leave the ".ini" file there but change it to point to the moved
After trying all of this solutions, I still had different problems. So what I found the simplest way was to create a python file: config.py, with a dictionary containing the file's absolute path and import it into the script. something like
import config as cfg
import pandas as pd
pd.read_csv(cfg.paths['myfilepath'])
where config.py has inside:
paths = {'myfilepath': 'home/docs/...'}
It is not automatic but it is a good solution when you have to work in different directory or different machines.
In my case I had to specify the Port Number using
scp -P 2222 username@hostip:/directory/ /localdirectory/
Twitter Bootstrap v3.0.3 has a class: center-block
Center content blocks
Set an element to display: block and center via margin. Available as a mixin and class.
Just need to add a class .center-block
in the img
tag, looks like this
<div class="container">
<div class="row">
<div class="span4"></div>
<div class="span4"><img class="center-block" src="logo.png" /></div>
<div class="span4"></div>
</div>
</div>
In Bootstrap already has css style call .center-block
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
You can see a sample from here
Dockers use images which are build in layers. This adds a lot in terms of portability, sharing, versioning and other features. These images are very easy to port or transfer and since they are in layers, changes in subsequent versions are added in form of layers over previous layers. So, while porting many a times you don't need to port the base layers. Dockers have containers which run these images with execution environment contained, they add changes as new layers providing easy version control.
Apart from that Docker Hub is a good registry with thousands of public images, where you can find images which have OS and other softwares installed. So, you can get a pretty good head start for your application.
You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx.
It is possible to make implicit connections without having to use the now obsolete System.Web.Mail namespace, but you have to access the Microsoft CDO (Collaborative Data Object). I have supplied an example of how to use the CDO in another discussion (GMail SMTP via C# .Net errors on all ports).
Hope this helps!
For an ES6 implementation, use something like the following:
const millisToMinutesAndSeconds = (millis) => {
const minutes = Math.floor(millis / 60000);
const seconds = ((millis % 60000) / 1000).toFixed(0);
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}
You can try this with your nav div
:
postion: fixed;
top: 0;
width: 100%;
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
In addition to all the mentions of StopIteration, the Python "for" loop simply does what you want:
>>> it = iter("hello")
>>> for i in it:
... print i
...
h
e
l
l
o
If You are comparing only with the date vale, then converting it to date (not datetime) will work
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= convert(date,'2013-04-12',102)
This conversion is also applicable during using GetDate() function
Nobody has proposed this simple plain-text solution:
from pprint import pprint
pprint(s.to_dict())
which produces results like the following:
{'% Diabetes': 0.06365372374283895,
'% Obesity': 0.06365372374283895,
'% Bachelors': 0.0,
'% Poverty': 0.09548058561425843,
'% Driving Deaths': 1.1775938892425206,
'% Excessive Drinking': 0.06365372374283895}
Additionally, when using Jupyter notebooks, this is a great solution.
Note: pd.Series()
has no .to_html()
so it must be converted to pd.DataFrame()
from IPython.display import display, HTML
display(HTML(s.to_frame().to_html()))
which produces results like the following:
Try Unlocker.
The Unlocker site has a nifty chart (scroll down after following the link) that shows a comparison to other tools. Obviously such comparisons are usually biased since they are typically written by the tool author, but the chart at least lists the alternatives so that you can try them for yourself.
At the moment (with the latest changes to Swift), NSDate.date()
is not longer available.
Instead you just need to initialize NSDate
and it gets the current date and time.
To try it, in a playground:
var d = NSDate()
d
and you will get:
Oct 22, 2014, 12:20 PM"
Do this in your .profile -
export JAVA_HOME=`/usr/libexec/java_home`
(backticks make sure to execute the command and place its value in JAVA_HOME)
You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else.
By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment
in order to find the action.
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
There are some subtle differences that mean you can use ViewData and ViewBag in slightly different ways from the view. One advantage is outlined in this post http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx and shows that casting can be avoided in the example by using the ViewBag instead of ViewData.
It is possible to get a web application running in full screen in both iOS and Android, it is called a PWA and after mucha hard work, it was the only way around this issue.
PWAs open a number of interesting options for development that should not be missed. I've made a couple already, check out this Public and Private Tender Manual For Designers (Spanish). And here is an English explanation from the CosmicJS site
Using Visual Studio's Productivity Power Tools (free) extension helps a bit. Specifically, the Solution Error Visualizer
feature. With it, compilation errors marked visually in the solution explorer (in the source file where the error was found). For some reason, however, this feature does not work as with other errors anywhere else in the code.
With MVC views, any compile-time errors will still be underlined in red in their respective .cs files, but signaling these errors is not propagated upwards in the Solution Explorer (in no way, even not in the containing source file).
Thanks for BlueClouds
for correcting my previous statement.
I have just reported this as an issue on the extension's github project.
Apart from the syntax, the main difference is in the scoping:
# scoping with alias_method
class User
def full_name
puts "Johnnie Walker"
end
def self.add_rename
alias_method :name, :full_name
end
end
class Developer < User
def full_name
puts "Geeky geek"
end
add_rename
end
Developer.new.name #=> 'Geeky geek'
In the above case method “name” picks the method “full_name” defined in “Developer” class. Now lets try with alias
.
class User
def full_name
puts "Johnnie Walker"
end
def self.add_rename
alias name full_name
end
end
class Developer < User
def full_name
puts "Geeky geek"
end
add_rename
end
Developer.new.name #=> 'Johnnie Walker'
With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.
This is because alias
is a keyword and it is lexically scoped. It means it treats self
as the value of self at the time the source code was read . In contrast alias_method
treats self
as the value determined at the run time.
Source: http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html
I'd rather not turn an integer into a string, so here's the function I use for this:
def digitize(n, base=10):
if n == 0:
yield 0
while n:
n, d = divmod(n, base)
yield d
Examples:
tuple(digitize(123456789)) == (9, 8, 7, 6, 5, 4, 3, 2, 1)
tuple(digitize(0b1101110, 2)) == (0, 1, 1, 1, 0, 1, 1)
tuple(digitize(0x123456789ABCDEF, 16)) == (15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
As you can see, this will yield digits from right to left. If you'd like the digits from left to right, you'll need to create a sequence out of it, then reverse it:
reversed(tuple(digitize(x)))
You can also use this function for base conversion as you split the integer. The following example splits a hexadecimal number into binary nibbles as tuples:
import itertools as it
tuple(it.zip_longest(*[digitize(0x123456789ABCDEF, 2)]*4, fillvalue=0)) == ((1, 1, 1, 1), (0, 1, 1, 1), (1, 0, 1, 1), (0, 0, 1, 1), (1, 1, 0, 1), (0, 1, 0, 1), (1, 0, 0, 1), (0, 0, 0, 1), (1, 1, 1, 0), (0, 1, 1, 0), (1, 0, 1, 0), (0, 0, 1, 0), (1, 1, 0, 0), (0, 1, 0, 0), (1, 0, 0, 0))
Note that this method doesn't handle decimals, but could be adapted to.
Note that since May 2013 ("Repository redirects are here!"), you can rename your GitHub repo without breaking any links:
We're happy to announce that starting today, we'll automatically redirect all requests for previous repository locations to their new home in these circumstances. There's nothing special you have to do. Just rename away and we'll take care of the rest.
As a special bonus, we'll also be servicing all Git clone, fetch, and push requests from previous repository locations.
That means you don't even have to git remote set-url
(change the url of your remote GitHub repo) on your local cloned repo!
Although Gabriel notes in the comments that the official GitHub help page strongly recommends that you do so:
to reduce confusion, we strongly recommend updating any existing local clones to point to the new repository URL. You can do this by using git remote on the command line:
git remote set-url origin new_url
Beware though:
GitHub Pages sites are not automatically redirected when their repositories are renamed at this time.
Renaming a Pages repository will continue to break any existing links to content hosted on thegithub.io
domain or custom domains.
Plus, the user still owns the namespace: if he/she creates a new repo using the old name of the renamed repo, that redirection (for said renamed repo) will stop working.
Or you can just include the SELECT statement in the SQL that's invoking the trigger, so its passed in as one of the columns in the trigger row(s). As long as you're certain it will infallibly return only one row (hence one value). (And, of course, it must not return a value that interacts with the logic in the trigger, but that's true in any case.)
For anyone who looks at this today after 2 years, Visual Studio 2019 (Community edition as well) shows the references
Adding this configuration in application.properties file to fixed this issue easily.
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
An aggregate function requires a GROUP BY in standard SQL
This is "Get minimum date per title" in plain language
SELECT title, MIN(date) FROM table GROUP BY title
Most RDBMS and the standard require that column is either in the GROUP BY or in a functions (MIN, COUNT etc): MySQL is the notable exception with some extensions that give unpredictable behaviour
There is a shortcut (Ctrl+Shift+A for Windows and Linux users, Command+Shift+A for Mac users) to select the whole block within the currently selected tag.
For example, if you pressed this while your text cursor was within the outer div
tag in the code below, all the div
s with class selected
would be selected.
<div class='current_tag_block'>
<div class='selected'></div>
<div class='selected'></div>
<div class='selected'></div>
<div class='selected'></div>
</div>
Assuming you have a Z:
drive mapped:
Get-ChildItem -Path "Z:" -Recurse | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq "hosts" }
If someone is having trouble with installing php-mbstring
package in ubuntu do following
sudo apt-get install libapache2-mod-php5
if you need to call a controller from a view, maybe to load a partial view, you thinking as modular programming, and you should implement HMVC structure in lieu of plane MVC. CodeIgniter didnt implement HMVC natively, but you can use this useful library in order to implement HMVC. https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup remember:that all your controllers should extends from MX_Controller in order to using this feature.
yourTextView.setText(String.format("Value of a: %.2f", a));
Try this:
select min(closing_date), date_part('month',closing_date) || '-' || date_part('year',closing_date) AS month,
Category, COUNT(Status)TotalCount
FROM MyTable
where Closing_Date >= '2012-02-01' AND Closing_Date <= '2012-12-31'
AND Defect_Status1 is not null
GROUP BY month, Category,
ORDER BY 1
This way you are grouping by a concatenated date format, joined by a -
Use this server variable to get the protocol details:
$scheme = $_SERVER['REQUEST_SCHEME'] . '://';
echo $scheme; //it gives http:// or https://
Note that this server variable is unreliable. For more information take a look at: Is $_SERVER['REQUEST_SCHEME'] reliable?
In Case of not considering '0' or 'NULL' in average function. Simply use
AVG(NULLIF(your_column_name,0))
An IFrame WILL "trigger" the spell checker (if it has content-editable set to true) just as a textfield, at least in Chrome.
You're looking for $anchorScroll()
.
Here's the (crappy) documentation.
Basically you just inject it and call it in your controller, and it will scroll you to any element with the id found in $location.hash()
app.controller('TestCtrl', function($scope, $location, $anchorScroll) {
$scope.scrollTo = function(id) {
$location.hash(id);
$anchorScroll();
}
});
<a ng-click="scrollTo('foo')">Foo</a>
<div id="foo">Here you are</div>
Here is a plunker to demonstrate
EDIT: to use this with routing
Set up your angular routing as usual, then just add the following code.
app.run(function($rootScope, $location, $anchorScroll, $routeParams) {
//when the route is changed scroll to the proper element.
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
$location.hash($routeParams.scrollTo);
$anchorScroll();
});
});
and your link would look like this:
<a href="#/test?scrollTo=foo">Test/Foo</a>
Here is a Plunker demonstrating scrolling with routing and $anchorScroll
And even simpler:
app.run(function($rootScope, $location, $anchorScroll) {
//when the route is changed scroll to the proper element.
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
if($location.hash()) $anchorScroll();
});
});
and your link would look like this:
<a href="#/test#foo">Test/Foo</a>
None of the answers solved my problem.
What did it for me was switching environments and going back to the same environment. File->Settings->Project interpreter
I am using conda environments.
jQuery dialog has an isOpen
property that can be used to check if a jQuery dialog is open or not.
You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html
Possibly off-topic, but maybe you came here looking for a way to sanitise text input from an HTML form, so that when a user inputs the apostrophe character, it doesn't throw an error when you try to write the text to an SQL-based table in a DB. There are a couple of ways to do this, and you might want to read about SQL injection too. Here's an example of using prepared statements and bound parameters in PHP:
$input_str = "Here's a string with some apostrophes (')";
// sanitise it before writing to the DB (assumes PDO)
$sql = "INSERT INTO `table` (`note`) VALUES (:note)";
try {
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':note', $input_str, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
return $dbh->errorInfo();
}
return "success";
In the special case where you may want to store your apostrophes using their HTML entity references, PHP has the htmlspecialchars() function which will convert them to '
. As the comments indicate, this should not be used as a substitute for proper sanitisation, as per the example given.
It can be complicated to compute a diff in your head from the different sections in $MERGED and apply that. In my setup, meld helps by showing you these diffs visually, using:
[merge]
tool = mymeld
conflictstyle = diff3
[mergetool "mymeld"]
cmd = meld --diff $BASE $REMOTE --diff $REMOTE $LOCAL --diff $LOCAL $MERGED
It looks strange but offers a very convenient work-flow, using three tabs:
in tab 1 you see (from left to right) the change that you should make in tab 2 to solve the merge conflict.
in the right side of tab 2 you apply the "change that you should make" and copy the entire file contents to the clipboard (using ctrl-a and ctrl-c).
in tab 3 replace the right side with the clipboard contents. If everything is correct, you will now see - from left to right - the same change as shown in tab 1 (but with different contexts). Save the changes made in this tab.
Notes:
Using jsonpickle
import jsonpickle
object = YourClass()
json_object = jsonpickle.encode(object)
If you are interesting in modern api way, avoiding NSSearchPath and filter files in documents directory, before deletion, you can do like:
let fileManager = FileManager.default
let keys: [URLResourceKey] = [.nameKey, .isDirectoryKey]
let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles, .skipsPackageDescendants]
guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last,
let fileEnumerator = fileManager.enumerator(at: documentsUrl,
includingPropertiesForKeys: keys,
options: options) else { return }
let urls: [URL] = fileEnumerator.flatMap { $0 as? URL }
.filter { $0.pathExtension == "exe" }
for url in urls {
do {
try fileManager.removeItem(at: url)
} catch {
assertionFailure("\(error)")
}
}
Have you already looked at adding a check constraint
on that column which would restrict values? Something like:
CREATE TABLE SomeTable
(
Id int NOT NULL,
Frequency varchar(200),
CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
)
I found an add-on for Brackets.io that uses auto-indent called Indentator.
It uses shortcut keys Ctrl + Alt + I
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
You could use method
javax.crypto.Cipher.getMaxAllowedKeyLength(String transformation)
to test the available key length, use that and inform the user about what is going on. Something stating that your application is falling back to 128 bit keys due to the policy files not being installed, for example. Security conscious users will install the policy files, others will continue using weaker keys.
It appears you can install the command line tools without getting Xcode from Downloads for Apple Developers. It required me to login with my apple account.
Alternatively, once you install Xcode from the app store, you might notice the command line tools are not installed by default. Open Xcode, go to preferences, click to the "downloads" tab, and from there you can download and install command line tools.
100, it will hold the same references. Therefore if you make a change to a specific object in the list
, it will affect the same object in anotherList
.
Adding or removing objects in any of the list will not affect the other.
list
and anotherList
are two different instances, they only hold the same references of the objects "inside" them.
Based on the current user's latitude, longitude and the distance you wants to find,the sql query is given below.
SELECT * FROM(
SELECT *,(((acos(sin((@latitude*pi()/180)) * sin((Latitude*pi()/180))+cos((@latitude*pi()/180)) * cos((Latitude*pi()/180)) * cos(((@longitude - Longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance FROM Distances) t
WHERE distance <= @distance
@latitude and @longitude are the latitude and longitude of the point. Latitude and longitude are the columns of distances table. Value of pi is 22/7
I received this error while trying to run Google's Firebase analytics sample app:
Prerequisites:
Add Procedure:
Remove Procedure:
I added and removed the sample app multiple times without any noticeable side effects.
I like the idea of seting tomcat6 memory based on available server memory (it is cool because I don't have to change the setup after hardware upgrade). Here is my (a bit extended memory setup):
export CATALINA_OPTS="-Xmx
`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`
k -Xms`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`
k -XX:NewSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k -XX:MaxNewSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k -XX:PermSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k -XX:MaxPermSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k"
Put it to: "{tomcat}/bin/startup.sh" (e.g. "/usr/share/tomcat6/bin" for Ubuntu 10.10)
Is this what you're looking for?
I had this problem too. I had used stateSave
option and that made this problem.
Remove this option and problem is solved.
It's just about the remainders. Let me show you how
10 % 5=0
9 % 5=4 (because the remainder of 9 when divided by 5 is 4)
8 % 5=3
7 % 5=2
6 % 5=1
5 % 5=0 (because it is fully divisible by 5)
Now we should remember one thing, mod means remainder so
4 % 5=4
but why 4? because 5 X 0 = 0 so 0 is the nearest multiple which is less than 4 hence 4-0=4
Press Ctrl + KM and then type in (or click) the language you want.
Alternatively, to access it from the command palette, look for "Change Language Mode" as seen below:
Please use the following query to list the tables in your DB.
select name from sys.Tables
In Addition, you can add a where
condition, to skip system generated tables and lists only user created table by adding type ='U'
Ex : select name from sys.Tables where type ='U'
Model.select(:rating).distinct
You can use python-textops3 :
from textops import *
print('\n'.join(cat(f) | grep(search_term)))
with python-textops3 you can use unix-like commands with pipes
To be clear, the 1990's Windows way of click on Start, right click on This PC, and choose Properties, and then select Advanced system settings, and then in the dialog box that pops up, select Environment Variables, and in the list double clicking on PATH and then using the New, Edit, Move Up and Move Down all still work for changing the PATH. Power shell, and the rest of Windows get whatever you set here.
Yes you can use these new methods, but the old one still works. And at the base level all of the permanent change methods are controlled ways of editing your registry files.
-qscale:v
to control qualityUse -qscale:v
(or the alias -q:v
) as an output option.
-qmin 1
output option (because the default is -qmin 2
).ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg
See the image muxer documentation for more options involving image outputs.
ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg
I don't have a machine available to test this but it should work. First you will probably need to install the either the 2007 Office System Driver: Data Connectivity Components or the Microsoft Access Database Engine 2010 Redistributable. Then try the following code, note you will need to change the name of the Sheet in the Select statement below to match sheetname in your excel file:
using System.Data;
using System.Data.OleDb;
namespace Data_Migration_Process_Creator
{
class Class1
{
private DataTable GetDataTable(string sql, string connectionString)
{
DataTable dt = null;
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
return dt;
}
}
}
}
private void GetExcel()
{
string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
DataTable dt = GetDataTable("SELECT * from [SheetName$]", connString);
foreach (DataRow dr in dt.Rows)
{
//Do what you need to do with your data here
}
}
}
}
Note: I don't have an environment to test this in (One with Office installed) so I can't say if it will work in your environment or not but I don't see why it shouldn't work.
If you are using Java for OpenCV, then you can use the following code.
Mat img = src.clone(); //Clone from the original image
img.setTo(new Scalar(255,255,255)); //This sets the whole image to white, it is R,G,B value
I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'service.svc/Request',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('securityCode', 'Foo');
xhr.setRequestHeader('passkey', 'Bar');
}
</script>
</head>
<body>
<h1>Some Text</h1>
</body>
</html>
If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:
The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.
Hope this helps!
Just a quick note because I had a hard time with this.
By using #container { overflow: hidden; } the page I had started to have layout issues in Firefox and IE (when the zoom would go in and out the content would bounce in and out of the parent div).
The solution to this issue is to add a display: inline-block; to the same div with overflow:hidden;
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
Ah, since I had no dependencies in my master project, "gradle dependencies" only lists those and not subproject dependencies so the correct command ended up being
gradle :<subproject>:dependencies
so for me this was
gradle :master:dependencies
You can use CSS3 filters. They are relatively easy to implement, though are only supported on webkit at the minute. Samsung Galaxy 2's browser should support though, as I think that's a webkit browser?
try
{
String datestr="06/27/2007";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/dd/yyyy");
date = (Date)formatter.parse(datestr);
}
catch (Exception e)
{}
month is MM, minutes is mm..
Run git fetch (remote)
to update your remote refs, it'll show you what's new. Then, when you checkout your local branch, it will show you whether it's behind upstream.
And here is a simple Send-MailMessage
example with username/password for anyone looking for just that
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
It may be useful to just a few people, but I had the same problem and discovered that it was related to file permessions, so I gave it a 777 permission and it worked, of course after you're sure the problem it's there, make sure to change back the permissions to safer values.
C:\ <path to android sdk> \tools\source.properties (open with notepad)
There you will find it.
My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:
-----------test2-------test3
What happened is the machine actually printed this:
test-------test2-------test3\r-------
That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(12, 18)
);
Extending on @isaac-pak's answer, if you want to pass the default value to your component in a prop, you can save it in state in the componentDidMount() lifecycle method to ensure the default is selected the first time.
Note, I've updated the following code to make it more complete and to use an empty string as the initial value per the comment.
export default class MySelect extends Component {
constructor(props) {
super(props);
this.state = {
selectedValue: '',
};
this.handleChange = this.handleChange.bind(this);
this.options = [
{value: 'foo', label: 'Foo'},
{value: 'bar', label: 'Bar'},
{value: 'baz', label: 'Baz'}
];
}
componentDidMount() {
this.setState({
selectedValue: this.props.defaultValue,
})
}
handleChange(selectedOption) {
this.setState({selectedValue: selectedOption.target.value});
}
render() {
return (
<Select
value={this.options.filter(({value}) => value === this.state.selectedValue)}
onChange={this.handleChange}
options={this.options}
/>
)
}
}
MySelect.propTypes = {
defaultValue: PropTypes.string.isRequired
};
Short answer but did you have Skype open? This interferes specifically with ASP.NET by default (and localhosts in general) using port:80.
In Windows: Go to Tools -> Options -> Advanced -> Connection and uncheck the box "use port 80 and 443 as alternatives for incoming connections".
Query with sub query in Laravel
$resortData = DB::table('resort')
->leftJoin('country', 'resort.country', '=', 'country.id')
->leftJoin('states', 'resort.state', '=', 'states.id')
->leftJoin('city', 'resort.city', '=', 'city.id')
->select('resort.*', 'country.name as country_name', 'states.name as state_name','city.name as city_name', DB::raw("(SELECT GROUP_CONCAT(amenities.name) from resort_amenities LEFT JOIN amenities on amenities.id= resort_amenities.amenities_id WHERE resort_amenities.resort_id=resort.id) as amenities_name"))->groupBy('resort.id')
->orderBy('resort.id', 'DESC')
->get();
foo = foo.Substring(0,5);
delay
does not work on none queue functions, so we should use setTimeout()
.
And you don't need to separate things. All you need to do is including everything in a setTimeOut
method:
setTimeout(function () {
$("#div").addClass("error").delay(1000).removeClass("error");
}, 1000);
Loadsh is the universal standard library for coping any object deepcopy. It's a recursive algorithm. It's check everything and does copy for the given object. Writing this kind of algorithm will take longer time. It's better to leverage the same.
It's not that bad, but you forgot to call treeView2.EndUpdate()
in your addParentNode_Click()
method.
You can also call treeView2.ExpandAll()
at the end of your addChildNode_Click()
method to see your child node directly.
private void addParentNode_Click(object sender, EventArgs e) {
treeView2.BeginUpdate();
//treeView2.Nodes.Clear();
string yourParentNode;
yourParentNode = textBox1.Text.Trim();
treeView2.Nodes.Add(yourParentNode);
treeView2.EndUpdate();
}
private void addChildNode_Click(object sender, EventArgs e) {
if (treeView2.SelectedNode != null) {
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.SelectedNode.Nodes.Add(yourChildNode);
treeView2.ExpandAll();
}
}
I don't know if it was a mistake or not but there was 2 TreeViews. I changed it to only 1 TreeView...
EDIT: Answer to the additional question:
You can declare the variable holding the child node name outside of the if clause:
private void addChildNode_Click(object sender, EventArgs e) {
var childNode = textBox1.Text.Trim();
if (!string.IsNullOrEmpty(childNode)) {
TreeNode parentNode = treeView2.SelectedNode ?? treeView2.Nodes[0];
if (parentNode != null) {
parentNode.Nodes.Add(childNode);
treeView2.ExpandAll();
}
}
}
Note: see http://www.yoda.arachsys.com/csharp/csharp2/nullable.html for info about the ?? operator.
Reworked the method set originating from -> the accepted answer
@JaredRummler An answer to your comment:
Won't this add an extra new line at the end of the string?
To prevent having a newline added at the end you can use a Boolean value set during the first loop as you will in the code example Boolean firstLine
public static String convertStreamToString(InputStream is) throws IOException {
// http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
Boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if(firstLine){
sb.append(line);
firstLine = false;
} else {
sb.append("\n").append(line);
}
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws IOException {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
Starting from Bootstrap 2.1.0:
HTML:
<input type='text' class='ajax-typeahead' data-link='your-json-link' />
Javascript:
$('.ajax-typeahead').typeahead({
source: function(query, process) {
return $.ajax({
url: $(this)[0].$element[0].dataset.link,
type: 'get',
data: {query: query},
dataType: 'json',
success: function(json) {
return typeof json.options == 'undefined' ? false : process(json.options);
}
});
}
});
Now you can make a unified code, placing "json-request" links in your HTML-code.
I have used this before and I think in order to make sure credential persist and in a best secure way is
ConfigurationManager
classSecureString
classCryptography
namespace.This link will be of great help I hope : Click here
You can use the following workaround for it to work with the first parameter too:
var param1 =
HttpUtility.ParseQueryString(url.Substring(
new []{0, url.IndexOf('?')}.Max()
)).Get("param1");
The problem with the EXIT /B
solutions, when more realistically inside a batch file as just one part of it is the following. There is no subsequent processing within the said batch file after the EXIT /B
. Usually there is much more to batches than just the one, limited task.
To counter that problem:
@echo off & setlocal enableextensions enabledelayedexpansion
set myfile_=C:\_D\TEST\My test file.txt
set FirstLine=
for /f "delims=" %%i in ('type "%myfile_%"') do (
if not defined FirstLine set FirstLine=%%i)
echo FirstLine=%FirstLine%
endlocal & goto :EOF
(However, the so-called poison characters will still be a problem.)
More on the subject of getting a particular line with batch commands:
How do I get the n'th, the first and the last line of a text file?" http://www.netikka.net/tsneti/info/tscmd023.htm
[Added 28-Aug-2012] One can also have:
@echo off & setlocal enableextensions
set myfile_=C:\_D\TEST\My test file.txt
for /f "tokens=* delims=" %%a in (
'type "%myfile_%"') do (
set FirstLine=%%a& goto _ExitForLoop)
:_ExitForLoop
echo FirstLine=%FirstLine%
endlocal & goto :EOF
On my Linux machine :
git config --system --get https.proxy (returns nothing)
git config --global --get https.proxy (returns nothing)
git config --system --get http.proxy (returns nothing)
git config --global --get http.proxy (returns nothing)
I found out my https_proxy and http_proxy are set, so I just unset them.
unset https_proxy
unset http_proxy
On my Windows machine :
set https_proxy=""
set http_proxy=""
Optionally use setx to set environment variables permanently on Windows and set system environment using "/m"
setx https_proxy=""
setx http_proxy=""
Another open source tool for this is Cloud Query https://docs.cloudquery.io/
You can Start the android Service by this command.
adb shell am startservice -n packageName/.ServiceClass
Use mod_php7.c instead of mod_php5.c for PHP 7
Example
<IfModule mod_php7.c>
php_value max_execution_time 500
</IfModule>
Use diskpart.exe
.
Once you are in diskpart select volume <VolumeNumber>
then type filesystems
.
It should tell you the file system type and the allocation unit size. It will also tell you the supported sizes etc. Previously mentioned fsutil
does work, but answer isn't as clear and I couldn't find a syntax to get the same information for a junction point.
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
VMs used to work for me under Genymotion 2.0.0. with default RAM and CPU settings and VirtualBox 4.3.2 (on ubuntu 13.10). Upgrading to 2.0.1 made them stop working and give the error you mentioned.
I tried various fixes as I described here: https://stackoverflow.com/a/20018833/2527118, but in summary what fixed my problem was to delete VM and recreate it (same source and settings) in GenyMotion. You might want to try the other fixes (less destructive) before doing that.
Andrei
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%
. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!
. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion
to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &
, &&
, or ||
are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET
or SET /?
from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
In your apache's httpd.conf, just add such a line:
AddType application/x-javascript .js
You can also use
var XLSX = require('xlsx');
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
console.log(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]))
Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.
Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
pip install --ignore-installed six
Would do the trick.
Source: github.com/pypa/pip/issues/3165
If I ommit begin - end it is error. So for me this is working (nothing else needed):
set serveroutput on;
begin
DBMS_OUTPUT.PUT_LINE('testing');
end;
For small tables DELETE
is often faster and needs less aggressive locking (for heavy concurrent load):
DELETE FROM tbl;
With no WHERE
condition.
For medium or bigger tables, go with TRUNCATE tbl
, like @Greg posted.
in my case, it was a confilict with IntelliJ , I've resolved it by building the project from command line and it worked!
for me the "workaround" solution was to remove the "_normal" from the end of the string
Check it out below:
Unfortunately, the methods you are using are unsupported in those browsers. To support my answer (this unsupportive behaviour) I have given links below.
onbeforeunload
and onunload
not working in opera
... to support this
onbeforeunload in Opera
http://www.zachleat.com/web/dont-let-the-door-hit-you-onunload-and-onbeforeunload/
Though the onunload
event doesn't work completely, you can use onunload
to show a warning if a user clicks a link to navigate away from a page with an unsaved form.
onunload
not working in safari
... to support this
https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
You could rather try using the pagehide
event in the safari browser in lieu of onunload
.
onunload
not working in firefox
... to support this
They are yet to come up with a solution in FF too
Wish you good luck cheers.
go to dosbox installation directory (on my machine that is C:\Program Files (x86)\DOSBox-0.74 ) as you see the version number is part of the installation directory name.
run "DOSBox 0.74 Options.bat"
the script starts notepad with configuration file: here change
windowresolution=1600x800
output=ddraw
(the resolution can't be changed if output=surface - that's the default).
You can use a sort function :
var myarray=[25, 8, 7, 41]
myarray.sort( function(a,b) { return b - a; } );
// 7 8 25 41
Look at http://www.javascriptkit.com/javatutors/arraysort.shtml
Since Nick's answer is deprecated by now and Rafael's comment is really useful, I want to add this as an Answer. If you want to change all factor
columns to character
use mutate_if
:
dat %>% mutate_if(is.factor, as.character)
Also other functions are allowed. I for instance used iconv
to change the encoding of all character
columns:
dat %>% mutate_if(is.character, function(x){iconv(x, to = "ASCII//TRANSLIT")})
or to substitute all NA
by 0 in numeric columns:
dat %>% mutate_if(is.numeric, function(x){ifelse(is.na(x), 0, x)})
I just figured out that for a case where the path involves the use of white space characters, for example, when I need to access the app xyz
which location is :
C:\Program Files\ab cd\xyz.exe
To run this from windows cmd prompt, you need to use
C:\"Program Files"\"ab cd"\xyz.exe
or
"C:\Program Files\ab cd\xyz.exe"
andyras is completely correct. One minor addition, try this (for example)
plot 'ls.dat' using 4:xtic(1)
This will keep your datafile in the correct order, but also preserve your version tic labels on the x-axis.
A more contemporary way of doing it on a separate thread using Tasks and Kotlin
private val mExecutor: Executor = Executors.newSingleThreadExecutor()
private fun createHttpTask(u:String): Task<String> {
return Tasks.call(mExecutor, Callable<String>{
val url = URL(u)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 3000
conn.readTimeout = 3000
val rc = conn.responseCode
if ( rc != HttpURLConnection.HTTP_OK) {
throw java.lang.Exception("Error: ${rc}")
}
val inp: InputStream = BufferedInputStream(conn.inputStream)
val resp: String = inp.bufferedReader(UTF_8).use{ it.readText() }
return@Callable resp
})
}
and now you can use it like below in many places:
createHttpTask("https://google.com")
.addOnSuccessListener {
Log.d("HTTP", "Response: ${it}") // 'it' is a response string here
}
.addOnFailureListener {
Log.d("HTTP", "Error: ${it.message}") // 'it' is an Exception object here
}
The previous answers did not work for me, but this did:
docker stop $(docker ps -q --filter ancestor=<image-name> )
EDIT: After your comments, I understand that you want to pass variable through your form.
You can do this using hidden field:
<input type='hidden' name='var' value='<?php echo "$var";?>'/>
In PHP action File:
<?php
if(isset($_POST['var'])) $var=$_POST['var'];
?>
Or using sessions: In your first page:
$_SESSION['var']=$var;
start_session();
should be placed at the beginning of your php page.
In PHP action File:
if(isset($_SESSION['var'])) $var=$_SESSION['var'];
First Answer:
You can also use $GLOBALS
:
if (isset($_POST['save_exit']))
{
echo $GLOBALS['var'];
}
Check this documentation for more informations.
values = set(map(lambda x:x[1], mylist))
newlist = [[y[0] for y in mylist if y[1]==x] for x in values]
Even though this is an old question, this way of doing it would take of many situations and seems to be robust. You need to have PHP 5.3.0 or above.
$EndDateTime = DateTime::createFromFormat('d/m/Y', "16/07/2017");
$EndDateTime->modify('+6 days');
echo $EndDateTime->format('d/m/Y');
You can have any type of format for the date string and this would work.
If your branch is local only and hasn't been pushed to the server, use
git rebase master
Otherwise, use
git merge master
You have to change the extends Activity to extends AppCompactActivity then try set and getSupportActionBar()
Rejecting the WiFi networks idea!
Sorry folks... I don't see it. Using WiFi networks around you seems to be a highly inaccurate and ineffective method of collecting data. WiFi networks these days simply don't stay long in one place.
Think about it, the WiFi networks change every day. Not to mention MiFi and Adhoc networks which are "designed" to be mobile and travel with the users. Equipment breaks, network settings change, people move... Relying on "WiFi Networks" in your area seems highly inaccurate and in the end may not even offer a significant improvement in granularity over IP lookup.
I think the idea that iPhone users are "scanning and sending" the WiFi survey data back to google, and the wardriving, perhaps in conjunction with the Google Maps "Street View" mapping might seem like a very possible method of collecting this data however, in practicality, it does not work as a business model.
Oh and btw, I forgot to mention in my prior post... when I originally pulled my location the time I was pinpointed "precisely" on the map I was connecting to a router from my desktop over an ethernet connection. I don't have a WiFi card on my desktop.
So if that "nearby WiFi networks" theory was true... then I shouldn't have been able to pinpoint my location with such precision.
I'll call my ISP, SKyrim, and ask them as to whether they share their network topology to enable geolocation on their networks.
Above mentioned issue happened in my local system. Check in sql server configuration manager.
Step 1:
SQL server Network configuration
step 2:
.. after I made changes the sql server browser started working
Following many hours of search and testing i found following solution(by implementing different SO solutions) here it what didn't failed in any case i was getting crash.
Runnable runnable = new Runnable() {
@Override
public void run() {
//displayPopup,progress dialog or what ever action. example
ProgressDialogBox.setProgressBar(Constants.LOADING,youractivityName.this);
}};
Where logcat is indicating the crash is happening.. start a runnable .in my case at receiving broadcast.
runOnUiThread(new Runnable() {
@Override
public void run() {
if(!isFinishing()) {
new Handler().postAtTime(runnable,2000);
}
}
});
Swift 3.1 You can do this by implementing the delegate method of UINavigationController.
func navigationController(_ navigationController: UINavigationController,
willShow viewController: UIViewController, animated: Bool) {
/** It'll hide the Title with back button only,
** we'll still get the back arrow image and default functionality.
*/
let item = UIBarButtonItem(title: " ", style: .plain, target: nil,
action: nil)
viewController.navigationItem.backBarButtonItem = item
}
One more approach, what you can do is
// get your optionals first
Optional<String> p1 = otherObject.getP1();
Optional<BigInteger> p2 = otherObject.getP2();
// bind values to a function
Supplier<Integer> calculatedValueSupplier = () -> { // your logic here using both optional as state}
Once you have built a function(supplier in this case) you will be able to pass this around as any other variable and would be able to call it using
calculatedValueSupplier.apply();
The idea here being whether you have got optional value or not will be internal detail of your function and will not be in parameter. Thinking functions when thinking about optional as parameter is actually very useful technique that I have found.
As to your question whether you should actually do it or not is based on your preference, but as others said it makes your API ugly to say the least.
In my case, my dataframe has the following characteristics
<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Close 3038 non-null float64
dtypes: float64(1)
memory usage: 47.5+ KB
The first option data.index = pd.to_datetime(data.index)
returned
ParserError: String does not contain a date: ParserError: String does not contain a date:
The second option: data.index.to_datetime()
returned
AttributeError: 'Index' object has no attribute 'to_datetime'
It returned
Another option I have tested is. data.index = pd.to_datetime(data.index)
It returned: ParserError: String does not contain a date:
What could be my problem? Thanks
In foreach
loop instead of carBootSaleList
use carBootSaleList.data
.
You probably do not need answer anymore, but it could help someone.
Use numpy.apply_along_axis()
. Assuming your matrix is 2D, you can use like:
import numpy as np
mymatrix = np.matrix([[11,12,13],
[21,22,23],
[31,32,33]])
def myfunction( x ):
return sum(x)
print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]
I've tried most answers in this thread, no luck. Ended up with this:
protected void btnLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.Initialize();
var fat = new FormsAuthenticationTicket(1, "", DateTime.Now, DateTime.Now.AddMinutes(-30), false, string.Empty, FormsAuthentication.FormsCookiePath);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)));
FormsAuthentication.RedirectToLoginPage();
}
Found it here: http://forums.asp.net/t/1306526.aspx/1
Bassed on this page here:
I modified it so you can use ddbb in diferent hosts.
#!/bin/sh echo "Usage: dbdiff [user1:pass1@dbname1:host] [user2:pass2@dbname2:host] [ignore_table1:ignore_table2...]" dump () { up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:}; mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname -h $host $table > $2 } rm -f /tmp/db.diff # Compare up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:}; for table in `mysql -u $user -p$pass $dbname -h $host -N -e "show tables" --batch`; do if [ "`echo $3 | grep $table`" = "" ]; then echo "Comparing '$table'..." dump $1 /tmp/file1.sql dump $2 /tmp/file2.sql diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff else echo "Ignored '$table'..." fi done less /tmp/db.diff rm -f /tmp/file1.sql /tmp/file2.sql
You could also try something like this:
input[type="radio"] {_x000D_
margin-top: -1px;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<label class="child"><input id = "warm" type="radio" name="weathertype" value="warm" checked> Warm<br></label>_x000D_
<label class="child1"><input id = "cold" type="radio" name="weathertype" value="cold" checked> Cold<br></label>
_x000D_
In System.Diagnostics
,
Debug.Write()
Debug.WriteLine()
etc. will print to the Output window in VS.
if (pathname.substring(0, 6) == "/sub/1") {
// ...
}
Slight modification of Laurynas' plugin based on Igor's code. This accommodates possible labels associated with the radio buttons being targeted:
(function ($) {
$.fn.uncheckableRadio = function () {
return this.each(function () {
var radio = this;
$('label[for="' + radio.id + '"]').add(radio).mousedown(function () {
$(radio).data('wasChecked', radio.checked);
});
$('label[for="' + radio.id + '"]').add(radio).click(function () {
if ($(radio).data('wasChecked'))
radio.checked = false;
});
});
};
})(jQuery);
Über
is the German word for above
or over
(it's actually cognate with the English over
).
Hence, in this context, an uber-jar is an "over-jar", one level up from a simple JAR (a), defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of "beyond the normal".
The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.
All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies. And so on.
(a) I probably shouldn't have to explain what a JAR is to a Java developer but I'll include it for completeness. It's a Java archive, basically a single file that typically contains a number of Java class files along with associated metadata and resources.
Using null
is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.
As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:
if (x==2) doSomething;
else doSomethingElse
or, in your case,
if (x==2) doSomething;
For me, a hint to wrap the troubled element in another HTML tag helped. However I also needed to add a key to that HTML tag. For example:
// Didn't work
<div>
<TroubledComponent/>
</div>
// Worked
<div key='uniqueKey'>
<TroubledComponent/>
</div>
Do you really want to blacklist specific characters or rather whitelist the allowed charachters?
I assume that you actually want the latter. This is pretty simple (add any additional symbols to whitelist into the [\-]
group):
^(?:\p{L}\p{M}*|[\-])*$
Edit: Optimized the pattern with the input from the comments
df <- data.frame(a = 1:2, b = letters[1:2])
df[rep(seq_len(nrow(df)), each = 2), ]
for (int j=0; j<test.length; j++) {
System.out.format("%02X ", test[j]);
}
System.out.println();
Try to include length > 0 as well.
column1 is not NULL AND column1 <> '' AND length(column1) > 0
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
Most of these answers are either far too complicated or don't seem to work for me (e.g. System.Windows.Input doesn't seem to exist). Then I found some sample code which works fine: http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state
In case the page disappears in the future I am posting the relevant source code below:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace MouseKeyboardStateTest
{
public abstract class Keyboard
{
[Flags]
private enum KeyStates
{
None = 0,
Down = 1,
Toggled = 2
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern short GetKeyState(int keyCode);
private static KeyStates GetKeyState(Keys key)
{
KeyStates state = KeyStates.None;
short retVal = GetKeyState((int)key);
//If the high-order bit is 1, the key is down
//otherwise, it is up.
if ((retVal & 0x8000) == 0x8000)
state |= KeyStates.Down;
//If the low-order bit is 1, the key is toggled.
if ((retVal & 1) == 1)
state |= KeyStates.Toggled;
return state;
}
public static bool IsKeyDown(Keys key)
{
return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
}
public static bool IsKeyToggled(Keys key)
{
return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
}
}
}
<!-- xaml code-->
<Grid>
<ComboBox Name="cmbData" SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
<Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
</Grid>
//student Class
public class Student
{
public int Id { set; get; }
public string name { set; get; }
}
//set 2 properties in MainWindow.xaml.cs Class
public ObservableCollection<Student> studentInfo { set; get; }
public Student SelectedstudentInfo { set; get; }
//MainWindow.xaml.cs Constructor
public MainWindow()
{
InitializeComponent();
bindCombo();
this.DataContext = this;
cmbData.ItemsSource = studentInfo;
}
//method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
public void bindCombo()
{
ObservableCollection<Student> studentList = new ObservableCollection<Student>();
studentList.Add(new Student { Id=0 ,name="==Select=="});
studentList.Add(new Student { Id = 1, name = "zoyeb" });
studentList.Add(new Student { Id = 2, name = "siddiq" });
studentList.Add(new Student { Id = 3, name = "James" });
studentInfo=studentList;
}
//button click to get selected student MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student = SelectedstudentInfo;
if(student.Id ==0)
{
MessageBox.Show("select name from dropdown");
}
else
{
MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
}
}
I think simplest would be use numpy
here. For example you can read a file as bytes and then expand it to bits easily like this:
Bytes = numpy.fromfile(filename, dtype = "uint8")
Bits = numpy.unpackbits(Bytes)
In general, you can't do this. UTF-8 is capable of encoding any Unicode code point. ISO-8859-1 can handle only a tiny fraction of them. So, transcoding from ISO-8859-1 to UTF-8 is no problem. Going backwards from UTF-8 to ISO-8859-1 will cause "replacement characters" (�) to appear in your text when unsupported characters are found.
To transcode text:
byte[] latin1 = ...
byte[] utf8 = new String(latin1, "ISO-8859-1").getBytes("UTF-8");
or
byte[] utf8 = ...
byte[] latin1 = new String(utf8, "UTF-8").getBytes("ISO-8859-1");
You can exercise more control by using the lower-level Charset
APIs. For example, you can raise an exception when an un-encodable character is found, or use a different character for replacement text.
Here's a method using display:flex
:
.container {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
display: flex;_x000D_
position: fixed;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>centered text!</div>_x000D_
</div>
_x000D_
To create global gitignore from scratch:
$ cd ~
$ touch .gitignore_global
$ git config --global core.excludesfile ~/.gitignore_global
C:/Users/User
.gitignore_global
extensionIn the MongoDB shell:
db.getCollection('sensorevents').find({from:{$gt: new ISODate('2015-08-30 16:50:24.481Z')}})
In my nodeJS code ( using Mongoose )
SensorEvent.Model.find( {
from: { $gt: new Date( SensorEventListener.lastSeenSensorFrom ) }
} )
I am querying my sensor events collection to return values where the 'from' field is greater than the given date
TypeScript 2.1 introduced elegant way to handle this issue.
const key: (keyof ISomeObject) = 'secondKey';
const secondValue: string = someObject[key];
We can access all object property names during compilation phase by keyof
keyword (see changelog).
You only need to replace string
variable type with keyof ISomeObject
.
Now compiler knows key
variable is allowed to contain only property names from ISomeObject
.
Full example:
interface ISomeObject {
firstKey: string;
secondKey: string;
thirdKey: number;
}
const someObject: ISomeObject = {
firstKey: 'firstValue',
secondKey: 'secondValue',
thirdKey: 3
};
const key: (keyof ISomeObject) = 'secondKey';
const secondValue: string = someObject[key];
// You can mix types in interface, keyof will know which types you refer to.
const keyNumber: (keyof ISomeObject) = 'thirdKey';
const numberValue: number = someObject[keyNumber];
Live code on typescriptlang.org (set noImplicitAny
option)
Further reading with more keyof
usages.
There is a much easier way to run Python, and it doesn't need any configuration:
If you want to add the Python path, you could go to File ? Preference ? Settings, and add the Python path like below:
"code-runner.executorMap":
{
"python": "\"C:\\Program Files\\Python35\\python.exe\" -u"
}
In case you have installed the Python extension and manually set your interpreter already, you could configure your settings.json file as follows:
{
"python.pythonPath": "C:\\\\python36\\\\python36.exe",
"code-runner.executorMap":
{
"python": "$pythonPath -u $fullFileName"
}
}
As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>
).
You want to deserialize into a single RootObject
.
This seems to work for me.
def make_Ramp( ramp_colors ):
from colour import Color
from matplotlib.colors import LinearSegmentedColormap
color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
plt.figure( figsize = (15,3))
plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
plt.xticks([])
plt.yticks([])
return color_ramp
custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] )
You miss the class declaration.
public class DerivativeQuiz{
public static void derivativeQuiz(String args[]){ ... }
}
Well you certainly can use a List<List<string>>
where you'd then write:
List<string> track = new List<string>();
track.Add("2349");
track.Add("The Prime Time of Your Life");
// etc
matrix.Add(track);
But why would you do that instead of building your own class to represent a track, with Track ID, Name, Artist, Album, Play Count and Skip Count properties? Then just have a List<Track>
.
I had the same problem. Coudn't resolve google.com. There was a bug somewhere in php fpm, which i am using. Restarting php-fpm solved it for me.
I don't agree with the statement about [...] HTTP referrer leakage (an external image in the target page might leak the password) in Slough's response.
The HTTP 1.1 RFC explicitly states:
Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP request if the referring page was transferred with a secure protocol.
Anyway, server logs and browser history are more than sufficient reasons not to put sensitive data in the query string.
Here is an example of the working code.
template<typename T>
using toStringFn = decltype(std::declval<const T>().toString());
template <class T, toStringFn<T>* = nullptr>
std::string optionalToString(const T* obj, int)
{
return obj->toString();
}
template <class T>
std::string optionalToString(const T* obj, long)
{
return "toString not defined";
}
int main()
{
A* a;
B* b;
std::cout << optionalToString(a, 0) << std::endl; // This is A
std::cout << optionalToString(b, 0) << std::endl; // toString not defined
}
toStringFn<T>* = nullptr
will enable the function which takes extra int
argument which has a priority over function which takes long
when called with 0
.
You can use the same principle for the functions which returns true
if function is implemented.
template <typename T>
constexpr bool toStringExists(long)
{
return false;
}
template <typename T, toStringFn<T>* = nullptr>
constexpr bool toStringExists(int)
{
return true;
}
int main()
{
A* a;
B* b;
std::cout << toStringExists<A>(0) << std::endl; // true
std::cout << toStringExists<B>(0) << std::endl; // false
}
You can add as many headers as you like by calling addHeaderView() multiple times. You have to do it before setting the adapter to the list view.
And yes you can add header something like this way:
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);
An example usage:
>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world
The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.
This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray
:
>>> s = bytearray(1000000) # a million zeroed bytes
>>> t = buffer(s, 1) # slice cuts off the first byte
>>> s[1] = 5 # set the second element in s
>>> t[0] # which is now also the first element in t!
'\x05'
This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.
Note that buffer
has been replaced by the better named memoryview
in Python 3, though you can use either in Python 2.7.
Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.
I used this. Similar idea to other answers, but didn't see the exact approach anywhere :)
System.out.println(Integer.toBinaryString((b & 0xFF) + 0x100).substring(1));
0xFF
is 255, or 11111111
(max value for an unsigned byte).
0x100
is 256, or 100000000
The &
upcasts the byte to an integer. At that point, it can be anything from 0
-255
(00000000
to 11111111
, I excluded the leading 24 bits). + 0x100
and .substring(1)
ensure there will be leading zeroes.
I timed it compared to João Silva's answer, and this is over 10 times faster. http://ideone.com/22DDK1 I didn't include Pshemo's answer as it doesn't pad properly.
I hope it will help someone ! (works on Angular 6)
I had to add lots of select/options dynamically and following worked for me:
<div *ngFor="let option of model.q_options; let ind=index;">
<select
[(ngModel)]="model.q_options[ind].type"
[ngModelOptions]="{standalone: true}"
>
<option
*ngFor="let object of objects"
[ngValue]="object.type"
[selected]="object.type === model.q_options[ind].type"
>{{object.name}}
</option>
</select>
<div [ngSwitch]="model.q_options[ind].type">
( here <div *ngSwitchCase="'text' or 'imagelocal' or etc."> is used to add specific input forms )
</div>
</div>
and in *.ts
// initial state of the model
// q_options in html = NewOption and its second argument is option type
model = new NewQuestion(1, null, 2,
[
new NewOption(0, 'text', '', 1),
new NewOption(1, 'imagelocal', '', 1)
]);
// dropdown options
objects = [
{type: 'text', name: 'text'},
{type: 'imagelocal', name: 'image - local file'},
{type: 'imageurl', name: 'image URL'}
( and etc.)
];
When user adds one more 'input option' (pls do not confuse 'input option' with select/options - select/options are static here) specific select/option, selected by the user earlier, is preserved on each/all dynamically added 'input option's select/options.
#!/usr/bin/env sh
this is how git bash knows a file is executable. chmod a+x
does nothing in gitbash. (Note: any "she-bang" will work, e.g. #!/bin/bash
, etc.)
For the case I met, I found there are missing modules after make. So I did the following:
Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.
The long way is to write custom JsonConverter
s to handle (de)serialization by manually checking and setting the type property.
A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:
[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
public virtual string Sound { get; }
public string Color { get; set; }
}
public class Dog : Animal
{
public override string Sound { get; } = "Bark";
public string Breed { get; set; }
}
public class Cat : Animal
{
public override string Sound { get; } = "Meow";
public bool Declawed { get; set; }
}
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
Just need click button 'AppTheme', and choose 'Manifest Themes'. It works in most cases.
Please make use of the code below to display images inline:
<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>
You must be prompted in your s4 screen to authorize that computer. You can tell it to remember it. This is for security reasons, occurring in Android 4.4+
You could return the value using return JsonConvert.SerializeObject(objName); And send it to the front end
You could:
SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1
INTO res;
This happens to work, because your query has an aggregate function and consequently always returns a row, even if nothing is found in the underlying table.
Plain queries without aggregate would return no row in such a case. COALESCE
would never be called and couldn't save you. While dealing with a single column we can wrap the whole query instead:
SELECT COALESCE( (SELECT columnA FROM my_table WHERE ID = 1), 0)
INTO res;
Works for your original query as well:
SELECT COALESCE( (SELECT SUM(columnA) FROM my_table WHERE columnB = 1), 0)
INTO res;
More about COALESCE()
in the manual.
More about aggregate functions in the manual.
More alternatives in this later post:
The only guaranteed secure method of retrieving the current domain is to store it in a secure location yourself.
Most frameworks take care of storing the domain for you, so you will want to consult the documentation for your particular framework. If you're not using a framework, consider storing the domain in one of the following places:
Secure methods of storing the domain | Used By |
---|---|
A config file | Joomla, Drupal/Symfony |
The database | WordPress |
An environmental variable | Laravel |
A service registry | Kubernetes DNS |
Hackers can make the following variables output whatever domain they want. This can lead to cache poisoning and barely noticeable phishing attacks.
$_SERVER['HTTP_HOST']
This gets the domain from the request headers which are open to manipulation by hackers. Same with:
$_SERVER['SERVER_NAME']
This one can be made better if the Apache setting usecanonicalname is turned off; in which case $_SERVER['SERVER_NAME']
will no longer be allowed to be populated with arbitrary values and will be secure. This is, however, non-default and not as common of a setup.
Below is how you can get the current domain in the following frameworks/systems:
WordPress
$urlparts = parse_url(home_url());
$domain = $urlparts['host'];
If you're constructing a URL in WordPress, just use home_url or site_url, or any of the other URL functions.
Laravel
request()->getHost()
The request()->getHost
function is inherited from Symfony, and has been secure since the 2013 CVE-2013-4752 was patched.
Drupal
The installer does not yet take care of making this secure (issue #2404259). But in Drupal 8 there is documentation you can you can follow at Trusted Host Settings to secure your Drupal installation after which the following can be used:
\Drupal::request()->getHost();
Other frameworks
Feel free to edit this answer to include how to get the current domain in your favorite framework. When doing so, please include a link to the relevant source code or to anything else that would help me verify that the framework is doing things securely.
Exploitation examples:
Cache poisoning can happen if a botnet continuously requests a page using the wrong hosts header. The resulting HTML will then include links to the attackers website where they can phish your users. At first the malicious links will only be sent back to the hacker, but if the hacker does enough requests, the malicious version of the page will end up in your cache where it will be distributed to other users.
A phishing attack can happen if you store links in the database based on the hosts header. For example, let say you store the absolute URL to a user's profiles on a forum. By using the wrong header, a hacker could get anyone who clicks on their profile link to be sent a phishing site.
Password reset poisoning can happen if a hacker uses a malicious hosts header when filling out the password reset form for a different user. That user will then get an email containing a password reset link that leads to a phishing site. Another more complex form of this skips the user having to do anything by getting the email to bounce and resend to one of the hacker's SMTP servers (for example CVE-2017-8295.)
Here are some more malicious examples
Additional Caveats and Notes:
$_SERVER['SERVER_NAME']
is populated with the same header $_SERVER['HTTP_HOST']
would have used anyways (plus the port). This is Apache's default setup. If you or devops turns this on then you're okay -- ish -- but do you really want to rely on a separate team, or yourself three years in the future, to keep what would appear to be a minor configuration at a non-default value? Even though this makes things secure, I would caution against relying on this setup.$_SERVER['SERVER_NAME']
will not return the current domain, but will return the value of the serverName directive.Little Rant:
This question received hundreds of thousands of views without a single mention of the security problems at hand! It shouldn't be this way, but just because a Stack Overflow answer is popular, that doesn't mean it is secure.
You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".
Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.
The relevant paragraph:
Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.
This makes lots of sense.
For your specific question.. the o
in the <o:p>
means "Office namespace" so anything following the o:
in a tag means "I'm part of Office namespace" - in case of <o:p>
it just means paragraph, the equivalent of the ordinary <p>
tag.
I assume that every HTML tag has its Office "equivalent" and they have more.
You should change the line this.MyDateTime = myNewDT.MyDateTime.Value;
to just this.MyDateTime = myNewDT.MyDateTime;
The exception you were receiving was thrown in the .Value
property of the Nullable DateTime
, as it is required to return a DateTime
(since that's what the contract for .Value
states), but it can't do so because there's no DateTime
to return, so it throws an exception.
In general, it is a bad idea to blindly call .Value
on a nullable type, unless you have some prior knowledge that that variable MUST contain a value (i.e. through a .HasValue
check).
EDIT
Here's the code for DateTimeExtended
that does not throw an exception:
class DateTimeExtended
{
public DateTime? MyDateTime;
public int? otherdata;
public DateTimeExtended() { }
public DateTimeExtended(DateTimeExtended other)
{
this.MyDateTime = other.MyDateTime;
this.otherdata = other.otherdata;
}
}
I tested it like this:
DateTimeExtended dt1 = new DateTimeExtended();
DateTimeExtended dt2 = new DateTimeExtended(dt1);
Adding the .Value
on other.MyDateTime
causes an exception. Removing it gets rid of the exception. I think you're looking in the wrong place.
OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom"
instead of app:showAsAction="ifRoom"
since i am using v7 library.
However the title is coming at center of extended toolbar. How to make it appear at the top?
I was also having this same error but hopefully after spending 1 day on this error i have got this solution and it got started perfectly and i also hope this works for you guys also...
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
The above answer didn't work with Angular 6. So following is how I resolved it. Lets say this is how I defined my input box -
<input type="number" id="myTextBox" name="myTextBox"_x000D_
[(ngModel)]="response.myTextBox"_x000D_
#myTextBox="ngModel">
_x000D_
To check if the field is empty or not this should be the script.
<div *ngIf="!myTextBox.value" style="color:red;">_x000D_
Your field is empty_x000D_
</div>
_x000D_
Do note the subtle difference between the above answer and this answer. I have added an additional attribute .value
after my input name myTextBox
.
I don't know if the above answer worked for above version of Angular, but for Angular 6 this is how it should be done.
Some more explanation on why this check works; when there is no value present in the input box the default value of myTextBox.value
will be undefined
. As soon as you enter some text, your text becomes the new value of myTextBox.value
.
When your check is !myTextBox.value
it is checking that the value is undefined or not, it is equivalent to myTextBox.value == undefined
.
A more simple English explanation: jQuery is something that makes AJAX and other JavaScript tasks much easier.
Functional Programming is a form of declarative programming, which describe the logic of computation and the order of execution is completely de-emphasized.
Problem: I want to change this creature from a horse to a giraffe.
Each item can be run in any order to produce the same result.
Imperative Programming is procedural. State and order is important.
Problem: I want to park my car.
Each step must be done in order to arrive at desired result. Pulling into the garage while the garage door is closed would result in a broken garage door.
For ASP.NET Core 3.1 you can follow this documentation:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1
When you create a new ASP.NET Core 3.1 project you will have the following configuration line in Program.cs
:
Host.CreateDefaultBuilder(args)
This enables the following:
This means you can inject IConfiguration
and fetch values with a string key, even nested values. Like IConfiguration ["Parent:Child"];
Example:
appsettings.json
{
"ApplicationInsights":
{
"Instrumentationkey":"putrealikeyhere"
}
}
WeatherForecast.cs
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration _configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var key = _configuration["ApplicationInsights:InstrumentationKey"];
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
Initially, Grab the .offset position of the element and calculate its relative position with respect to window
Refer :
1. offset
2. scroll
3. scrollTop
You can give it a try at this fiddle
Following few lines of code explains how this can be solved
when .scroll event is performed, we calculate the relative position of the element with respect to window object
$(window).scroll(function () {
console.log(eTop - $(window).scrollTop());
});
when scroll is performed in browser, we call the above event handler function
function log(txt) {_x000D_
$("#log").html("location : <b>" + txt + "</b> px")_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
var eTop = $('#element').offset().top; //get the offset top of the element_x000D_
log(eTop - $(window).scrollTop()); //position of the ele w.r.t window_x000D_
_x000D_
$(window).scroll(function() { //when window is scrolled_x000D_
log(eTop - $(window).scrollTop());_x000D_
});_x000D_
});
_x000D_
#element {_x000D_
margin: 140px;_x000D_
text-align: center;_x000D_
padding: 5px;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
border: 1px solid #0099f9;_x000D_
border-radius: 3px;_x000D_
background: #444;_x000D_
color: #0099d9;_x000D_
opacity: 0.6;_x000D_
}_x000D_
#log {_x000D_
position: fixed;_x000D_
top: 40px;_x000D_
left: 40px;_x000D_
color: #333;_x000D_
}_x000D_
#scroll {_x000D_
position: fixed;_x000D_
bottom: 10px;_x000D_
right: 10px;_x000D_
border: 1px solid #000;_x000D_
border-radius: 2px;_x000D_
padding: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="log"></div>_x000D_
_x000D_
<div id="element">Hello_x000D_
<hr>World</div>_x000D_
<div id="scroll">Scroll Down</div>
_x000D_
setInterval()
setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().
if you want to loop code for animations or clocks Then use setInterval.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
setTimeout()
setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.
Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.
You can try using: netstat -a
to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp
On mac you will start your activemq using:
$ACTMQ_HOME/bin/activemq start
Or if your config file (activemq.xml ) if located in another location you can use:
$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}
In your case the executable is under: bin/macosx/activemq
so you need to use: $ACTMQ_HOME/bin/macosx/activemq start
I'd do (added caching):
var bbx = $("#blackbox");
bbx.css('background-color') === 'rgb(255, 192, 203)' ? bbx.css('background','black') : bbx.css('background','pink')
wroking fiddle (new AGAIN): http://jsfiddle.net/6nar4/37/
I had to change the first operator as css()
returns the rgb value of the color
Parse Querystring into a NameValueCollection. Remove an item. And use the toString to convert it back to a querystring.
using System.Collections.Specialized;
NameValueCollection filteredQueryString = System.Web.HttpUtility.ParseQueryString(Request.QueryString.ToString());
filteredQueryString.Remove("appKey");
var queryString = '?'+ filteredQueryString.ToString();
By using typed arrays, you can store arrays of these types:
For example:
?var array = new Uint8Array(100);
array[42] = 10;
alert(array[42]);?
See it in action here.
You can use a RegularExpression validator. The ValidationExpression property has a button you can press in Visual Studio's property's panel that gets lists a lot of useful expressions. The one they use for email addresses is:
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
qx.Class.define('FpsCounter', {
extend: qx.core.Object
,properties: {
}
,events: {
}
,construct: function(){
this.base(arguments);
this.restart();
}
,statics: {
}
,members: {
restart: function(){
this.__frames = [];
}
,addFrame: function(){
this.__frames.push(new Date());
}
,getFps: function(averageFrames){
debugger;
if(!averageFrames){
averageFrames = 2;
}
var time = 0;
var l = this.__frames.length;
var i = averageFrames;
while(i > 0){
if(l - i - 1 >= 0){
time += this.__frames[l - i] - this.__frames[l - i - 1];
}
i--;
}
var fps = averageFrames / time * 1000;
return fps;
}
}
});