In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Finally found a solution for this by adding this line to gradle.properties.
org.gradle.jvmargs=-Xmx4608m
For anybody facing a similar issue at this point in time, all you need to do is update your Android Studio to the latest version
Extending Yoni Gibbs's answer, if you are in an android project using retrofit and configure serialization with Jackson you can do these things in order to deserialization works as expected with kotlin's data class.
In your build gradle import:
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.+"
Then, your implementation of retrofit:
val serverURL = "http://localhost:8080/api/v1"
val objectMapper = ObjectMapper()
objectMapper.registerModule(KotlinModule())
//Only if you are using Java 8's Time API too, require jackson-datatype-jsr310
objectMapper.registerModule(JavaTimeModule())
Retrofit.Builder()
.baseUrl(serverURL)
.client(
OkHttpClient.Builder()
.readTimeout(1, TimeUnit.MINUTES)//No mandatory
.connectTimeout(1, TimeUnit.MINUTES)//No mandatory
.addInterceptor(UnauthorizedHandler())//No mandatory
.build())
.addConverterFactory(
JacksonConverterFactory.create(objectMapper)
)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
Data class:
@JsonIgnoreProperties(ignoreUnknown = true)
data class Task(val id: Int,
val name: String,
@JsonSerialize(using = LocalDateTimeSerializer::class)
@JsonDeserialize(using = LocalDateTimeDeserializer::class)
val specificDate: LocalDateTime?,
var completed: Boolean,
val archived: Boolean,
val taskListId: UUID?
CORS issue can be simply resolved by following this:
Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"
Spring Boot 2.0.*
or aboveIf you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary
, because various auto-configurations down the road expect to be able to get one by type.
If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
return firstDataSourceProperties().initializeDataSourceBuilder().build();
}
@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
return DataSourceBuilder.create().type(BasicDataSource.class).build();
}
firstDataSourceProperties
has to be flagged as@Primary
so that the database initializer feature uses your copy (if you use the initializer).
And your application.propoerties
will look something like this:
app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver
app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver
The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.
Not sure if this solution works for you or not but just want to heads you up on compiler and build tools version compatibility issues.
This could be because of Java and Gradle version mismatch.
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
Gradle 4.4 is compatible with only Java 7 and 8. So, point your global variable JAVA_HOME to Java 7 or 8.
In mac, add below line to your ~/.bash_profile
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
You can have multiple java versions. Just change the JAVA_HOME path based on need. You can do it easily, check this
The Actual solution of this problem is changing first line in web.php
Just replace Welcome route with following route
Route::view('/', 'welcome');
If still getting same error than you probab
I also have the same error. I have updated the jackson library version and error has gone.
<!-- Jackson to convert Java object to Json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
</dependencies>
and also check your data classes that have you created getters and setters for all the properties.
For unit test:
spyOn(component.form, 'valid').and.returnValue(true);
in your CFG file please change the hibernate dialect
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
Delete android sdk "tools" folder : [Your Android SDK root]/tools -> tools
Download SDK Tools: http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip
Extract that to Android SDK root
Build your project
After that it didn't work for me yet, I had to
Go to the Java archives (http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html)
Search for the jdk-8u131 release.
Accept the Licence Agreement,make an account and download the release.
Install it and define it as JDK path in Unity.
source : https://www.reddit.com/r/Unity3D/comments/77azfb/i_cant_get_unity_to_build_run_my_game/
In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
1-Delete the migration file. 2-connect to your database and drop the table created by the migration. 3-recreate the file of the migration with the the right sql.
A better approach is to let Retrofit generate POJO for you from the json (using gson
). First thing is to add .addConverterFactory(GsonConverterFactory.create())
when creating your Retrofit
instance. For example, if you had a User
java class (such as shown below) that corresponded to your json, then your retrofit api could return Call<User>
class User {
private String id;
private String Username;
private String Level;
...
}
I resolved this issue by Adding implements Serializable in the Model.
@Entity
@Table(name="Model_Rest")
@IdClass(Model_Rest.class)
public class Model_Rest implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
//@GeneratedValue(strategy = GenerationType.AUTO)
//@Column(columnDefinition="id")
@Id
private String login;
@Id
private String password;
@Autowired
public String getLogin() {
return login;
}
@Autowired
public void setLogin(String login) {
this.login = login;
}
@Autowired
public String getPassword() {
return password;
}
@Autowired
public void setPassword(String password) {
this.password = password;
}
public Model_Rest() {
// TODO Auto-generated constructor stub
}
public Model_Rest(String login, String password) {
this.login = login;
this.password = password;
}
@Override
public String toString() {
return "Model_Rest [login=" + login + ", password=" + password + "]";
}
}
This is a well-known issue and based on this answer you could add setLenient
:
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Now, if you add this to your retrofit, it gives you another error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:
{
android:[
{ ver:"1.5", name:"Cupcace", api:"Api Level 3" }
...
]
}
For better comprehension, compare your response with Github api.
Suggestion: to find out what's going on to your request/response
add HttpLoggingInterceptor
in your retrofit.
Based on this answer your ServiceHelper would be:
private ServiceHelper() {
httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.interceptors().add(interceptor);
Retrofit retrofit = createAdapter().build();
service = retrofit.create(IService.class);
}
Also don't forget to add:
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
For me the only thing that works is to add to repositories
maven {
url "https://maven.google.com"
}
It should look like this:
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.
I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.
After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.
It's incorrect to use zeros in date or in datetime, just put null instead of zeros.
To me it happened in DogController
that autowired DogService
that autowired DogRepository
. Dog
class used to have field name
but I changed it to coolName
, but didn't change methods in DogRepository
: Dog findDogByName(String name)
. I change that method to Dog findDogByCoolName(String name)
and now it works.
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
you must stop another running app involved with especial database table ... like running java API in other module or other project is not terminated .. so terminate running.
starting the hive metastore service worked for me. First, set up the database for hive metastore:
$ hive --service metastore
Second, run the following commands:
$ schematool -dbType mysql -initSchema
$ schematool -dbType mysql -info
https://cwiki.apache.org/confluence/display/Hive/Hive+Schema+Tool
also try to increase gradle version in your project's build.gradle. It helped me
I got that error message in code line containing SqlConnection.Open()
running my .NET code as x64 application. Running as x86 causing no errors.
Solution was to deactivate the Force protocol encryption
option for TCP/IP in
%windir%\System32\cliconfg.exe
When I add @ComponentScan("com.firstday.spring.boot.services")
or scanBasePackages{"com.firstday.spring.boot.services"}
jsp is not loaded. So when I add the parent package of project in @SpringBootApplication class it's working fine in my case
Code Example:-
package com.firstday.spring.boot.firstday;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.firstday.spring.boot"})
public class FirstDayApplication {
public static void main(String[] args) {
SpringApplication.run(FirstDayApplication.class, args);
}
}
Another approach is by using FormBody.Builder()
.
Here's an example of callback:
Callback loginCallback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
try {
Log.i(TAG, "login failed: " + call.execute().code());
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// String loginResponseString = response.body().string();
try {
JSONObject responseObj = new JSONObject(response.body().string());
Log.i(TAG, "responseObj: " + responseObj);
} catch (JSONException e) {
e.printStackTrace();
}
// Log.i(TAG, "loginResponseString: " + loginResponseString);
}
};
Then, we create our own body:
RequestBody formBody = new FormBody.Builder()
.add("username", userName)
.add("password", password)
.add("customCredential", "")
.add("isPersistent", "true")
.add("setCookie", "true")
.build();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(this)
.build();
Request request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
Finally, we call the server:
client.newCall(request).enqueue(loginCallback);
From stack trace:
HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.
The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.
Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.
otherwise, your maximum connections 'at a time' requirement is higher than 20 !
On your command prompt type sqllocaldb start
Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />
This error is because of multiple project having the offending resources.
Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
The important part is this:
Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];
due to:
nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
According to this log, Spring could not find your MemberPointSummaryDAOImpl
class.
I had exact same error, I was not giving base package. Giving correct base package,ressolved it.
package com.ymc.backend.ymcbe;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages="com.ymc.backend")
public class YmcbeApplication {
public static void main(String[] args) {
SpringApplication.run(YmcbeApplication.class, args);
}
}
Note: not including .controller @ComponentScan(basePackages="com.ymc.backend.controller") because i have many other component classes which my project does not scan if i just give .controller
Here is my controller sample:
package com.ymc.backend.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin
@RequestMapping(value = "/user")
public class UserController {
@PostMapping("/sendOTP")
public String sendOTP() {
return "OTP sent";
};
}
request.getSession(true)
and request.getSession()
both do the same thing, but if we use
request.getSession(false)
it will return null
if session object not created yet.
Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.
OpenSessionInViewFilter
calls the openSession
method of the underlying SessionFactory
and obtains a new Session
.Session
is bound to the TransactionSynchronizationManager
.OpenSessionInViewFilter
calls the doFilter
of the javax.servlet.FilterChain
object reference and the request is further processedDispatcherServlet
is called, and it routes the HTTP request to the underlying PostController
.PostController
calls the PostService
to get a list of Post
entities.PostService
opens a new transaction, and the HibernateTransactionManager
reuses the same Session
that was opened by the OpenSessionInViewFilter
.PostDAO
fetches the list of Post
entities without initializing any lazy association.PostService
commits the underlying transaction, but the Session
is not closed because it was opened externally.DispatcherServlet
starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.OpenSessionInViewFilter
can close the Session
, and the underlying database connection is released as well.At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.
The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection
as read-only which would allow the database server to avoid writing to the transaction log.
There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.
The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize
for fetching associations in batches, and FetchMode.SUBSELECT
to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.
Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.
Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.
So, make sure that in the application.properties
configuration file, you have the following entry:
spring.jpa.open-in-view=false
This will disable OSIV so that you can handle the LazyInitializationException
the right way.
Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.
Because of old version I got this error. Then I changed to this version n error gone Using maven my pom.xml
<properties>
...
<jackson.version>2.5.2</jackson.version>
</properties>
<dependencies>
...
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
my old version was '2.2.3'
Well, you're getting a java.lang.NoClassDefFoundError
. In your pom.xml
, hibernate-core
version is 3.3.2.GA
and declared after hibernate-entitymanager
, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final
from hibernate-entitymanager
.
You're using spring-boot
as parent, so no need to declare version of some dependencies, since they are managed by spring-boot
.
Also, hibernate-commons-annotations
is inherited from hibernate-entitymanager
and hibernate-annotations
is an old version of hibernate-commons-annotations
, you can remove both.
Finally, your pom.xml
can look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
<artifactId>TrafficSpyService</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Let me know if you have a problem.
If you're using jackson, better to convert directly to ObjectNode.
//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();
//pass it your payload
public static ObjectNode convObjToONode(Object o) {
StringWriter stringify = new StringWriter();
ObjectNode objToONode = null;
try {
mapper.writeValue(stringify, o);
objToONode = (ObjectNode) mapper.readTree(stringify.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(objToONode);
return objToONode;
}
It seems your @ComponentScan
annotation is not set properly.
Try :
@ComponentScan(basePackages = {"com.pharmacy"})
Actually you do not need the component scan if you have your main class at the top of the structure, for example directly under com.pharmacy
package.
Also, you don't need both
@SpringBootApplication
@EnableAutoConfiguration
The @SpringBootApplication
annotation includes @EnableAutoConfiguration
by default.
I had faced this similar error too. In my case it was one of my picture files in my drawable
folder. Removing the picture that was unused solved the problem for me. So, make sure to remove any unused items from drawable
folder.
Below worked for me..
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.apache.catalina.security.SecurityConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.something.configuration.SomethingConfig;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SomethingConfig.class, SecurityConfig.class }) //All your configuration classes
@EnableAutoConfiguration
@WebAppConfiguration // for MVC configuration
@EnableJpaRepositories("com.something.persistence.dataaccess") //JPA repositories
@EntityScan("com.something.domain.entity.*") //JPA entities
@ComponentScan("com.something.persistence.fixture") //any component classes you have
public class SomethingApplicationTest {
@Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
}
@Test
public void loginTest() throws Exception {
this.mockMvc.perform(get("/something/login"))
.andDo(print()).andExpect(status().isOk());
}
}
git shelve
doesn't exist in Git.
Only git stash
:
You had a 2008 old project git shelve to isolate modifications in a branch, but that wouldn't be very useful nowadays.
As documented in Intellij IDEA shelve dialog, the feature "shelving and unshelving" is not linked to a VCS (Version Control System tool) but to the IDE itself, to temporarily storing pending changes you have not committed yet in changelist.
Note that since Git 2.13 (Q2 2017), you now can stash individual files too.
1 Close Android Studio (AS)
2 Delete the folder in C:\Users.gradle\wrapper\dists\gradle-2.1-all
3 Run AS as admin
4 Sync your project files
Example.
var request = require('request');
var url = "http://localhost:3000";
var requestData = {
...
}
var data = {
url: url,
json: true,
body: JSON.stringify(requestData)
}
request.post(data, function(error, httpResponse, body){
console.log(body);
});
As inserting json: true
option,
sets body to JSON representation of value and adds "Content-type": "application/json"
header. Additionally, parses the response body as JSON.
LINK
just add login password to connect to RabbitMq
CachingConnectionFactory connectionFactory =
new CachingConnectionFactory("rabbit_host");
connectionFactory.setUsername("login");
connectionFactory.setPassword("password");
I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.
@GetMapping(value="/person/{id}/",
params="format=json",
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
Person person = personMapRepository.findPerson(id);
return ResponseEntity.ok(person);
}
@GetMapping(value="/person/{id}/",
params="format=xml",
produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
return GetPerson(id); // delegate
}
add spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
in application.properties file
thanks to the answers of Steve Park and Rafal Borowiec I got my code working, however, I had one issue: the DriverManagerDataSource is a "simple" implementation and does NOT give you a ConnectionPool (check http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/DriverManagerDataSource.html).
Hence, I replaced the functions which returns the DataSource
for the secondDB
to.
public DataSource <secondaryDB>DataSource() {
// use DataSourceBuilder and NOT DriverManagerDataSource
// as this would NOT give you ConnectionPool
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.url(databaseUrl);
dataSourceBuilder.username(username);
dataSourceBuilder.password(password);
dataSourceBuilder.driverClassName(driverClassName);
return dataSourceBuilder.build();
}
Also, if do you not need the EntityManager
as such, you can remove both the entityManager()
and the @Bean
annotation.
Plus, you may want to remove the basePackages annotation of your configuration class: maintaining it with the factoryBean.setPackagesToScan()
call is sufficient.
I had this error too because in the file where I used @Transactional
annotation, I was importing the wrong class
import javax.transaction.Transactional;
Instead of javax, use
import org.springframework.transaction.annotation.Transactional;
See my post here
How are you? I had the same problem while i was trying connect to MSSQL Server remotely using jdbc (dbeaver on debian).
After a while, i found out that my firewall configuration was not correctly. So maybe it could help you!
Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.
Four exceptions must be configured in Windows Firewall to allow access to SQL Server:
A port exception for TCP Port 1433. In the New Inbound Rule Wizard dialog, use the following information to create a port exception: Select Port Select TCP and specify port 1433 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – TCP 1433" A port exception for UDP Port 1434. Click New Rule again and use the following information to create another port exception: Select Port Select UDP and specify port 1434 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – UDP 1434 A program exception for sqlservr.exe. Click New Rule again and use the following information to create a program exception: Select Program Click Browse to select ‘sqlservr.exe’ at this location: [C:\Program Files\Microsoft SQL Server\MSSQL11.\MSSQL\Binn\sqlservr.exe] where is the name of your SQL instance. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL – sqlservr.exe A program exception for sqlbrowser.exe Click New Rule again and use the following information to create another program exception: Select Program Click Browse to select sqlbrowser.exe at this location: [C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe]. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL - sqlbrowser.exe
Source: http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/
I just solved this error happening in my tests.
Just make sure your test class has all dependencies in the attributes of the class being tested annotated with @MockBean
so SpringBoot test context can wire your classes correctly.
Only if you are testing controller: you need also class annotations to load the Controller context propertly.
Check it out:
@DisplayName("UserController Adapter Test")
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(TestConfig.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private CreateUserCommand createUserCommand;
@MockBean
private GetUserListQuery getUserListQuery;
@MockBean
private GetUserQuery getUserQuery;
For other users getting this problem.
You may get this error if you are running a newer ElasticSearch (5.5 or later) while running Spring Boot <2 version.
Recommendation is to use the REST Client since the Java Client will be deprecated.
Other workaround would be to upgrade to Spring Boot 2, since that should be compatible.
See https://discuss.elastic.co/t/spring-data-elasticsearch-cant-connect-with-elasticsearch-5-5-0/94235 for more information.
You can use Environment
Class to get data :
@Autowired
private Environment env;
String prop= env.getProperty('some.prop');
It works with Spring Boot 2.1.0 and Hibernate 5
@PersistenceContext
private EntityManager entityManager;
Then you can create new Session by using entityManager.unwrap(Session.class)
Session session = null;
if (entityManager == null
|| (session = entityManager.unwrap(Session.class)) == null) {
throw new NullPointerException();
}
example create query:
session.createQuery("FROM Student");
application.properties:
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db11g
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
Please note instead of
public TomcatEmbeddedServletContainerFactory tomcatFactory()
I had to use the following method signature
public EmbeddedServletContainerFactory embeddedServletContainerFactory()
I accomplished something similar using jQuery Waypoints.
There's a lot of moving parts, and quite a bit of logic (that I hope to get on GitHub some day soon), but essentially what you could do is...
fixed
.table.fixed
that make it invisible.sticky
to table.fixed
table.sticky.fixed
that position it just below the navbar and also make just the thead
content visible. This also has a z-index
so it is laid above the rest of the content..sticky
from the table.fixed
You have to duplicate the entire table DOM in order to ensure column widths line up appropriately.
If that sounds really complicated, you might want to try playing around with the DataTables plugin and the FixedHeader extension: https://datatables.net/extensions/fixedheader/
In my specific case I seemed to have been missing the dependency
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
If using Spring Boot this works well. Even with Spring Reactive Mongo.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
and validation config:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@Configuration
public class MongoValidationConfig {
@Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
}
I received same error despite jar being in lib directory & added to deployment assembly in Eclipse.
So I doubted two things ,
1.Some Weblogic cache issue - as this app was deployed before & I was trying to redeploy after some changes
2.Jar itself is corrupt due to partial download etc
So I re downloaded the jar & deleted everything in directory - ..\Oracle_Home\user_projects\domains\base_domain\lib and redeployed again & all went well.
I've got this error when I accidentally defined a property as a specific object type, instead of the interface type I have defined in UnityContainer.
For example:
Defining UnityContainer:
var container = new UnityContainer();
container.RegisterInstance(typeof(IDashboardRepository), DashboardRepository);
config.DependencyResolver = new UnityResolver(container);
SiteController (the wrong way - notice repo type):
private readonly DashboardRepository _repo;
public SiteController(DashboardRepository repo)
{
_repo = repo;
}
SiteController (the right way):
private readonly IDashboardRepository _repo;
public SiteController(IDashboardRepository repo)
{
_repo = repo;
}
I got this issue for a console Application.
In my case i just changed the Platform Target to "Any CPU" which you can see when you right click your solution and click on properties , you will find a Tab "Build" click on it, you will see "Platform target:" change it to "Any CPU", which will solve your issue
Here is some text I found at experts-exchange:
Bug 14575666
In 12.1, the default value for the SQLNET.ALLOWED_LOGON_VERSION parameter has been updated to 11. This means that database clients using pre-11g JDBC thin drivers cannot authenticate to 12.1 database servers unless theSQLNET.ALLOWED_LOGON_VERSION parameter is set to the old default of 8.
This will cause a 10.2.0.5 Oracle RAC database creation using DBCA to fail with the ORA-28040: No matching authentication protocol error in 12.1 Oracle ASM and Oracle Grid Infrastructure environments.
Workaround: Set SQLNET.ALLOWED_LOGON_VERSION=8 in the oracle/network/admin/sqlnet.ora file.
The same to @Anas. I can run it in Eclipse, but when i use "java -jar ..." run it, it giving me this error. Then i find my java build path is wrong, it missing the folder “src/main/resources”, so, the application can't find application.properties. When i add the “src/main/resources” folder in java build path, it worked.
And, you need add "@PropertySource({"application.properties"})" in your Application class.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController'
Make sure that you have added ojdbc14.jar
into your library.
For oracle 11g, usie ojdbc6.jar
.
You are missing spring-security-web-3.1.X.RELEASE.jar
from your classpath
To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.
We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.
CriteriaQuery
instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.EntityManager
to create a Query
instance for those (which effectively triggers query syntax validation).Metamodel
for meta-data about the domain types handled to prepare is-new checks etc.All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).
If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:
This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext
usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager
or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.
Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager
injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager
-> CriteriaBuilder
, CriteriaQuery
etc.) so that you end up with mocks returning mocks and so on.
Updated Answer
Due to all the downsides of adding a function to the Array prototype, I am updating this answer to provide an alternative that keeps the syntax similar to the syntax originally requested in the question.
class TravellerCollection extends Array {
sum(key) {
return this.reduce((a, b) => a + (b[key] || 0), 0);
}
}
const traveler = new TravellerCollection(...[
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
]);
console.log(traveler.sum('Amount')); //~> 235
Original Answer
Since it is an array you could add a function to the Array prototype.
traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
];
Array.prototype.sum = function (prop) {
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += this[i][prop]
}
return total
}
console.log(traveler.sum("Amount"))
The Fiddle: http://jsfiddle.net/9BAmj/
Add the following code to hibernate.cfg.xml
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
There is one more chance to get this exception even we used class name i.e., if we have two classes with same name in different packages. we'll get this problem.
I think hibernate may get ambiguity and throws this exception, so the solution is to use complete qualified name(like com.test.Customerv)
I added this answer that will help in scenario as I mentioned. I got the same scenario got stuck for some time.
I faced the same situation. Create your connection string as follows.
Replace
"connectionString": "Data Source=server name;Initial Catalog=DB name;User id=user id;Password=password;Integrated Security=True;MultipleActiveResultSets=True"
by
"connectionString": "Server=server name; Database=Treat; User Id=user id; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true"
If you have a circular spring injected dependency it will fail without warning, depending on the level of logging, and a few other factors.
Class A injects Class B, and Class B injects Class A. Via constructor, in this particular case.
You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation:
. So, your code should look like this:
// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//when delete is tapped
[currentCart removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
You can also simplify your code a little by using the array creation shortcut @[]
:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
I had the exact same problem, found that I was missing
<mdb>
<resource-adapter-ref resource-adapter-name="hornetq-ra"/>
<bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>
</mdb>
under
<subsystem xmlns="urn:jboss:domain:ejb3:1.2">
in standalone/configuration/standalone.xml
In my case, I was fetching data from database, changing some column values and updating it in database but for updating I was using the same save query which was violating primary key constraints i.e duplicate values for primary key, so I had written a separate query for updating the columns and it solved my problem..!
Add "EntityFramework.SqlServer.dll" into your bin folder. Problem will get resolved.
In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :
@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}
Spring doc about Aggregating @Configuration classes with @Import: link
The best way to handle the LazyInitializationException
is to use the JOIN FETCH
directive:
Query query = session.createQuery("""
select m
from Model m
join fetch m.modelType
where modelGroup.id = :modelGroupId
"""
);
Anyway, DO NOT use the following Anti-Patterns as suggested by some of the answers:
Sometimes, a DTO projection is a better choice than fetching entities, and this way, you won't get any LazyInitializationException
.
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
Use PowerMockito on top of Mockito.
Example code:
@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class Mocker {
@Test
public void shouldVerifyParameters() throws Exception {
//given
PowerMockito.mockStatic(DriverManager.class);
BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);
//when
sut.execute(); // System Under Test (sut)
//then
PowerMockito.verifyStatic();
DriverManager.getConnection(...);
}
More information:
After reporting the problem on the Android Studio feedback site, they found a solution for me. I am now using Gradle 1.10 and Android Studio 0.4.3.
Here is the link to the page with a description of how I fixed mine: https://code.google.com/p/android/issues/detail?id=65219
Hope this helps!
There are times that using OPTION(RECOMPILE)
makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:
EXEC sp_updatestats
And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.
Adding OPTION(RECOMPILE)
rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy
but maybe we are just using different terms for the same thing.
When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.
In summary - I don't see any reason that OPTION(RECOMPILE)
would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.
And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.
I know that it is very late to answer the question, but it may help someone like me who spent lots off time to fetch data using hql
So the thing is you just have to write a query
Query query = session.createQuery("from Employee");
it will give you all the data list but to fetch data from this you have to write this line.
List<Employee> fetchedData = query.list();
As simple as it looks.
This is because the port is already running in the background.So you can restart the eclipse and try again. OR open the file application.properties and change the value of 'server.port' to some other value like ex:- 8000/8181
Error: java.lang.NoSuchMethodError: javax.persistence.JoinTable.indexes()[Ljavax/persistence/Index;
The only thing that solved my problem was removing the following dependency in pom.xml:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
And replace it for:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
Hope it helps someone.
Because these days ASP.NET is open source, you can find it on GitHub: AspNet.Identity 3.0 and AspNet.Identity 2.0.
From the comments:
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 2:
* PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
* (See also: SDL crypto guidelines v5.1, Part III)
* Format: { 0x00, salt, subkey }
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
Server Error in '/' Application.
The system cannot find the file specified
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified
Source Error:
{ SqlCommand cmd = new SqlCommand("select * from tblemployee",con); con.Open(); GridView1.DataSource = cmd.ExecuteReader(); GridView1.DataBind();
Source File: d:\C# programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line: 23
if your error is same like mine..just do this
right click on your table in sqlserver object explorer,choose properties in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..
I was facing the same issue while auto-wiring the class from one of my jar file. I fixed the issue by using @Lazy annotation:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
@Autowired
@Lazy
private IGalaxyCommand iGalaxyCommand;
Reference here 2.10.2.1 Troubleshooting Problems Starting the MySQL Server.
1.Find the data directory ,it was configured in my.cnf.
[mysqld]
datadir=/var/lib/mysql
2. Check the err file,it log the error message about why mysql server start failed. the name of err file is related with your hostname.
cd /var/lib/mysql
ll
tail (hostname).err
3.If you find some messages like :
InnoDB: Error: log file ./ib_logfile0 is of different size 0 33554432 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!
170513 14:25:22 [ERROR] Plugin 'InnoDB' init function returned error.
170513 14:25:22 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
170513 14:25:22 [ERROR] Unknown/unsupported storage engine: InnoDB
170513 14:25:22 [ERROR] Aborting
then
delete ib_logfile0 and ib_logfile1
, then,
/etc/init.d/mysqld start
You can also try default values. spring-value-annotation
Default values can be provided for properties that might not be defined. In this example the value “some default” will be injected:
@Value("${unknown.param:some default}")
private String someDefault;
If the same property is defined as a system property and in the properties file, then the system property would be applied.
For my situation, I switched the value of "fork" to false, such as <fork>false</fork>
. I do not understand why, hope someone could explain to me. Thanks in advance.
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.
The @JoinColumn
annotation specifies the name of the column being used as the foreign key on the targeted entity.
On the Product
class above, the name of the join column is set to ID_CATALOG
.
@ManyToOne
@JoinColumn(name="ID_CATALOG")
private Catalog catalog;
However, the foreign key on the Product
table is called catalog_id
`catalog_id` int(11) DEFAULT NULL,
You'll need to change either the column name on the table or the name you're using in the @JoinColumn
so that they match. See http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association
I tried the binding according to the answer by @Szymon but It did not work for me. I tried basicHttpsBinding which is new in .net 4.5 and It solved the issue. Here is the complete configuration that works for me.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpsBinding>
<binding name="basicHttpsBindingForYourService">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"/>
</security>
</binding>
</basicHttpsBinding>
</bindings>
<services>
<service name="YourServiceName">
<endpoint address="" binding="basicHttpsBinding" bindingName="basicHttpsBindingForYourService" contract="YourContract" />
</service>
</services>
</system.serviceModel>
FYI: My application's target framework is 4.5.1. IIS web site that I created to deploy this wcf service only has https binding enabled.
JSON of unknown format to HashMap
public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
writeJson("JsonFile.json");
readgson("JsonFile.json");
}
public static void readgson(String file) {
try {
System.out.println( "Reading JSON file from Java program" );
FileReader fileReader = new FileReader( file );
com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader );
Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet();
if ( keys.isEmpty() ) {
System.out.println( "Empty JSON Object" );
}else {
Map<String, Object> map = json_UnKnown_Format( keys );
System.out.println("Json 2 Map : "+map);
}
} catch (IOException ex) {
System.out.println("Input File Does not Exists.");
}
}
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){
Map<String, Object> jsonMap = new HashMap<String, Object>();
for (Entry<String, JsonElement> entry : keys) {
String keyEntry = entry.getKey();
System.out.println(keyEntry + " : ");
JsonElement valuesEntry = entry.getValue();
if (valuesEntry.isJsonNull()) {
System.out.println(valuesEntry);
jsonMap.put(keyEntry, valuesEntry);
}else if (valuesEntry.isJsonPrimitive()) {
System.out.println("P - "+valuesEntry);
jsonMap.put(keyEntry, valuesEntry);
}else if (valuesEntry.isJsonArray()) {
JsonArray array = valuesEntry.getAsJsonArray();
List<Object> array2List = new ArrayList<Object>();
for (JsonElement jsonElements : array) {
System.out.println("A - "+jsonElements);
array2List.add(jsonElements);
}
jsonMap.put(keyEntry, array2List);
}else if (valuesEntry.isJsonObject()) {
com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString());
Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet();
jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
}
}
return jsonMap;
}
@SuppressWarnings("unchecked")
public static void writeJson( String file ) {
JSONObject json = new JSONObject();
json.put("Key1", "Value");
json.put("Key2", 777); // Converts to "777"
json.put("Key3", null);
json.put("Key4", false);
JSONArray jsonArray = new JSONArray();
jsonArray.put("Array-Value1");
jsonArray.put(10);
jsonArray.put("Array-Value2");
json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]
JSONObject jsonObj = new JSONObject();
jsonObj.put("Obj-Key1", 20);
jsonObj.put("Obj-Key2", "Value2");
jsonObj.put(4, "Value2"); // Converts to "4"
json.put("InnerObject", jsonObj);
JSONObject jsonObjArray = new JSONObject();
JSONArray objArray = new JSONArray();
objArray.put("Obj-Array1");
objArray.put(0, "Obj-Array3");
jsonObjArray.put("ObjectArray", objArray);
json.put("InnerObjectArray", jsonObjArray);
Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
sortedTree.put("Sorted1", 10);
sortedTree.put("Sorted2", 103);
sortedTree.put("Sorted3", 14);
json.put("TreeMap", sortedTree);
try {
System.out.println("Writting JSON into file ...");
System.out.println(json);
FileWriter jsonFileWriter = new FileWriter(file);
jsonFileWriter.write(json.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
Use: xmlhttp.setRequestHeader(key, value);
In JPA a relationship has a single owner, and by using mappedBy
in your UserBoard
class you tell that PinItem
is the owner of that bidirectional relationship, and that the property in PinItem
of the relationship is named board
.
In your UserBoard
class you do not have any fields/properties with the name board
, but it has a property pinItemList
, so you might try to use that property instead.
YES!!!
Install-Package Microsoft.AspNet.WebApi -Version 5.0.0
It works fine in my case....thnkz
This is the normal behavior and the reason is that your sqlCommandHandlerService.persist
method needs a TX when being executed (because it is marked with @Transactional
annotation). But when it is called inside processNextRegistrationMessage
, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist
method, it causes TX to be set to rollBackOnly
(even if you catch the exception in the caller and ignore it).
To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.
Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.
Write your first unit test
Write a JUnit test -- here's mine:
import org.junit.Assert;
import org.junit.Test;
public class MyFirstTest {
@Test
public void firstTest() {
Assert.assertTrue(true);
}
}
Ok, so the easiest method to create several plots is this:
import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
plt.figure()
plt.plot(x[i],y[i])
# Show/save figure as desired.
plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()
Note that you need to create a figure
every time or pyplot
will plot in the first one created.
If you want to create several data series all you need to do is:
import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')
You could automate it by having a list of colours like ['r','g','b','k']
and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):
import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.
for i in range(len(x)):
plt.plot(x[i],y[i],colours[i])
plt.show()
Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.
17 Dec 2019: added plt.show()
and plt.figure()
calls to clarify this part of the story.
I took @jaytrixz's answer/comment one step further and added "text/html" to the existing set of types. That way when they fix it on the server side to "application/json" or "text/json" I claim it'll work seamlessly.
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
Q: If PyPy can solve these great challenges (speed, memory consumption, parallelism) in comparison to CPython, what are its weaknesses that are preventing wider adoption?
A: First, there is little evidence that the PyPy team can solve the speed problem in general. Long-term evidence is showing that PyPy runs certain Python codes slower than CPython and this drawback seems to be rooted very deeply in PyPy.
Secondly, the current version of PyPy consumes much more memory than CPython in a rather large set of cases. So PyPy didn't solve the memory consumption problem yet.
Whether PyPy solves the mentioned great challenges and will in general be faster, less memory hungry, and more friendly to parallelism than CPython is an open question that cannot be solved in the short term. Some people are betting that PyPy will never be able to offer a general solution enabling it to dominate CPython 2.7 and 3.3 in all cases.
If PyPy succeeds to be better than CPython in general, which is questionable, the main weakness affecting its wider adoption will be its compatibility with CPython. There also exist issues such as the fact that CPython runs on a wider range of CPUs and OSes, but these issues are much less important compared to PyPy's performance and CPython-compatibility goals.
Q: Why can't I do drop in replacement of CPython with PyPy now?
A: PyPy isn't 100% compatible with CPython because it isn't simulating CPython under the hood. Some programs may still depend on CPython's unique features that are absent in PyPy such as C bindings, C implementations of Python object&methods, or the incremental nature of CPython's garbage collector.
For CodeIgniter 4
, you can use the built-in API Response Trait
Here's sample code for reference:
<?php namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
class Home extends BaseController
{
use ResponseTrait;
public function index()
{
$data = [
'data' => 'value1',
'data2' => 'value2',
];
return $this->respond($data);
}
}
I had this issue as well but the solution had nothing to do with coding. Make sure you are able to connect to gmail. Ping smtp.gmail.com. If you don't get a reply check your firewall settings. It could also be a proxy setting issue.
Give the path relative to your project.
Create a folder called resources
in your src
and put your config file there.
configuration.configure("/resources/hibernate.cfg.xml");
And If you check your code
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();
In two lines you are creating two configuration objects.
That should work(haven't tested) if you write,
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return configuration.buildSessionFactory();
But It fails after you deploy on the server,Since you are using system path than project relative path.
Convert by Number Class
:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number
is class. When we pass string, then constructor of Number class
will convert it.
Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml
to read your $_POST. You can use file_get_contents('php://input')
to get the raw post data as plain XML.
Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team
, of type int
, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:
@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;
Then, the following query will work flawlessly:
select e from Employee e inner join e.team
Which will load all the employees, except those that aren't associated to any team.
The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss
, id_profession
).
It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.
I'm lacking context, but this is working just fine:
List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...
In order to use the legacy UIApplication method to hide/show the status bar, your app must set a plist value for iOS 7:
View-Controller Based Status Bar Appearance = NO
This value is set to YES by default. If you change it to NO, you can use the legacy methods. If you leave it set to YES, you can still hide the status bar, but it's up to each view controller subclass in your app to override: prefersStatusBarHidden
to return YES.
Any time your app needs the status bar appearance or visibility to change, and View-Controller Based Status Bar Appearance is set to YES, your outermost view controller needs to call:
setNeedsStatusBarAppearanceUpdateAnimation
You are missing setter for salt
property as indicated by the exception
Please add the setter as
public void setSalt(long salt) {
this.salt=salt;
}
A pkg-config file describes all necessary compile-time and link-time flags and dependencies needed to use a library.
pkg-config --static --libs glfw3
shows me that
-L/usr/local/lib -lglfw3 -lrt -lXrandr -lXinerama -lXi -lXcursor -lGL -lm -ldl -lXrender -ldrm -lXdamage -lX11-xcb -lxcb-glx -lxcb-dri2 -lxcb-dri3 -lxcb-present -lxcb-sync -lxshmfence -lXxf86vm -lXfixes -lXext -lX11 -lpthread -lxcb -lXau -lXdmcp
I don't know if all these libs are actually necessary for compiling but for me it works...
You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml
available on the test classpath.
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {
@Autowired
protected SessionFactory sessionFactory;
@Test
public void testDBSourceIsCorrect() throws SQLException {
String databaseProductName = sessionFactory.getCurrentSession()
.connection()
.getMetaData()
.getDatabaseProductName();
assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
}
}
Note: This works with Spring 2.5.2 and Hibernate 3.6.5
This is an old bug, but I encountered it today on a web service which had barely been altered since being created via "New \ Project.."
For me, this issue was caused by the "IService.cs
" file containing the following:
<%@ ServiceHost Language="C#" Debug="true" Service="JSONWebService.Service1.svc" CodeBehind="Service1.svc.cs" %>
Notice the value in the Service
attribute contains ".svc
" at the end.
This shouldn't be there.
Removing those 4 characters resolved this issue.
<%@ ServiceHost Language="C#" Debug="true" Service="JSONWebService.Service1" CodeBehind="Service1.svc.cs" %>
Note that you need to open this file from outside of Visual Studio.
Visual Studio shows one file, Service1.cs
in the Solution Explorer, but that only lets you alter Service1.svc.cs
, not the Service1.svc
file.
I also faced this error when I was adding firebase push notifications in my app. but in my case I was doing a very silly mistake which i noticed after some time. I declared below code in manifest two times. After removing duplicate declaration. my issue solved.
<service android:name="com.evampsaanga.mytelenor.firebase.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>`
so you also check if there is anything duplicate in your app manifest file.
If you are maintaining one more cinfiguration file for app.config , Don't include any key in parent page.
Parent Page : app.config
<appSettings configSource="appSettings.config">
<add key="ClientSettings" value="venice" /> <!-- Don't add Key Here -->
</appSettings>
Child Page : appSettings.config
<appSettings>
<add key="ClientSettings" value="venice"/> <!-- add Here -->
</appSettings>
You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding
, and the default value for securityMode\transport
for that binding is Message
.
Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration
attribute:
<bindings>
<wsHttpBinding>
<binding name="ota2010AEndpoint"
.......>
<readerQuotas maxDepth="32" ... />
<reliableSession ordered="true" .... />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
(Snipped parts of the config to save space in the answer).
<service name="Synxis" behaviorConfiguration="SynxisWCF">
<endpoint address="" name="wsHttpEndpoint"
binding="wsHttpBinding"
bindingConfiguration="ota2010AEndpoint"
contract="Synxis" />
This will then assign your defined binding (with Transport security) to the endpoint.
Try this:
Select
Id,
Salt,
Password,
BannedEndDate,
(Select Count(*)
From LoginFails
Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
From Users
Where username = '" + LoginModel.Username + "'
And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!
Hope that helps!
Read the message:
Only one
<configSections>
element allowed per config file and if present must be the first child of the root<configuration>
element.
Move the configSections element to the top - just above where system.data is currently.
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory ** This is a solution if you are using Audit table.@Audit
Use:- @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.
To add the jar file to your project in Eclipse, do the following:
Check your server config file /etc/mysql/my.cnf
- verify bind_address
is not set to 127.0.0.1
. Set it to 0.0.0.0
or comment it out then restart server with:
sudo service mysql restart
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
For me the problem was invalid permissions - I was requesting "birthday" instead of "user_birthday". It's a shame the error message isn't at least minimally descriptive - just saying "permissions invalid" rather than ERROR CODE 2 would have saved me so much time.
We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext
.
In a standalone application, you can specify that as below
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");
Context ctx = new InitialContext(env);
But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext
as below
System.getProperty(Context.PROVIDER_URL);
and
these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work
InitialContext ctx = new InitialContext();
user2689410's code was exactly what I needed. Providing my version (credits to user2689410), which is faster due to calculating mean at once for whole rows in the DataFrame.
Hope my suffix conventions are readable: _s: string, _i: int, _b: bool, _ser: Series and _df: DataFrame. Where you find multiple suffixes, type can be both.
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
def time_offset_rolling_mean_df_ser(data_df_ser, window_i_s, min_periods_i=1, center_b=False):
""" Function that computes a rolling mean
Credit goes to user2689410 at http://stackoverflow.com/questions/15771472/pandas-rolling-mean-by-time-interval
Parameters
----------
data_df_ser : DataFrame or Series
If a DataFrame is passed, the time_offset_rolling_mean_df_ser is computed for all columns.
window_i_s : int or string
If int is passed, window_i_s is the number of observations used for calculating
the statistic, as defined by the function pd.time_offset_rolling_mean_df_ser()
If a string is passed, it must be a frequency string, e.g. '90S'. This is
internally converted into a DateOffset object, representing the window_i_s size.
min_periods_i : int
Minimum number of observations in window_i_s required to have a value.
Returns
-------
Series or DataFrame, if more than one column
>>> idx = [
... datetime(2011, 2, 7, 0, 0),
... datetime(2011, 2, 7, 0, 1),
... datetime(2011, 2, 7, 0, 1, 30),
... datetime(2011, 2, 7, 0, 2),
... datetime(2011, 2, 7, 0, 4),
... datetime(2011, 2, 7, 0, 5),
... datetime(2011, 2, 7, 0, 5, 10),
... datetime(2011, 2, 7, 0, 6),
... datetime(2011, 2, 7, 0, 8),
... datetime(2011, 2, 7, 0, 9)]
>>> idx = pd.Index(idx)
>>> vals = np.arange(len(idx)).astype(float)
>>> ser = pd.Series(vals, index=idx)
>>> df = pd.DataFrame({'s1':ser, 's2':ser+1})
>>> time_offset_rolling_mean_df_ser(df, window_i_s='2min')
s1 s2
2011-02-07 00:00:00 0.0 1.0
2011-02-07 00:01:00 0.5 1.5
2011-02-07 00:01:30 1.0 2.0
2011-02-07 00:02:00 2.0 3.0
2011-02-07 00:04:00 4.0 5.0
2011-02-07 00:05:00 4.5 5.5
2011-02-07 00:05:10 5.0 6.0
2011-02-07 00:06:00 6.0 7.0
2011-02-07 00:08:00 8.0 9.0
2011-02-07 00:09:00 8.5 9.5
"""
def calculate_mean_at_ts(ts):
"""Function (closure) to apply that actually computes the rolling mean"""
if center_b == False:
dslice_df_ser = data_df_ser[
ts-pd.datetools.to_offset(window_i_s).delta+timedelta(0,0,1):
ts
]
# adding a microsecond because when slicing with labels start and endpoint
# are inclusive
else:
dslice_df_ser = data_df_ser[
ts-pd.datetools.to_offset(window_i_s).delta/2+timedelta(0,0,1):
ts+pd.datetools.to_offset(window_i_s).delta/2
]
if (isinstance(dslice_df_ser, pd.DataFrame) and dslice_df_ser.shape[0] < min_periods_i) or \
(isinstance(dslice_df_ser, pd.Series) and dslice_df_ser.size < min_periods_i):
return dslice_df_ser.mean()*np.nan # keeps number format and whether Series or DataFrame
else:
return dslice_df_ser.mean()
if isinstance(window_i_s, int):
mean_df_ser = pd.rolling_mean(data_df_ser, window=window_i_s, min_periods=min_periods_i, center=center_b)
elif isinstance(window_i_s, basestring):
idx_ser = pd.Series(data_df_ser.index.to_pydatetime(), index=data_df_ser.index)
mean_df_ser = idx_ser.apply(calculate_mean_at_ts)
return mean_df_ser
I had to add the ?wsdl parameter to the end of the url. For example: http://localhost:8745/YourServiceName/?wsdl
This could also happens if you put a @PreAuthorize
or @PostAuthorize
in a Bean in creation. I would recommend to move such annotations to methods of interest.
If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()
in such cases getContext() is safe
then the code for starting the activity will be slightly changed like,
Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);
Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.
ObjectMapper mapper = new ObjectMapper();
Hi,
When I use mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
My json object values come '' blank in angular page mean in response
Solved with the help of only below settings
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().
withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
I encountered this exception in WebLogic, turns out it is a bug in WebLogic. Please see here for more details: Spring Boot exception: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]
I know this question has already been answered. However, for those using spring boot, this link helped me - https://smarterco.de/java-load-file-classpath-spring-boot/
However, the resourceLoader.getResource("classpath:file.txt").getFile();
was causing this problem and sbk's comment:
That's it. A java.io.File represents a file on the file system, in a directory structure. The Jar is a java.io.File. But anything within that file is beyond the reach of java.io.File. As far as java is concerned, until it is uncompressed, a class in jar file is no different than a word in a word document.
helped me understand why to use getInputStream()
instead. It works for me now!
Thanks!
in my case the solution was to set the proxy to "native" I had configured the proxy under linux with cntlm and also in Firefox (used as eclipse browser also.
What happens after login (to which url the user is redirected) is handled by the AuthenticationSuccessHandler
.
This interface (a concrete class implementing it is SavedRequestAwareAuthenticationSuccessHandler
) is invoked by the AbstractAuthenticationProcessingFilter
or one of its subclasses like (UsernamePasswordAuthenticationFilter
) in the method successfulAuthentication
.
So in order to have an other redirect in case 3 you have to subclass SavedRequestAwareAuthenticationSuccessHandler
and make it to do what you want.
Sometimes (depending on your exact usecase) it is enough to enable the useReferer
flag of AbstractAuthenticationTargetUrlRequestHandler
which is invoked by SimpleUrlAuthenticationSuccessHandler
(super class of SavedRequestAwareAuthenticationSuccessHandler
).
<bean id="authenticationFilter"
class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="filterProcessesUrl" value="/login/j_spring_security_check" />
<property name="authenticationManager" ref="authenticationManager" />
<property name="authenticationSuccessHandler">
<bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="useReferer" value="true"/>
</bean>
</property>
<property name="authenticationFailureHandler">
<bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login?login_error=t" />
</bean>
</property>
</bean>
This answer comes late but summarizes the concept involved in the "table not mapped" exception(in order to help those who come across this problem since its very common for hibernate newbies). This error can appear due to many reasons but the target is to address the most common one that is faced by a number of novice hibernate developers to save them hours of research. I am using my own example for a simple demonstration below.
The exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: subscriber is not mapped [ from subscriber]
In simple words, this very usual exception only tells that the query is wrong in the below code.
Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from subscriber").list();
This is how my POJO class is declared:
@Entity
@Table(name = "subscriber")
public class Subscriber
But the query syntax "from subscriber" is correct and the table subscriber
exists. Which brings me to a key point:
and how its explained here
HQL works with persistent objects and their properties not with the database tables and columns.
Since the above query is an HQL one, the subscriber
is supposed to be an entity name not a table name. Since I have my table subscriber
mapped with the entity Subscriber
. My problem solves if I change the code to this:
Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from Subscriber").list();
Just to keep you from getting confused. Please note that HQL is case sensitive in a number of cases. Otherwise it would have worked in my case.
Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.
https://www.tutorialspoint.com/hibernate/hibernate_query_language.htm
To further understand how hibernate mapping works, please read this
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
Refering to Oliver Gierke's hint:
When the manipulation of the persistance.xml does the trick, then you created a normal java-class instead of a entity-class.
When creating a new entity-class then the entry in the persistance.xml should be set by Netbeans (in my case).
But as mentioned by Oliver Gierke you can add the entry later to the persistance.xml (if you created a normal java-class).
This only happens inside my load/unit testing projects. Frustrating, I jyst had it crop up in a project I have been running for 2 years. Must have been some order of test running that breaks things. I guess once that fi gets removed its gone.
I found that simply declaring a variable that uses the correct value fixes the issue... I never even call the method. Just define it. Odd but it works.
/// <summary> /// So that the test runner copies dlls not directly referenced by the integration project /// </summary> private void referenceLibs() { var useless = SqlProviderServices.Instance; }
Add this code ..It helped me
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
classpath:/org/springframework/context/config/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
classpath:/org/springframework/aop/config/spring-aop-3.0.xsd
">
</beans>
In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.
List<Apartment> aptList = new ArrayList<Apartment>();
Apartment aptmt = null;
for(int i=0;i<5;i++){
aptmt= new Apartment();
aptmt.setAptName("Apartment Name : ArrowHead Ranch");
aptmt.setAptNum("3153"+i);
aptmt.setPhase((i+1));
aptmt.setFloorLevel(i+2);
aptList.add(aptmt);
}
mapper.writeValueAsString(aptList)
public class LoginTest extends BaseTest {
@Test
public void exampleTest( ){
// Test
}
}
Inherits from a base test class (this example is testng
rather than jUnit
, but the ActiveProfiles
is the same):
@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
public class BaseTest extends AbstractTestNGSpringContextTests { }
MyActiveProfileResolver
can contain any logic required to determine which profile to use:
public class MyActiveProfileResolver implements ActiveProfilesResolver {
@Override
public String[] resolve(Class<?> aClass) {
// This can contain any custom logic to determine which profiles to use
return new String[] { "exampleProfile" };
}
}
This sets the profile which is then used to resolve dependencies required by the test.
I'm not sure but:
If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?
If you call the delete method with a transient object, then it is possible that you have a cascade="delete"
or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.
Edit: Calling delete() with a transient instance means doing something like that:
MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);
This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.
If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.
I encountered a similar problem when I was using the below to obtain connection factory
ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");
Its resolved when I changed it to the below
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");
The below then showed that my Q size was increasing..
http://:8161/admin/queues.jsp
for converting dd/mm/yyyy
to mm/dd/yyyy
=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))
I encountered the same problem in the code and What I did is I found out all the changes I have made from the last correct compilation. And I have observed one function declaration was without ";" and also it was passing a value and I have declared it to pass nothing "void". this method will surely solve the problem for many.
Viscon
For me this worked (basically pom.xml
level global properties):
<properties>
<sonar.exclusions>**/Name*.java</sonar.exclusions>
</properties>
According to: http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-Patterns
It appears you can either end it with ".java" or possibly "*"
to get the java classes you're interested in.
I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-web </artifactId>
<version> 1.2.0.RELEASE </version>
</dependency>
You don't need the SELECT
DECLARE @LastChangeDate as date
SET @LastChangeDate = GetDate()
project.group
is a predefined property. With -P
, you can only set project properties that are not predefined. Alternatively, you can set Java system properties (-D
).
Some how all the above solutions did not worked in hibernate 5.2.10.Final.
But setting the map to null as below worked for me:
playlist.setPlaylistadMaps(null);
I can't see anything obviously wrong, but perhaps a different approach might help you debug it?
You could try specify your datasource in the per-application-context instead of the global tomcat one.
You can do this by creating a src/main/webapp/META-INF/context.xml (I'm assuming you're using the standard maven directory structure - if not, then the META-INF folder should be a sibling of your WEB-INF directory). The contents of the META-INF/context.xml file would look something like:
<?xml version="1.0" encoding="UTF-8"?>
<Context [optional other attributes as required]>
<Resource name="jdbc/PollDatasource" auth="Container"
type="javax.sql.DataSource" driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail" maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>
Obviously the path and docBase would need to match your application's specific details.
Using this approach, you don't have to specify the datasource details in Tomcat's context.xml file. Although, if you have multiple applications talking to the same database, then your approach makes more sense.
At any rate, give this a whirl and see if it makes any difference. It might give us a clue as to what is going wrong with your approach.
it is better to use json after post your resuest like below
var clien = new RestClient("https://smple.com/");
var request = new RestRequest("index", Method.POST);
request.AddHeader("Sign", signinstance);
request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
var response = client.Execute<YourReturnclassSample>(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
return Ok(response.Content);
}
Using EntityManager em;
public User getUserById(Long id) {
return em.getReference(User.class, id);
}
Copy Local = True was solve for one of my projects. But in another project, I get the same error, tried to set Copy Local = true, but it not solve my problem. Changing the Target framework from 4.5.1 to 4.5 in Project Properties Helped with this.
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
Your @Entity
class has a String
type for its @Id
field, so it can't generate ids for you.
If you change it to an auto increment in the DB and a Long
in java, and add the @GeneratedValue
annotation:
@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;
it will handle incrementing id generation for you.
In ES5 supported (or shimmed) browsers...
var keys = Object.keys(myHash);
var values = keys.map(function(v) { return myHash[v]; });
Shims from MDN...
You will have to annotate your service with @Service
since you have said I am using annotations for mapping
I have the same problem a few months ago. This solve my problem using Maven instead of a downloaded version of Spring and some changes in the web.xml.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringWEB1</groupId>
<artifactId>SpringWEB1</artifactId>
<version>1</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
Controller.java
package com.jmtm.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@org.springframework.stereotype.Controller
public class Controller {
@RequestMapping("/hi")
public ModelAndView hi(){
return new ModelAndView("Hello", "msg", "Hello user.");
}
}
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<context:component-scan base-package="com.jmtm.controller"></context:component-scan>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
And the most important part of the solution, include the path of the servlet dispatcher (A.K.A. spring-servlet.xml) in the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringWEB1</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Something weird happen when I try to solve this. Any downloaded version of Spring from maven.springframework.org/release/org/springframework/spring gives me a lot of problems (Tomcat couldn't find servlet, Spring stops Tomcat, Eclipse couldn't start the server {weird}) so with many problems find many partial solutions. I hope this works for you.
As an extra help, in Eclipse, download from the Eclipse Marketplace the Spring STS Tool for Eclipse, this will help you to create configuration files (servlet.xml) and write code for the servlet in the web.xml file.
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
for best behaviour create a class with a method like this
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddCommand("Send-MailMessage")
.AddParameter("SMTPServer", "smtp.xxx.com")
.AddParameter("From", "[email protected]")
.AddParameter("Subject", "xxx Notification")
.AddParameter("Body", body_msg)
.AddParameter("BodyAsHtml")
.AddParameter("To", recipients);
// invoke execution on the pipeline (ignore output) --> nothing will be displayed
PowerShellInstance.Invoke();
}
Whereby these instance is called in a function like:
public void sendEMailPowerShell(string body_msg, string[] recipients)
Never forget to use a string array for the recepients, which can be look like this:
string[] reportRecipient = {
"xxx <[email protected]>",
"xxx <[email protected]>"
};
this message can be overgiven as parameter to the method itself, HTML coding enabled!!
never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!
mail reportMail = new mail(); //instantiate from class
reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses
I think you could use Spring's
@Lazy
annotation on one of the autowired fields to break circular dependency.
I'm not sure if this works/exists in mentioned Spring version.
In the HQL , you should use the java class name and property name of the mapped @Entity
instead of the actual table name and column name , so the HQL should be :
List<User> result = session.createQuery("from User", User.class).getResultList();
Update : To be more precise , you should use the entity name configured in @Entity
to refer to the "table" , which default to unqualified name of the mapped java class if you do not set it explicitly.
(P.S. It is @javax.persistence.Entity
but not @org.hibernate.annotations.Entity
)
I am using below code and it perfect works for me, hope it will help you.
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Force redirect to https" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
</rule>
</rules>
</rewrite>
</system.webServer>
In the endpoint tag you need to include the property address=""
<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />
SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.
I was also facing the error "Error preloading the connection pool" while using Oracle 10g Express Edition with my Spring and CAS based application during login.
My CAS based application only has classes12.jar in its classpath, Placing ojdbc14.jar in the classpath has resolved my problem.
I solved the error by modifying the following property in hibernate.cfg.xml
<property name="hibernate.hbm2ddl.auto">validate</property>
Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.
Instead of passing reference object passed the saved object, below is explanation which solve my issue:
//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)
//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)
In my case it was the wrong dependecy for CrudRepository. My IDE added also follwing:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.11.2.RELEASE</version>
</dependency>
But I just needed:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>RELEASE</version>
</dependency>
I removed the first one and everything was fine.
The simple solution to the problem Kaleb is trying to solve is just to accept the property name if the column attribute doesn't exist:
Dapper.SqlMapper.SetTypeMap(
typeof(T),
new Dapper.CustomPropertyTypeMap(
typeof(T),
(type, columnName) =>
type.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName) || prop.Name == columnName)));
Please do check Hibernate Property Name and Id Name also.
This SO answer might help in this case.
If the main project already references the resource project, then you could just explicitly work with your generated-resource class in your code, and access its ResourceManager
from that. Hence, something along the lines of:
ResourceManager resMan = YeagerTechResources.Resources.ResourceManager;
// then, you could go on working with that
ResourceSet resourceSet = resMan.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// ...
Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:
PHP Code sample:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}
In particular, don't add an exit;
as no preflight is needed.
Yes, it is deprecated. http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory() specifically tells you to use the other method you found instead (buildSessionFactory(ServiceRegistry serviceRegistry)
) - so use it.
The documentation is copied over from release to release, and likely just hasn't been updated yet (they don't rewrite the manual with every release) - so trust the Javadocs.
The specifics of this change can be viewed at:
Some additional references:
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?.I encountered this error recently and after some brief investigation, found the cause to be that we were running out of space on the disk holding the database (less than 1GB).
As soon as I moved out the database files (.mdf and .ldf) to another disk on the same server (with lots more space), the same page (running the query) that had timed-out loaded within three seconds.
One other thing to investigate, while trying to resolve this error, is the size of the database log files. Your log files just might need to be shrunk.
Check the items in forEach
<c:forEach items="${pools}" var="pool">
${pool.name}
</c:forEach>
Some times items="${pools}" has an extra space or it acts like string, retyping it should solve the issue.
I was also getting the same error, the WCF was working properly for me when i was using it in the Dev Environment with my credentials, but when someone else was using it in TEST, it was throwing the same error. I did a lot of research, and then instead of doing config updates, handled an exception in the WCF method with the help of fault exception. Also the identity for the WCF needs to be set with the same credentials which are having access in the database, someone might have changed your authority. Please find below the code for the same:
[ServiceContract]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(ServiceData))]
ForDataset GetCCDBdata();
[OperationContract]
[FaultContract(typeof(ServiceData))]
string GetCCDBdataasXMLstring();
//[OperationContract]
//string GetData(int value);
//[OperationContract]
//CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
[DataContract]
public class ServiceData
{
[DataMember]
public bool Result { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
[DataMember]
public string ErrorDetails { get; set; }
}
in your service1.svc.cs you can use this in the catch block:
catch (Exception ex)
{
myServiceData.Result = false;
myServiceData.ErrorMessage = "unforeseen error occured. Please try later.";
myServiceData.ErrorDetails = ex.ToString();
throw new FaultException<ServiceData>(myServiceData, ex.ToString());
}
And use this in the Client application like below code:
ConsoleApplicationWCFClient.CCDB_HIG_service.ForDataset ds = obj.GetCCDBdata();
string str = obj.GetCCDBdataasXMLstring();
}
catch (FaultException<ConsoleApplicationWCFClient.CCDB_HIG_service.ServiceData> Fex)
{
Console.WriteLine("ErrorMessage::" + Fex.Detail.ErrorMessage + Environment.NewLine);
Console.WriteLine("ErrorDetails::" + Environment.NewLine + Fex.Detail.ErrorDetails);
Console.ReadLine();
}
Just try this, it will help for sure to get the exact issue.
There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as
<class>com.yourCompanyName.WhateverEntityClass</class>
In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.
In C# and SQL SERVER, we can fix the error by adding Integrated Security = true
to the connection string.
Please find the full connection string:
constr = @"Data Source=<Data-Source-Server-Name>;Initial Catalog=<DB-Name>;Integrated Security=true";
You can do it by using include_once()
function in php. Construct a header part in the name of header.php
and construct the footer part by footer.php
. Finally include all the content in one file.
For example:
header.php
<html>
<title>
<link href="sample.css">
footer.php
</html>
So the final files look like
include_once("header.php")
body content(The body content changes based on the file dynamically)
include_once("footer.php")
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter | openSession | getCurrentSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session creation | Always open new session | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close | Need to explicity flush and close session objects | No need to flush and close sessions , since it is automatically taken by hibernate internally. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance | In single threaded environment , it is slower than getCurrentSession | In single threaded environment , it is faster than openSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration | No need to configure any property to call this method | Need to configure additional property: |
| | | <property name=""hibernate.current_session_context_class"">thread</property> |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
In earlier versions session factory was created as below:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be like:
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
The error shows that com.bd.service.ArticleService
is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:
<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>
Alternatively, if you want to include all subpackages in com.bd
:
<context:component-scan base-package="com.bd">
<context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>
As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan
annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration
.
@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {
@Autowired
ArticleService articleService;
...
}
You might find this Spring in depth section on Autowiring useful.
Just throw any RuntimeException
from a method marked as @Transactional
.
By default all RuntimeException
s rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor()
and noRollbackFor()
annotation parameters:
@Transactional(rollbackFor=Exception.class)
This will rollback transaction after throwing any exception.
You can change the ApplicationPoolIdentity from IIS7 -> Application Pools -> Advanced Settings.
Under ApplicationPoolIdentity you will find local system. This will make your application run under NT AUTHORITY\SYSTEM
, which is an existing login for the database by default.
Edit: Before applying this suggestion you should note and understand the security implications.
public class AesCryptoService
{
private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");
public static string EncryptStringToBytes_Aes(string plainText)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
public static string DecryptStringFromBytes_Aes(string Text)
{
if (Text == null || Text.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
string plaintext = null;
byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
My personal opinion: Go for Swing together with the NetBeans platform.
If you need advanced components (more than NetBeans offers) you can easily integrate SwingX without problems (or JGoodies) as the NetBeans platform is completely based on Swing.
I would not start a large desktop application (or one that is going to be large) without a good platform that is build upon the underlying UI framework.
The other option is SWT together with the Eclipse RCP, but it's harder (though not impossible) to integrate "pure" Swing components into such an application.
The learning curve is a bit steep for the NetBeans platform (although I guess that's true for Eclipse as well) but there are some good books around which I would highly recommend.
you need to add jar file in your build path..
commons-dbcp-1.1-RC2.jar
or any version of that..!!!!
ADDED : also make sure you have commons-pool-1.1.jar too in your build path.
ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.
Same problem has been resolved in LINK:
I could found other option from post on the Spring forum that you can pass a reference to the Spring application context via the SchedulerFactoryBean. Like the example shown below:
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<propertyy name="triggers">
<list>
<ref bean="simpleTrigger"/>
</list>
</property>
<property name="applicationContextSchedulerContextKey">
<value>applicationContext</value>
</property>
Then using below code in your job class you can get the applicationContext and get whatever bean you want.
appCtx = (ApplicationContext)context.getScheduler().getContext().get("applicationContextSchedulerContextKey");
Hope it helps. You can get more information from Mark Mclaren'sBlog
First of all, enable the less secure app in your Gmail account from which you will send emails using this link:- https://myaccount.google.com/lesssecureapps?pli=1
Then you simply add the following code in your session creation. It will work fine then.
Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"your_email", "your_password");// Specify the Username and the PassWord
}
});
if you want the more elaborated one use the following:-
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailSender {
public Properties mailProperties() {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.user", "your_email");
props.setProperty("mail.smtp.password", "your_password");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.auth", "true");
return props;
}
public String sendMail(String from, String to, String subject, String msgBody) {
Properties props = mailProperties();
Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"your_email", "your_password");// Specify the Username and the PassWord
}
});
mailSession.setDebug(false);
try {
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(subject);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, to);
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(msgBody, "text/html");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
return "SUCCESS";
} catch (NoSuchProviderException e) {
e.printStackTrace();
return "INVALID_EMAIL";
} catch (MessagingException e) {
e.printStackTrace();
}
return "ERROR";
}
public static void main(String args[]) {
System.out.println(new MailSender().sendMail("your_email/from_email", "to_email", "Subject", "Message"));
}
}
Hope! it helps. Thanks!
I referenced System.Configuration
library and I have the same error.
The debug files had not their app.config, create manually this file.
The error is, I solved this copying the file "appname.exe.config" in debug folder. The IDE was not create the file.
Every InvoiceItem
must have an Invoice
attached to it because of the not-null="true"
in the many-to-one mapping.
So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a setItems
method. I do NOT see an addInvoiceItem
method. When you set items, you need to loop through the set and call item.setInvoice(this)
on all of the items. If you implement an addItem
method, you need to do the same thing. Or you need to otherwise set the Invoice of every InvoiceItem
in the collection.
Two solutions
1. use merge if you want to update the object
2. use save if you want to just save new object (make sure identity is null to let hibernate or database generate it)
3. if you are using mapping like
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
@JoinColumn(name = "stock_id")
Then use CascadeType.ALL to CascadeType.MERGE
thanks Shahid Abbasi
For me the thing that worked was the order in which the namespaces were defined in the xsi:schemaLocation tag : [ since the version was all good and also it was transaction-manager already ]
The error was with :
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
AND RESOLVED WITH :
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar
import net.sf.json.JSONObject;
...
public void send()
{
//put attributes
Map m = New HashMap();
m.put("send_to","[email protected]");
m.put("email_subject","this is a test email");
m.put("email_content","test email content");
//generate JSON Object
JSONObject json = JSONObject.fromObject(content);
String message = json.toString();
...
}
public void receive(String jsonMessage)
{
//parse attributes
JSONObject json = JSONObject.fromObject(jsonMessage);
String to = (String) json.get("send_to");
String title = (String) json.get("email_subject");
String content = (String) json.get("email_content");
...
}
More samples here http://json-lib.sourceforge.net/usage.html
C:\>help if
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
You are using POST method, but are you providing an array of data? E.g.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
You can use this
(new SelectElement(driver.FindElement(By.Id(""))).SelectByText("");
Sometimes, a Swift version of the "SQLite in 5 minutes or less" approach shown on sqlite.org is sufficient.
The "5 minutes or less" approach uses sqlite3_exec()
which is a convenience wrapper for sqlite3_prepare()
, sqlite3_step()
, sqlite3_column()
, and sqlite3_finalize()
.
Swift 2.2 can directly support the sqlite3_exec()
callback
function pointer as either a global, non-instance procedure func
or a non-capturing literal closure {}
.
Readable typealias
typealias sqlite3 = COpaquePointer
typealias CCharHandle = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>
typealias CCharPointer = UnsafeMutablePointer<CChar>
typealias CVoidPointer = UnsafeMutablePointer<Void>
Callback Approach
func callback(
resultVoidPointer: CVoidPointer, // void *NotUsed
columnCount: CInt, // int argc
values: CCharHandle, // char **argv
columns: CCharHandle // char **azColName
) -> CInt {
for i in 0 ..< Int(columnCount) {
guard let value = String.fromCString(values[i])
else { continue }
guard let column = String.fromCString(columns[i])
else { continue }
print("\(column) = \(value)")
}
return 0 // status ok
}
func sqlQueryCallbackBasic(argc: Int, argv: [String]) -> Int {
var db: sqlite3 = nil
var zErrMsg:CCharPointer = nil
var rc: Int32 = 0 // result code
if argc != 3 {
print(String(format: "ERROR: Usage: %s DATABASE SQL-STATEMENT", argv[0]))
return 1
}
rc = sqlite3_open(argv[1], &db)
if rc != 0 {
print("ERROR: sqlite3_open " + String.fromCString(sqlite3_errmsg(db))! ?? "" )
sqlite3_close(db)
return 1
}
rc = sqlite3_exec(db, argv[2], callback, nil, &zErrMsg)
if rc != SQLITE_OK {
print("ERROR: sqlite3_exec " + String.fromCString(zErrMsg)! ?? "")
sqlite3_free(zErrMsg)
}
sqlite3_close(db)
return 0
}
Closure Approach
func sqlQueryClosureBasic(argc argc: Int, argv: [String]) -> Int {
var db: sqlite3 = nil
var zErrMsg:CCharPointer = nil
var rc: Int32 = 0
if argc != 3 {
print(String(format: "ERROR: Usage: %s DATABASE SQL-STATEMENT", argv[0]))
return 1
}
rc = sqlite3_open(argv[1], &db)
if rc != 0 {
print("ERROR: sqlite3_open " + String.fromCString(sqlite3_errmsg(db))! ?? "" )
sqlite3_close(db)
return 1
}
rc = sqlite3_exec(
db, // database
argv[2], // statement
{ // callback: non-capturing closure
resultVoidPointer, columnCount, values, columns in
for i in 0 ..< Int(columnCount) {
guard let value = String.fromCString(values[i])
else { continue }
guard let column = String.fromCString(columns[i])
else { continue }
print("\(column) = \(value)")
}
return 0
},
nil,
&zErrMsg
)
if rc != SQLITE_OK {
let errorMsg = String.fromCString(zErrMsg)! ?? ""
print("ERROR: sqlite3_exec \(errorMsg)")
sqlite3_free(zErrMsg)
}
sqlite3_close(db)
return 0
}
To prepare an Xcode project to call a C library such as SQLite, one needs to (1) add a Bridging-Header.h file reference C headers like #import "sqlite3.h"
, (2) add Bridging-Header.h to Objective-C Bridging Header in project settings, and (3) add libsqlite3.tbd
to Link Binary With Library target settings.
The sqlite.org's "SQLite in 5 minutes or less" example is implemented in a Swift Xcode7 project here.
It is possible, but only if the struct you're initializing is a POD (plain old data) struct. It cannot contain any methods, constructors, or even default values.
They both represent floating point numbers. A FLOAT
is for single-precision, while a DOUBLE
is for double-precision numbers.
MySQL uses four bytes for single-precision values and eight bytes for double-precision values.
There is a big difference from floating point numbers and decimal (numeric) numbers, which you can use with the DECIMAL
data type. This is used to store exact numeric data values, unlike floating point numbers, where it is important to preserve exact precision, for example with monetary data.
In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__
. So if you don't define it in your class, you will get the one from the base.
Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__
, your class will inherit the first one only.
In such cases, you should really use super
if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).
If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super
):
class A:
def __init__(self):
print('A')
super().__init__()
class B:
def __init__(self):
print('B')
super().__init__()
class C(A, B):
pass
C()
#prints:
#A
#B
Notice how both base classes use super
even though they don't have their own base classes.
What super
does is: it calls the method from the next class in MRO (method resolution order). The MRO for C
is: (C, A, B, object)
. You can print C.__mro__
to see it.
So, C
inherits __init__
from A
and super
in A.__init__
calls B.__init__
(B
follows A
in MRO).
So by doing nothing in C
, you end up calling both, which is what you want.
Now if you were not using super
, you would end up inheriting A.__init__
(as before) but this time there's nothing that would call B.__init__
for you.
class A:
def __init__(self):
print('A')
class B:
def __init__(self):
print('B')
class C(A, B):
pass
C()
#prints:
#A
To fix that you have to define C.__init__
:
class C(A, B):
def __init__(self):
A.__init__(self)
B.__init__(self)
The problem with that is that in more complicated MI trees, __init__
methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.
I personally find it easier use MySQL event scheduler than cron.
Enable it with
SET GLOBAL event_scheduler = ON;
and create an event like this:
CREATE EVENT name_of_event
ON SCHEDULE EVERY 1 DAY
STARTS '2014-01-18 00:00:00'
DO
DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7;
and that's it.
Read more about the syntax here and here is more general information about it.
I have finally managed to properly add back button to actionbar/toolbar
@Override
public void onCreate(Bundle savedInstanceState) {
...
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
To remove migration (if you already migrated the migration)
rake db:migrate:down VERSION="20130417185845" #Your migration version
To remove Model
rails d model name #name => Your model name
In my case, radio button value is fetched from database and then set into the form. Following code works for me.
$("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);
Here's the simple, built-in way:
<span title="My tip">text</span>
That gives you plain text tooltips. If you want rich tooltips, with formatted HTML in them, you'll need to use a library to do that. Fortunately there are loads of those.
First:
While publishing recheck what u have opted.
this should do it. It did for me!:)
I have found an excellent and relatively short explanation here.
A multipart request is a REST request containing several packed REST requests inside its entity.
var otherInput = $(this).closest('.row').find('.inputQty');
That goes up to a row level, then back down to .inputQty
.
Equal height columns is the default behaviour for Bootstrap 4 grids.
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
<br>_x000D_
Line 2_x000D_
<br>_x000D_
Line 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You might need to install for your specific version, I have known cases where this was needed when I was using many versions of python and one version in a virtualenv using for example python 3.7 was not importing tkinter I would have to install it for that version specifically.
For example
sudo apt-get install python3.7-tk
No idea why - but this has occured.
I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)
I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.
Hope that helps.
public static void main(String[] args) {
int[] A=new int[size];
//code for take input in array
int[] C=sorting(A); //pass array via method
//and then print array
}
public static int[] sorting(int[] a) {
//code for work with array
return a; //retuen array
}
it is very possible to convert JSON using XSLT: you need JSON2SAX deserializer and SAX2JSON serializer.
Sample code in Java: http://www.gerixsoft.com/blog/json/xslt4json
The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).
In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.
This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)
First create a Project With PdfCreation in Android Studio
Then Follow below steps:
1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/PDF");
System.out.print(myDir.toString());
myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} // Open Document for Writting into document
document.open(); // User Define Method
addMetaData(document);
try {
addTitlePage(document);
} catch (DocumentException e) {
e.printStackTrace();
} // Close Document after writting all content
document.close();
5. public void addMetaData(Document document)
{
document.addTitle("RESUME");
document.addSubject("Person Info");
document.addKeywords("Personal, Education, Skills");
document.addAuthor("TAG");
document.addCreator("TAG");
}
public void addTitlePage(Document document) throws DocumentException
{ // Font Style for Document
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
| Font.UNDERLINE, BaseColor.GRAY);
Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
prHead.setFont(titleFont); // Add item into Paragraph
prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
myTable.setWidthPercentage(100.0f); // Create New Cell into Table
PdfPCell myCell = new PdfPCell(new Paragraph(""));
myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
myTable.addCell(myCell);
prHead.setFont(catFont);
prHead.add("\nName1 Name2\n");
prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
document.add(prHead);
document.add(myTable);
document.add(myTable); // Now Start another New Paragraph
Paragraph prPersinalInfo = new Paragraph();
prPersinalInfo.setFont(smallBold);
prPersinalInfo.add("Address 1\n");
prPersinalInfo.add("Address 2\n");
prPersinalInfo.add("City: SanFran. State: CA\n");
prPersinalInfo.add("Country: USA Zip Code: 000001\n");
prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
document.add(prPersinalInfo);
document.add(myTable);
document.add(myTable);
Paragraph prProfile = new Paragraph();
prProfile.setFont(smallBold);
prProfile.add("\n \n Profile : \n ");
prProfile.setFont(normal);
prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
prProfile.setFont(smallBold);
document.add(prProfile); // Create new Page in PDF
document.newPage();
}
Make sure you have a working python-apt package. You could try and remove and install that package again to fix the problem with apt_pkg.so not being located.
apt-get install python-apt
The latest way to do this with ES2016 JavaScript
let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
name,
totalScore,
gamesPlayed
})
It depends on what type of fading you are looking for.
But with shadow and rounded corners you can get a nice result. Rounded corners because the bigger the shadow, the weirder it will look in the edges unless you balance it out with rounded corners.
also.. http://css3pie.com/
If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.
Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/
EDIT
Your code should look like this:
.img_thumb {
float: left;
height: 120px;
margin-bottom: 5px;
margin-left: 9px;
position: relative;
width: 147px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 3px;
line-height:120px;
text-align:center;
}
.img_thumb img {
vertical-align: middle;
}
The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:
http://jsfiddle.net/Cthulhu/QHEnL/6/
http://jsfiddle.net/Cthulhu/QHEnL/7/
UPDATE
It's now 2016 (the future!) and looks like a few things are changing (finally!!).
Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).
Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.
With that being said, here's an updated way of aligning elements, both horizontally and vertically:
.container {
position: relative;
}
.container .element {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Using this transform: translate();
method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.
If you only need to center in one dimension, you can use translateY
or translateX
. Just try it for a while and you'll see how it works. Also, try to change the values of the translate
, you will find it useful for a bunch of different situations.
Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/
For more information on transform
, here's a good resource.
Happy coding.
Interfaces are used to drive consistency,in a manner that is loosely coupled which makes it different to abstract class which is tightly coupled.That's why its also commonly defined as a contract.Whichever classes that implements the interface has abide to "rules/syntax" defined by the interface and there is no concrete elements within it.
I'll just give an example supported by the graphic below.
Imagine in a factory there are 3 types of machines.A rectangle machine,a triangle machine and a polygon machine.Times are competitive and you want to streamline operator training.You just want to train them in one methodology of starting and stopping machines so you have a green start button and red stop button.So now across 3 different machines you have a consistent way of starting and stopping 3 different types of machines.Now imagine these machines are classes and the classes need to have start and stop methods,how you going to drive consistency across these classes which can be very different? Interface is the answer.
A simple example to help you visualize,one might ask why not use abstract class? With an interface the objects don't have to be directly related or inherited and you can still drive consistency across different classes.
public interface IMachine
{
bool Start();
bool Stop();
}
public class Car : IMachine
{
public bool Start()
{
Console.WriteLine("Car started");
return true;
}
public bool Stop()
{
Console.WriteLine("Car stopped");
return false;
}
}
public class Tank : IMachine
{
public bool Start()
{
Console.WriteLine("Tank started");
return true;
}
public bool Stop()
{
Console.WriteLine("Tank stopped");
return false;
}
}
class Program
{
static void Main(string[] args)
{
var car = new Car();
car.Start();
car.Stop();
var tank = new Tank();
tank.Start();
tank.Stop();
}
}
The difference between <pluginManagement/>
and <plugins/>
is that a <plugin/>
under:
<pluginManagement/>
defines the settings for plugins that will be inherited by modules in your build. This is great for cases where you have a parent pom file.
<plugins/>
is a section for the actual invocation of the plugins. It may or may not be inherited from a <pluginManagement/>
.
You don't need to have a <pluginManagement/>
in your project, if it's not a parent POM. However, if it's a parent pom, then in the child's pom, you need to have a declaration like:
<plugins>
<plugin>
<groupId>com.foo</groupId>
<artifactId>bar-plugin</artifactId>
</plugin>
</plugins>
Notice how you aren't defining any configuration. You can inherit it from the parent, unless you need to further adjust your invocation as per the child project's needs.
For more specific information, you can check:
The Maven pom.xml reference: Plugins
The Maven pom.xml reference: Plugin Management
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:
Add to your footer and header this CSS:
position: relative;
EDITED:
Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...
Remove From the #backstretch:
z-index: -999999;
Read a little bit about Z-Index here!
I want to enhance Mr. Kamran Ali's answer with pictorial view.
- Go to "Database" Menu option
- Select the "Reverse Engineer" option.
- A wizard will come. Select from "Stored Connection" and press "Next" button.
- Then "Next"..to.."Finish"
Enjoy :)
In A1 of your new sheet, put this:
=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)
... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.
If you want to copy the nth line but multiple columns, use the formula:
=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)
This can be copied right too.
You can do it with PhantomJSDriver.
PhantomJSDriver pd = ((PhantomJSDriver) ((WebDriverFacade) getDriver()).getProxiedDriver());
pd.executePhantomJS(
"this.onResourceRequested = function(request, net) {" +
" net.setHeader('header-name', 'header-value')" +
"};");
Using the request object, you can filter also so the header won't be set for every request.
In 2019, I would suggest putting all the item animations into the ItemAnimator.
Let's start with declaring the animator in the recycler-view:
with(view.recycler_view) {
adapter = Adapter()
itemAnimator = CustomAnimator()
}
Declare the custom animator then,
class CustomAnimator() : DefaultItemAnimator() {
override fun animateAppearance(
holder: RecyclerView.ViewHolder,
preInfo: ItemHolderInfo?,
postInfo: ItemHolderInfo): Boolean{} // declare what happens when a item appears on the recycler view
override fun animatePersistence(
holder: RecyclerView.ViewHolder,
preInfo: ItemHolderInfo,
postInfo: ItemHolderInfo): Boolean {} // declare animation for items that persist in a recycler view even when the items change
}
Similar to the ones above there is one for disappearance animateDisappearance
, for add animateAdd
, for change animateChange
and move animateMove
.
One important point would be to call the correct animation-dispatchers inside them.
grep has a -P switch allowing to use perl regexp syntax the perl regex allows to look at bytes, using \x.. syntax.
so you can look for a given hex string in a file with: grep -aP "\xdf"
but the outpt won't be very useful; indeed better do a regexp on the hexdump output;
The grep -P can be useful however to just find files matrching a given binary pattern. Or to do a binary query of a pattern that actually happens in text (see for example How to regexp CJK ideographs (in utf-8) )
Highlight the cells, format cells, select Custom then select zero.
Dictionary:
Hashtable:
I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:
create table destination_old as select * from destination;
drop table destination;
create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;
It's safe because you have a copy of destination
before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.
Using the pattern above you end up with two country
fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old
and perhaps using coalesce
to retrieve the values from destination_old
if the country
field in source
is null. So for example:
create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
If your goal is to use the ActionLink helper and open a new tab:
@Html.ActionLink("New tab please", "Home", null , new { target = "_blank" })
@Html.ActionLink("New tab please", "Home", Nothing, New With {Key .target = "_blank"})
Static variables in the context of a class are shared between all instances of a class.
In a function, it remains a persistent variable, so you could for instance count the number of times a function has been called.
When used outside of a function or class, it ensures the variable can only be used by code in that specific file, and nowhere else.
Constant variables however are prevented from changing. A common use of const and static together is within a class definition to provide some sort of constant.
class myClass {
public:
static const int TOTAL_NUMBER = 5;
// some public stuff
private:
// some stuff
};
I have handled back and Home button in Navigation Drawer like
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
NavigationView navigationView;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
//showing first fragment on Start
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//listener for home
if(id==android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Begin the transaction
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.nav_companies_list) {
fragment = new FirstFragment();
// Handle the action
}
// Begin the transaction
if(fragment!=null){
if(item.isChecked()){
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.WikiCompany, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
drawerToggle.setDrawerIndicatorEnabled(false);
else
drawerToggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
and In each onViewCreated
I call
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((HomeActivity)getActivity()).updateDrawerIcon();
((HomeActivity) getActivity()).setActionBarTitle("List");
}
As an extension to @JBNizet's answer for more technical users here's what implementation of org.w3c.dom.Node
interface in com.sun.org.apache.xerces.internal.dom.ParentNode
looks like, gives you the idea how it actually works.
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid;
for (kid = firstChild; kid != null; kid = kid.nextSibling) {
kid.normalize();
}
isNormalized(true);
}
It traverses all the nodes recursively and calls kid.normalize()
This mechanism is overridden in org.apache.xerces.dom.ElementImpl
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid, next;
for (kid = firstChild; kid != null; kid = next) {
next = kid.nextSibling;
// If kid is a text node, we need to check for one of two
// conditions:
// 1) There is an adjacent text node
// 2) There is no adjacent text node, but kid is
// an empty text node.
if ( kid.getNodeType() == Node.TEXT_NODE )
{
// If an adjacent text node, merge it with kid
if ( next!=null && next.getNodeType() == Node.TEXT_NODE )
{
((Text)kid).appendData(next.getNodeValue());
removeChild( next );
next = kid; // Don't advance; there might be another.
}
else
{
// If kid is empty, remove it
if ( kid.getNodeValue() == null || kid.getNodeValue().length() == 0 ) {
removeChild( kid );
}
}
}
// Otherwise it might be an Element, which is handled recursively
else if (kid.getNodeType() == Node.ELEMENT_NODE) {
kid.normalize();
}
}
// We must also normalize all of the attributes
if ( attributes!=null )
{
for( int i=0; i<attributes.getLength(); ++i )
{
Node attr = attributes.item(i);
attr.normalize();
}
}
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
isNormalized(true);
}
Hope this saves you some time.
Just an example of how I fixed the problem in an array to load a listView, hope it helps.
mItems = new ArrayList<ListViewItem>();
// Resources resources = getResources();
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.az_lgo), getString(R.string.st_az), getString(R.string.all_nums)));
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.ca_lgo), getString(R.string.st_ca), getString(R.string.all_nums)));
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.co_lgo), getString(R.string.st_co), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.az_lgo, null), getString(R.string.st_az), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.ca_lgo, null), getString(R.string.st_ca), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.co_lgo, null), getString(R.string.st_co), getString(R.string.all_nums)));
Following are eight ways to find the Uptime in Windows OS.
In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.
The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.
The systeminfo
command line utility checks and displays various system statistics such as installation date, installed hotfixes and more.
Open a Command Prompt and type the following command:
systeminfo
You can also narrow down the results to just the line you need:
systeminfo | find "System Boot Time:"
Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.
Read the following KB for more info and for the download links:
To use it, follow these steps:
uptime.exe
utility. You can add a /? to the command in order
to get more options.
It does not offer many command line parameters:
C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
-V display version
C:\uptimefromcodeplex\> uptime -V
version 1.1.0
There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)
Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)
C:\uptimev100download>uptime.exe /?
UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation
Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
server Name or IP address of remote server to process.
/s Display key system events and statistics.
/a Display application failure events (assumes /s).
/d: Only calculate for events after mm/dd/yyyy.
/p: Only calculate for events in the previous n days.
/heartbeat Turn on/off the system's heartbeat
/? Basic usage.
/help Additional usage information.
Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:
net statistics workstation
The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.
Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.
Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.
Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.
Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}
GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.
wmic os get lastbootuptime
Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h
command-line parameter).
Additionally, this version of uptime.exe
will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:
and when executed as uptime -h
:
Upgrading to Tensorflow 2.0 using pip. Requires Python > 3.4 and pip >= 19.0
CST:~ USERX$ pip3 show tensorflow
Name: tensorflow
Version: 1.13.1
CST:~ USERX$ python3 --version
Python 3.7.3
CST:~ USERX$ pip3 install --upgrade tensorflow
CST:~ USERX$ pip3 show tensorflow
Name: tensorflow
Version: 2.0.0
dec2hex = function (d) {
if (d > 15)
{ return d.toString(16) } else
{ return "0" + d.toString(16) }
}
rgb = function (r, g, b) { return "#" + dec2hex(r) + dec2hex(g) + dec2hex(b) };
and:
parent.childNodes[1].style.color = rgb(155, 102, 102);
CREATE FUNCTION DBO.ConvertDateToVarchar
(
@DATE DATETIME
)
RETURNS VARCHAR(24)
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),@DATE, 121))
END
Just use Hour
and Minute
properties
var date = DateTime.Now;
date.Hour;
date.Minute;
Or you can easily zero the seconds using
var zeroSecondDate = date.AddSeconds(-date.Second);
Here follows the only solutions that worked for me. Add this to the Host node in the conf/server.xml
<Context path="" docBase="yourAppContextName">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
go to Tomcat server.xml file and set path blank
According to @artfulrobot, this should be faster than filter and lambda:
import re
re.sub(r'[^\x00-\x7f]',r'', your-non-ascii-string)
See more examples here Replace non-ASCII characters with a single space
This is the question all others as well as Google redirect to so I'm posting this here.
Many of these answers are correct but too cumbersome for simple situations such as when you don't have over 26 columns. If you have any doubt whether you might go into double character columns then ignore this answer, but if you're sure you won't, then you could do it as simple as this in C#:
public static char ColIndexToLetter(short index)
{
if (index < 0 || index > 25) throw new ArgumentException("Index must be between 0 and 25.");
return (char)('A' + index);
}
Heck, if you're confident about what you're passing in you could even remove the validation and use this inline:
(char)('A' + index)
This will be very similar in many languages so you can adapt it as needed.
Again, only use this if you're 100% sure you won't have more than 26 columns.
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
Then you can assign a value to the member variable n.
To "find where the data I get comes from", you can start SQL Profiler, start your report or application, and you will see all the queries issued against your database.
There is no need to destroy current instance, just refresh.
$('#datepicker')
.datepicker('option', 'minDate', new Date)
.datepicker('refresh');
I know this is an old thread but you can also get some useful info from the V$INSTANCE
view as well. the V$DATABASE
displays info from the control file, the V$INSTANCE
view displays state of the current instance.
This construction is not allowed in SQL Server. An inline table-valued function can perform as a parameterized view, but is still not allowed to call an SP like this.
Here's some examples of using an SP and an inline TVF interchangeably - you'll see that the TVF is more flexible (it's basically more like a view than a function), so where an inline TVF can be used, they can be more re-eusable:
CREATE TABLE dbo.so916784 (
num int
)
GO
INSERT INTO dbo.so916784 VALUES (0)
INSERT INTO dbo.so916784 VALUES (1)
INSERT INTO dbo.so916784 VALUES (2)
INSERT INTO dbo.so916784 VALUES (3)
INSERT INTO dbo.so916784 VALUES (4)
INSERT INTO dbo.so916784 VALUES (5)
INSERT INTO dbo.so916784 VALUES (6)
INSERT INTO dbo.so916784 VALUES (7)
INSERT INTO dbo.so916784 VALUES (8)
INSERT INTO dbo.so916784 VALUES (9)
GO
CREATE PROCEDURE dbo.usp_so916784 @mod AS int
AS
BEGIN
SELECT *
FROM dbo.so916784
WHERE num % @mod = 0
END
GO
CREATE FUNCTION dbo.tvf_so916784 (@mod AS int)
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM dbo.so916784
WHERE num % @mod = 0
)
GO
EXEC dbo.usp_so916784 3
EXEC dbo.usp_so916784 4
SELECT * FROM dbo.tvf_so916784(3)
SELECT * FROM dbo.tvf_so916784(4)
DROP FUNCTION dbo.tvf_so916784
DROP PROCEDURE dbo.usp_so916784
DROP TABLE dbo.so916784
Here are two methods to achieve the same thing:
Using parameters and return (recommended)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print(x)
x = other_function(x)
print(x)
When you run main_function
, you'll get the following output
>>> 10
>>> 15
Using globals (never do this)
x = 0 # The initial value of x, with global scope
def other_function():
global x
x = x + 5
def main_function():
print(x) # Just printing - no need to declare global yet
global x # So we can change the global x
x = 10
print(x)
other_function()
print(x)
Now you will get:
>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
This question is a old one but it can help for others too.
Try this :
li.setBackgroundColor(getResources().getColor(R.color.blue));
or
li.setBackgroundColor(getResources().getColor(android.R.color.red));
or
li.setBackgroundColor(Color.rgb(226, 11, 11));
or
li.setBackgroundColor(Color.RED)
unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle
use
LDFLAGS= -L<Directory where the library resides> -l<library name>
Like :
LDFLAGS = -L. -lmine
for ensuring static compilation you can also add
LDFLAGS = -static
Or you can just get rid of the whole library searching, and link with with it directly.
say you have main.c fun.c
and a static library libmine.a
then you can just do in your final link line of the Makefile
$(CC) $(CFLAGS) main.o fun.o libmine.a
This solution works like many of the others, and in fact uses the same regex as one of them, however in stead of returning a HTML String this will return a document fragment containing the A element and any applicable text nodes.
function make_link(string) {
var words = string.split(' '),
ret = document.createDocumentFragment();
for (var i = 0, l = words.length; i < l; i++) {
if (words[i].match(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi)) {
var elm = document.createElement('a');
elm.href = words[i];
elm.textContent = words[i];
if (ret.childNodes.length > 0) {
ret.lastChild.textContent += ' ';
}
ret.appendChild(elm);
} else {
if (ret.lastChild && ret.lastChild.nodeType === 3) {
ret.lastChild.textContent += ' ' + words[i];
} else {
ret.appendChild(document.createTextNode(' ' + words[i]));
}
}
}
return ret;
}
There are some caveats, namely with older IE and textContent support.
here is a demo.
For Chrome/Chromium
console.log(myObj)
or it's equivalent
console.debug(myObj)
I would suggest the method presented on the Gradle forum:
def createMinifyCssTask(def brand, def sourceFile, def destFile) {
return tasks.create("minify${brand}Css", com.eriwen.gradle.css.tasks.MinifyCssTask) {
source = sourceFile
dest = destFile
}
}
I have used this method myself to create custom tasks, and it works very well.
For this example we take it for granted that varcharcol doesn't contain ''
and have no empty cell against this column
select * from some_table where varcharCol = ''
select * from some_table where varcharCol like ''
The first one results in 0 row output while the second one shows the whole list. = is strictly-match case while like acts like a filter. if filter has no criteria, every data is valid.
like - by the virtue of its purpose works a little slower and is intended for use with varchar and similar data.
You can do:
function a {
if [ ! -z "$1" ]; then
echo '$1 is set'
fi
}
Break
statement will break the whole loop and execute the code after loop and Return
will not execute the code after that return
statement and execute the loop with next increment.
Break
for(int i=0;i<5;i++){
print(i)
if(i==2)
{
break;
}
}
output: 0 1
return
for(int i=0;i<5;i++)
{
print(i)
if(i==2)
{
return;
}
}
output: 0 1 3 4
You can also use ng-template, I think that would be more efficient while run time :)
<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
<div>2</div>
</ng-template>
Cheers
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
serves two purposes.
IE=edge
: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.chrome=1
: specifies that Google Chrome frame should start if the user has it installedThe IE=edge
flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.
As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1
will do nothing more than consume a few bytes of bandwidth.
I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.
Note, the W3C validator will flag chrome=1
as an error:
Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.
If you don't want to reinvent the wheel, you can install the symbolic maths library sympy (yes it's Python 3 compatible)
pip install sympy
And use the primerange function
from sympy import sieve
primes = list(sieve.primerange(1, 10**6))
Keep a friend table that holds the UserID and then the UserID of the friend (we will call it FriendID). Both columns would be foreign keys back to the Users table.
Somewhat useful example:
Table Name: User
Columns:
UserID PK
EmailAddress
Password
Gender
DOB
Location
TableName: Friends
Columns:
UserID PK FK
FriendID PK FK
(This table features a composite primary key made up of the two foreign
keys, both pointing back to the user table. One ID will point to the
logged in user, the other ID will point to the individual friend
of that user)
Example Usage:
Table User
--------------
UserID EmailAddress Password Gender DOB Location
------------------------------------------------------
1 [email protected] bobbie M 1/1/2009 New York City
2 [email protected] jonathan M 2/2/2008 Los Angeles
3 [email protected] joseph M 1/2/2007 Pittsburgh
Table Friends
---------------
UserID FriendID
----------------
1 2
1 3
2 3
This will show that Bob is friends with both Jon and Joe and that Jon is also friends with Joe. In this example we will assume that friendship is always two ways, so you would not need a row in the table such as (2,1) or (3,2) because they are already represented in the other direction. For examples where friendship or other relations aren't explicitly two way, you would need to also have those rows to indicate the two-way relationship.
Even the last example given on http://www.howtocreate.co.uk/tutorials/javascript/browserwindow is not working on Quirks mode. Easier to find than I thought, this seems to be the solution(extracted from latest jquery code):
Math.max(
document.documentElement["clientWidth"],
document.body["scrollWidth"],
document.documentElement["scrollWidth"],
document.body["offsetWidth"],
document.documentElement["offsetWidth"]
);
just replace Width for "Height" to get Height.
On Windows 7, the Program Files directory is protected so apps can't automatically write there. The simplest solution I've heard is just to install Eclipse into a user-writable location instead. For example, C:\Java\Eclipse
You should be able to just move your entire eclipse directory, there's no registry entries or anything else that ties Eclipse to the place where you extracted it.
[Edit] Have you checked that the directory it is complaining about i actually writable? Other than that, I really don't have any ideas. I haven't worked on Windows in several years and never with Win7. My only other suggestion is to just download the latest Eclipse, install it to a new location (do NOT intall it over top of your existing Eclipse), and point it to your existing workspace.
A fun, simple solution:
for (int i = 0; i < 5; i++)
System.out.println(" *********".substring(i, 5 + 2*i));
LENGTH()
returns the length of the string measured in bytes.
CHAR_LENGTH()
returns the length of the string measured in characters.
This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:
select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1
As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC
in UTF-8) even though it's only one character.
An alternative list comprehension method that uses list index values:
stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
index = [0, 3, 6]
new = [i for i in stuff if stuff.index(i) not in index]
This returns:
['b', 'c', 'e', 'f']
Surprisingly this question doesn't have a definitive documented answer. Perhaps another data point would provide value to others looking for an answer. On my systems running CentOS (6.8,7.3) and Java 8 (build 1.8.0_60-b27, 64-Bit Server):
default memory is 1/4 of physical memory, not limited by 1GB.
Also, -XX:+PrintFlagsFinal
prints to STDERR so command to determine current default memory presented by others above should be tweaked to the following:
java -XX:+PrintFlagsFinal 2>&1 | grep MaxHeapSize
The following is returned on system with 64GB of physical RAM:
uintx MaxHeapSize := 16873684992 {product}
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
Install an interval:
<script type="text/javascript">
setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>
#include <conio.h>
if (kbhit() != 0) {
cout << getch() << endl;
}
This uses kbhit()
to check if the keyboard is being pressed and uses getch()
to get the character that is being pressed.
Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that
let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"
It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?
Very simple answer for this problem that seems to catch a lot of people:
<img src="url-to-image">
<p>Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
img {
float: left;
}
p {
overflow: hidden;
}
See example: http://jsfiddle.net/vandigroup/upKGe/132/
Presuming you're talking about dynamic runtime loading of DLLs, you're looking for LoadLibrary and GetProAddress. There's an example on MSDN.
$.ajax({
url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data) {
if (data.web == 0) {
if (confirm('Data product upToWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 1},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
else {
if (confirm('Data product DownFromWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 0},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
If you are using Linux OS:
matplotlib==1.3.1
from requirements.txt
sudo apt-get install python-matplotlib
pip install -r requirements.txt
(Python 2), or pip3 install -r requirements.txt
(Python 3)pip freeze > requirements.txt
If you are using Windows OS:
python -m pip install -U pip setuptools
python -m pip install matplotlib
Download angular js from this link and add as new software in eclipse http://oss.opensagres.fr/angularjs-eclipse/0.6.0/
res.sendFile
& express.static
both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public
is the folder in which the client side code is
As suggested by @ATOzTOA and clarified by @Vozzie, path.join
takes the paths to join as arguments, the +
passes a single argument to path.
You can manage your application versioning wisely by using the Advanced Build Version Plugin for Gradle.
You just need to include the plugin in yout build.gradle
:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.moallemi.gradle.advanced-build-version:gradle-plugin:1.5.0'
}
}
apply plugin: 'org.moallemi.advanced-build-version'
And then you can use the versioning functions (and, obviously, customize them):
advancedVersioning {
nameOptions { }
codeOptions { }
outputOptions { }
}
def appVersionName = advancedVersioning.versionName
def appVersionCode = advancedVersioning.versionCode
For more information, take a look at the official documentation.
Aside from @see
, a more general way of refering to another class and possibly method of that class is {@link somepackage.SomeClass#someMethod(paramTypes)}
. This has the benefit of being usable in the middle of a javadoc description.
From the javadoc documentation (description of the @link tag):
This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text.
Encounter the same error when tried to connect to SQLServer2017 through Management Studio 2014
The reason was backward compatibility
So I just downloaded the Management Studio 2017 and tried to connect to SQLServer2017.
Problem Solve!!
html, body {
height: 100%;
width: 100%;
}
html {
display: table;
margin: auto;
}
body {
padding-top: 50px;
display: table-cell;
}
div {
margin: auto;
}
This will center align objects and then also center align the items within them to center align multiple objects with different widths.
import java.util.Scanner; import javax.swing.JOptionPane;
public class javaCalculator {
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
Try this:
jsonResponse = json.loads(response.decode('utf-8'))
You turn off pack_propagate
by setting pack_propagate(0)
Turning off pack_propagate
here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally
To turn off resizing the root window, you can set root.resizable(0, 0)
, where resizing is allowed in the x
and y
directions respectively.
To set a maxsize to window, as noted in the other answer you can set the maxsize
attribute or minsize
although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.
Whenever you set grid
or pack
on a widget it will return None
. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid
or pack
on it. You should instead set the variable to be the widget Widget(master, ....)
and then call pack
or grid
on the widget instead.
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
must separate this code to work well, or it well pause and play in one click !
$('video').click(function(){this.played ? this.pause() ;});
$('video').click(function(){this.paused ? this.play() ;});
Don't miss Tab policy for both of * Spaces only * Use spaces to indent wrapped lines
I checked only the latter thing and left the Combobox as Tabs Only which kept failing CheckStyle.. FYI, I'm talking about Preferences > Java > Formatter > Edit...
To Truncate:
hive -e "TRUNCATE TABLE IF EXISTS $tablename"
To Drop:
hive -e "Drop TABLE IF EXISTS $tablename"
For pre API 8 i solved the problem using a boolean flag, a dismiss listener and calling dialog.show again if in case the content of the editText wasn´t correct. Like this:
case ADD_CLIENT:
LayoutInflater factoryClient = LayoutInflater.from(this);
final View EntryViewClient = factoryClient.inflate(
R.layout.alert_dialog_add_client, null);
EditText ClientText = (EditText) EntryViewClient
.findViewById(R.id.client_edit);
AlertDialog.Builder builderClient = new AlertDialog.Builder(this);
builderClient
.setTitle(R.string.alert_dialog_client)
.setCancelable(false)
.setView(EntryViewClient)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
EditText newClient = (EditText) EntryViewClient
.findViewById(R.id.client_edit);
String newClientString = newClient
.getText().toString();
if (checkForEmptyFields(newClientString)) {
//If field is empty show toast and set error flag to true;
Toast.makeText(getApplicationContext(),
"Fields cant be empty",
Toast.LENGTH_SHORT).show();
add_client_error = true;
} else {
//Here save the info and set the error flag to false
add_client_error = false;
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
add_client_error = false;
dialog.cancel();
}
});
final AlertDialog alertClient = builderClient.create();
alertClient.show();
alertClient
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
//If the error flag was set to true then show the dialog again
if (add_client_error == true) {
alertClient.show();
} else {
return;
}
}
});
return true;
Capture the onContextMenu
event, and return false in the event handler.
You can also capture the click event and check which mouse button fired the event with event.button
, in some browsers anyway.
In Swift:
Changing the label text color is quite different than changing it for a UIButton
. To change the text color for a UIButton
use this method:
self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)
If you want to find the button only by its class name and using jQLite only, you can do like below:
var myListButton = $document.find('button').filter(function() {
return angular.element(this).hasClass('multi-files');
});
Hope this helps. :)
Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)
use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";
This gives you:
14.05.2014
double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));
change database collation:
ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
change table collation:
ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
change column collation:
ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
utf8mb4_0900_ai_ci
mean?3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 -- _unicode_
v5.20 -- _unicode_520_
v9.0 -- _0900_ (new)
_bin -- just compare the bits; don't consider case folding, accents, etc
_ci -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin -- simple, fast
_general_ci -- fails to compare multiple letters; eg ss=ß, somewhat fast
... -- slower
_0900_ -- (8.0) much faster because of a rewrite
More info:
I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.
Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.
var validations ={
email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
// Check all the input fields of type email. This function will handle all the email addresses validations
$("input[type=email]").change( function(){
// Set the regular expression to validate the email
validation = new RegExp(validations['email'][0]);
// validate the email value against the regular expression
if (!validation.test(this.value)){
// If the validation fails then we show the custom error message
this.setCustomValidity(validations['email'][1]);
return false;
} else {
// This is really important. If the validation is successful you need to reset the custom error message
this.setCustomValidity('');
}
});
})
Usually this happens if something is wrong with the byte array.
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Asynchronous implementation of this is also available.
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
Use String#next
as the counter.
>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003
next
is relatively 'clever', meaning you can even go for
>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003
Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.
If you already have a dictionary, a counter can easily be formed by:
c = Counter(d['123'])
as an example from your data.
The most_common
function allows easy access to descending order of the items in the counter
The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html
You can use the data function of the vector:
Returns a pointer to the first element in the vector.
If don't want the pointer to the first element, but by index, then you can try, for example:
//the index to the element that you want to receive its pointer:
int i = n; //(n is whatever integer you want)
std::vector<myObject> vec;
myObject* ptr_to_first = vec.data();
//or
std::vector<myObject>* vec;
myObject* ptr_to_first = vec->data();
//then
myObject element = ptr_to_first[i]; //element at index i
myObject* ptr_to_element = &element;
The new tag for recent Chrome and Chromium browsers is :
--disable-web-security --user-data-dir=c:\my\data
Your code (vector1 == vector2
) is correct C++ syntax. There is an ==
operator for vectors.
If you want to compare short vector with a portion of a longer vector, you can use theequal()
operator for vectors. (documentation here)
Here's an example:
using namespace std;
if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
DoSomething();
byte b = (byte)0xC8;
int v1 = b; // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)
Most of the time v2 is the way you really need.
A simple example of testing Tesseract OCR in C#:
public static string GetText(Bitmap imgsource)
{
var ocrtext = string.Empty;
using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
{
using (var img = PixConverter.ToPix(imgsource))
{
using (var page = engine.Process(img))
{
ocrtext = page.GetText();
}
}
}
return ocrtext;
}
Info: The tessdata folder must exist in the repository: bin\Debug\
No.
If the user is sophisticated or determined enough to:
then they are probably sophisticated or determined enough to:
So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.
Using Collections#addAll()
String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>();
Collections.addAll(arrayList, words);
Use MyDialog md = new MyDialog(MyActivity.this.getParent());
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
Somthing like this should workL
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()
Like from any regular input/select/etc...:
$("form.my-form .chosen-select").val()
This ip link | grep -A1 wlan0
command works on Android 9 from How to determine wifi hardware address in Termux
You can do as follows:
Select Format(test.Time, 'yyyyMMdd')
From TableTest test
For deep nested object and arrays. and exclude empty values from string and NaN
function isBlank(value) {
return _.isEmpty(value) && !_.isNumber(value) || _.isNaN(value);
}
var removeObjectsWithNull = (obj) => {
return _(obj).pickBy(_.isObject)
.mapValues(removeObjectsWithNull)
.assign(_.omitBy(obj, _.isObject))
.assign(_.omitBy(obj, _.isArray))
.omitBy(_.isNil).omitBy(isBlank)
.value();
}
var obj = {
teste: undefined,
nullV: null,
x: 10,
name: 'Maria Sophia Moura',
a: null,
b: '',
c: {
a: [{
n: 'Gleidson',
i: 248
}, {
t: 'Marta'
}],
g: 'Teste',
eager: {
p: 'Palavra'
}
}
}
removeObjectsWithNull(obj)
result:
{
"c": {
"a": [
{
"n": "Gleidson",
"i": 248
},
{
"t": "Marta"
}
],
"g": "Teste",
"eager": {
"p": "Palavra"
}
},
"x": 10,
"name": "Maria Sophia Moura"
}
You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText()
on the label and pass it the text from the text field.
Example:
label1.setText(nameField.getText());
You can also use std::vectors
for achieving this:
using std::vector< std::vector<int> >
Example:
std::vector< std::vector<int> > a;
//m * n is the size of the matrix
int m = 2, n = 4;
//Grow rows by m
a.resize(m);
for(int i = 0 ; i < m ; ++i)
{
//Grow Columns by n
a[i].resize(n);
}
//Now you have matrix m*n with default values
//you can use the Matrix, now
a[1][0]=1;
a[1][1]=2;
a[1][2]=3;
a[1][3]=4;
//OR
for(i = 0 ; i < m ; ++i)
{
for(int j = 0 ; j < n ; ++j)
{ //modify matrix
int x = a[i][j];
}
}
Yo can simply google for "exit sub in c#".
Also why would you check every text box if it is empty. You can place requiredfieldvalidator for these text boxes if this is an asp.net app and check if(Page.IsValid)
Or another solution is to get not of these conditions:
private void button1_Click(object sender, EventArgs e)
{
if (!(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""))
{
//do events
}
}
And better use String.IsNullOrEmpty:
private void button1_Click(object sender, EventArgs e)
{
if (!(String.IsNullOrEmpty(textBox1.Text)
|| String.IsNullOrEmpty(textBox2.Text)
|| String.IsNullOrEmpty(textBox3.Text)))
{
//do events
}
}
To match either / or end of content, use (/|\z)
This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).
To put that with an updated version of what you had:
/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)
Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+?
) rather than matching anything and everything ( .*
)
SELECT p.LastName, p.FirstName, o.OrderNo
FROM persons AS p
LEFT JOIN
orders AS o
ON o.orderNo = p.p_id
UNION ALL
SELECT NULL, NULL, orderNo
FROM orders
WHERE orderNo NOT IN
(
SELECT p_id
FROM persons
)
print(df.isnull().sum()) # check numbers of null value in each column
modifiedDf=df.fillna("NaN") # Replace empty/null values with "NaN"
# modifiedDf = fd.dropna() # Remove rows with empty values
print(modifiedDf.isnull().sum()) # check numbers of null value in each column
The second one creates a new array of Integers (first pass), and then adds all the elements of this new array to the list (second pass). It will thus be less efficient than the first one, which makes a single pass and doesn't create an unnecessary array of Integers.
A better way to use streams would be
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
Which should have roughly the same performance as the first one.
Note that for such a small array, there won't be any significant difference. You should try to write correct, readable, maintainable code instead of focusing on performance.
for MS excel 2000 office version, click on the pivot table you will find a tab above the ribon, called Pivottable tool - click on that You can change data source from Data tab
I'm going to take a stab in the dark and guess you're talking about Windows. In a nutshell, kernel mode has full access to hardware, but user mode doesn't. For instance, many if not most device drivers are written in kernel mode because they need to control finer details of their hardware.
See also this wikibook.
I had the problem due to an extra space in the name of the linked server. "SERVER1, 1234" instead of "SERVER1,1234"
You can add it by appending a Series to the dataframe as follows. I am assuming by blank you mean you want to add a row containing only "Nan". You can first create a Series object with Nan. Make sure you specify the columns while defining 'Series' object in the -Index parameter. The you can append it to the DF. Hope it helps!
from numpy import nan as Nan
import pandas as pd
>>> df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
... 'B': ['B0', 'B1', 'B2', 'B3'],
... 'C': ['C0', 'C1', 'C2', 'C3'],
... 'D': ['D0', 'D1', 'D2', 'D3']},
... index=[0, 1, 2, 3])
>>> s2 = pd.Series([Nan,Nan,Nan,Nan], index=['A', 'B', 'C', 'D'])
>>> result = df1.append(s2)
>>> result
A B C D
0 A0 B0 C0 D0
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A3 B3 C3 D3
4 NaN NaN NaN NaN
As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.
new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1
For anyone who may stumble across this thread while trying to fix this same error that results by running Enable-Migrations
, chances are none of the solutions above will help you (I tried them all).
I encountered this same issue in Web API 2 after running this in PM console:
Enable-Migrations -EnableAutomaticMigrations -ConnectionString IdentityConnection -ConnectionProviderName System.Data.SqlClient -Force
I fixed it by changing it to actually use the ApplicationDbContext
created in IdentityModels
.
Enable-Migrations -ContextTypeName ApplicationDbContext -EnableAutomaticMigrations -Force
The interesting thing is not only does this reference the same exact connection string, but the constructor includes code that 4castle said was a potential fix (i.e., the throwIfV1Schema: false
suggestion.
Note that the -Force
parameter is only being used because the Configuration.cs
file already exists.
I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:
$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');
Looking at the phpmailer code in more detail this is the offending line:
public function SetFrom($address, $name = '',$auto=1) {
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (!self::ValidateAddress($address)) {
$this->SetError($this->Lang('invalid_address').': '. $address);
if ($this->exceptions) {
throw new phpmailerException($this->Lang('invalid_address').': '.$address);
}
echo $this->Lang('invalid_address').': '.$address;
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto) {
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
if (empty($this->Sender)) {
$this->Sender = $address;
}
}
return true;
}
Specifically this line:
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
Thanks for your help everyone!
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
I had the same problem (I'm running cygwin)
Starting a shell through cygwin.bat didn't help, but starting a shell through MingWShell did. Not quite sure why, but I think it had something to do with the extra layer that cygwin puts between the executing script and the underlying filesystem.
I was running pip install from within a virtual env's cygwin to install django sentry..
I know this post is a couple years old, but I keep running into this and I'm not happy with the service locator pattern.
Also, I know the OP is looking for an implementation which allows you to choose a concrete implementation based on a string. I also realize that the OP is specifically asking for an implementation of an identical interface. The solution I'm about to describe relies on adding a generic type parameter to your interface. The problem is that you don't have any real use for the type parameter other than service collection binding. I'll try to describe a situation which might require something like this.
Imagine configuration for such a scenario in appsettings.json which might look something like this (this is just for demonstration, your configuration can come from wherever you want as long as you have the correction configuration provider):
{
"sqlDataSource": {
"connectionString": "Data Source=localhost; Initial catalog=Foo; Connection Timeout=5; Encrypt=True;",
"username": "foo",
"password": "this normally comes from a secure source, but putting here for demonstration purposes"
},
"mongoDataSource": {
"hostName": "uw1-mngo01-cl08.company.net",
"port": 27026,
"collection": "foo"
}
}
You really need a type that represents each of your configuration options:
public class SqlDataSource
{
public string ConnectionString { get;set; }
public string Username { get;set; }
public string Password { get;set; }
}
public class MongoDataSource
{
public string HostName { get;set; }
public string Port { get;set; }
public string Collection { get;set; }
}
Now, I know that it might seem a little contrived to have two implementations of the same interface, but it I've definitely seen it in more than one case. The ones I usually come across are:
Anyway, you can reference them by adding a type parameter to your service interface so that you can implement the different implementations:
public interface IService<T> {
void DoServiceOperation();
}
public class MongoService : IService<MongoDataSource> {
private readonly MongoDataSource _options;
public FooService(IOptionsMonitor<MongoDataSource> serviceOptions){
_options = serviceOptions.CurrentValue
}
void DoServiceOperation(){
//do something with your mongo data source options (connect to database)
throw new NotImplementedException();
}
}
public class SqlService : IService<SqlDataSource> {
private readonly SqlDataSource_options;
public SqlService (IOptionsMonitor<SqlDataSource> serviceOptions){
_options = serviceOptions.CurrentValue
}
void DoServiceOperation(){
//do something with your sql data source options (connect to database)
throw new NotImplementedException();
}
}
In startup, you'd register these with the following code:
services.Configure<SqlDataSource>(configurationSection.GetSection("sqlDataSource"));
services.Configure<MongoDataSource>(configurationSection.GetSection("mongoDataSource"));
services.AddTransient<IService<SqlDataSource>, SqlService>();
services.AddTransient<IService<MongoDataSource>, MongoService>();
Finally in the class which relies on the Service with a different connection, you just take a dependency on the service you need and the DI framework will take care of the rest:
[Route("api/v1)]
[ApiController]
public class ControllerWhichNeedsMongoService {
private readonly IService<MongoDataSource> _mongoService;
private readonly IService<SqlDataSource> _sqlService ;
public class ControllerWhichNeedsMongoService(
IService<MongoDataSource> mongoService,
IService<SqlDataSource> sqlService
)
{
_mongoService = mongoService;
_sqlService = sqlService;
}
[HttpGet]
[Route("demo")]
public async Task GetStuff()
{
if(useMongo)
{
await _mongoService.DoServiceOperation();
}
await _sqlService.DoServiceOperation();
}
}
These implementations can even take a dependency on each other. The other big benefit is that you get compile-time binding so any refactoring tools will work correctly.
Hope this helps someone in the future.
Have you tried using @JsonProperty?
@Entity
public class City {
@id
Long id;
String name;
@JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
@JsonProperty("value")
public Long getId() { return id; }
public void setId(Long id){ this.id = id; }
}
for a simple csv one map() and a join() are enough:
var csv = test_array.map(function(d){
return d.join();
}).join('\n');
/* Results in
name1,2,3
name2,4,5
name3,6,7
name4,8,9
name5,10,11
This method also allows you to specify column separator other than a comma in the inner join
. for example a tab: d.join('\t')
On the other hand if you want to do it properly and enclose strings in quotes ""
, then you can use some JSON magic:
var csv = test_array.map(function(d){
return JSON.stringify(d);
})
.join('\n')
.replace(/(^\[)|(\]$)/mg, ''); // remove opening [ and closing ] brackets from each line
/* would produce
"name1",2,3
"name2",4,5
"name3",6,7
"name4",8,9
"name5",10,11
if you have array of objects like :
var data = [
{"title": "Book title 1", "author": "Name1 Surname1"},
{"title": "Book title 2", "author": "Name2 Surname2"},
{"title": "Book title 3", "author": "Name3 Surname3"},
{"title": "Book title 4", "author": "Name4 Surname4"}
];
// use
var csv = data.map(function(d){
return JSON.stringify(Object.values(d));
})
.join('\n')
.replace(/(^\[)|(\]$)/mg, '');
You have to cast one (or both) of the arguments to the division operator to double
:
double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);
Since you are performing the same calculation twice I'd recommend refactoring your code:
double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;
This works in the same way, but now there is an implicit cast to double. This conversion from int
to double
is an example of a widening primitive conversion.
F5 reloads the page from server, but it uses the browser's cache for page elements like scripts, image, CSS stylesheets, etc, etc. But Ctrl + F5, reloads the page from the server and also reloads its contents from server and doesn't use local cache at all.
So by pressing F5 on, say, the Yahoo homepage, it just reloads the main HTML frame and then loads all other elements like images from its cache. If a new element was added or changed then it gets it from the server. But Ctrl + F5 reloads everything from the server.
Yes, all browsers should not submit the disabled inputs, as they are read-only.
More information (section 17.12.1)
Attribute definitions
disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:
- Disabled controls do not receive focus.
- Disabled controls are skipped in tabbing navigation.
- Disabled controls cannot be successful.
The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.
This attribute is inherited but local declarations override the inherited value.
How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.
In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.
<INPUT disabled name="fred" value="stone">
Note. The only way to modify dynamically the value of the disabled attribute is through a script.
In most cases, it is enough just to hide the element, for example in this way:
export default class ErrorBoxComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isHidden: false
}
}
dismiss() {
this.setState({
isHidden: true
})
}
render() {
if (!this.props.error) {
return null;
}
return (
<div data-alert className={ "alert-box error-box " + (this.state.isHidden ? 'DISPLAY-NONE-CLASS' : '') }>
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>×</a>
</div>
);
}
}
Or you may render/rerender/not render via parent component like this
export default class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isErrorShown: true
}
}
dismiss() {
this.setState({
isErrorShown: false
})
}
showError() {
if (this.state.isErrorShown) {
return <ErrorBox
error={ this.state.error }
dismiss={ this.dismiss.bind(this) }
/>
}
return null;
}
render() {
return (
<div>
{ this.showError() }
</div>
);
}
}
export default class ErrorBoxComponent extends React.Component {
dismiss() {
this.props.dismiss();
}
render() {
if (!this.props.error) {
return null;
}
return (
<div data-alert className="alert-box error-box">
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>×</a>
</div>
);
}
}
Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.
export default class ErrorBoxComponent extends React.Component {
dismiss() {
this.el.remove();
}
render() {
if (!this.props.error) {
return null;
}
return (
<div data-alert className="alert-box error-box" ref={ (el) => { this.el = el} }>
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>×</a>
</div>
);
}
}
I had this issue with AOSP (clang).
Add external\libcxx\include
to includes and _LIBCPP_COMPILER_CLANG
to symbols
Before applying WORKDIR. Here the WORKDIR is at the wrong place and is not used wisely.
FROM microsoft/aspnetcore:2
COPY --from=build-env /publish /publish
WORKDIR /publish
ENTRYPOINT ["dotnet", "/publish/api.dll"]
We corrected the above code to put WORKDIR at the right location and optimised the following statements by removing /Publish
FROM microsoft/aspnetcore:2
WORKDIR /publish
COPY --from=build-env /publish .
ENTRYPOINT ["dotnet", "api.dll"]
So it acts like a cd
and sets the tone for the upcoming statements.
You need a terminal multiplexer like either tmux or GNU screen
I'm surprised that a small comment by Ryan Amos' to the original question is the only mention of a solution far preferable to all the others on offer, no matter how clever the python trickery may be and how many upvotes they've received. Further to Ryan's comment, tmux is a nice alternative to GNU screen.
But the principle is the same: if you ever find yourself wanting to leave a terminal job running while you log-out, head to the cafe for a sandwich, pop to the bathroom, go home (etc) and then later, reconnect to your terminal session from anywhere or any computer as though you'd never been away, terminal multiplexers are the answer. Think of them as VNC or remote desktop for terminal sessions. Anything else is a workaround. As a bonus, when the boss and/or partner comes in and you inadvertently ctrl-w / cmd-w your terminal window instead of your browser window with its dodgy content, you won't have lost the last 18 hours-worth of processing!
Java SE Development Kit 9 is not compatible with the Netbeans IDE 8.2.
My Solution:
Have you installed it?
On debian/ubuntu:
aptitude install python-numpy
On windows:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems:
http://sourceforge.net/projects/numpy/files/NumPy/
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
open f, "test.txt"
$file = join '', <f>
<f>
- returns an array of lines from our file (if $/
has the default value "\n"
) and then join ''
will stick this array into.
Those settings has moved into the .csproj file.
By default they don't show up but you can discover them from Visual Studio 2017 in the project properties Package
tab.
Once saved those values can be found in MyProject.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
<Version>1.2.3.4</Version>
<Authors>Author 1</Authors>
<Company>Company XYZ</Company>
<Product>Product 2</Product>
<PackageId>MyApp</PackageId>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
<FileVersion>3.0.0.0</FileVersion>
<NeutralLanguage>en</NeutralLanguage>
<Description>Description here</Description>
<Copyright>Copyright</Copyright>
<PackageLicenseUrl>License URL</PackageLicenseUrl>
<PackageProjectUrl>Project URL</PackageProjectUrl>
<PackageIconUrl>Icon URL</PackageIconUrl>
<RepositoryUrl>Repo URL</RepositoryUrl>
<RepositoryType>Repo type</RepositoryType>
<PackageTags>Tags</PackageTags>
<PackageReleaseNotes>Release</PackageReleaseNotes>
</PropertyGroup>
In the file explorer properties information tab, FileVersion
is shown as "File Version" and Version
is shown as "Product version"
The above answers seem to resolve the issue. If it doesn't, then you may also try to update conda using the following command.
conda update conda
And then try to install numpy using
conda install numpy
Pushing to the limits corner radius up to get a circle:
self.btnFoldButton.layer.cornerRadius = self.btnFoldButton.frame.height/2.0;
If button frame is an square it does not matter frame.height or frame.width. Otherwise use the largest of both ones.
In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")
My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.
Use nm -a your.dylib
It will print all the symbols including globals
You can use the parse
method from the URL module in the request callback.
var http = require('http');
var url = require('url');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});
if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
response.end('Hello ' + queryData.name + '\n');
} else {
response.end("Hello World\n");
}
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
I suggest you read the HTTP module documentation to get an idea of what you get in the createServer
callback. You should also take a look at sites like http://howtonode.org/ and checkout the Express framework to get started with Node faster.
I'd use the code in the original question, but if you really wanted to use foreach and have an integer index in C#:
foreach (int i in Enumerable.Range(0, myArray.Length).Reverse())
{
myArray[i] = 42;
}
You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.
WITH PercentageOfTotal (Id, Percentage)
AS
(
SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT
CASE
WHEN o.TotalType = 'Average' THEN r.avgscore
WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
ELSE o.cnt
END AS [displayscore]
FROM PercentageOfTotal pt
JOIN dbo.MyTable t ON pt.Id = t.Id
You can also use fpdf class available at: http://www.fpdf.org. It gives options for both outputting to a file and displaying on browser.
Use BigDecimal
:
new BigDecimal(theInputString);
It retains all decimal digits. And you are sure of the exact representation since it uses decimal base, not binary base, to store the precision/scale/etc.
And it is not subject to precision loss like float
or double
are, unless you explicitly ask it to.
since python-daemon has not yet supported python 3.x, and from what can be read on the mailing list, it may never will, i have written a new implementation of PEP 3143: pep3143daemon
pep3143daemon should support at least python 2.6, 2.7 and 3.x
It also contains a PidFile class.
The library only depends on the standard library and on the six module.
It can be used as a drop in replacement for python-daemon.
Here is the documentation.
From Bloch, J., Effective Java, 2nd ed, Item 48:
The
float
anddouble
types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as afloat
ordouble
exactly.For example, suppose you have $1.03 and you spend 42c. How much money do you have left?
System.out.println(1.03 - .42);
prints out
0.6100000000000001
.The right way to solve this problem is to use
BigDecimal
,int
orlong
for monetary calculations.
Though BigDecimal
has some caveats (please see currently accepted answer).
Duplicate the string, tokenize it, then free it.
char *dup = strdup(str.c_str());
token = strtok(dup, " ");
free(dup);
UI_USER_INTERFACE_IDIOM()
only returns iPad if the app is for iPad or Universal. If its an iPhone app running on an iPad then it won't. So you should instead check the model.
Look at using the beautiful soup html parsing library.
http://www.crummy.com/software/BeautifulSoup/
You will do something like this:
import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
for link in soup.findAll("a"):
print link.get("href")
GIMP tool is exactly what you need to create the images for different pixel resolution devices.
Follow these steps:
Use below pixel dimension that you need:
xxxhdpi: 1280x1920 px
xxhdpi: 960x1600 px
xhdpi: 640x960 px
hdpi: 480x800 px
mdpi: 320x480 px
ldpi: 240x320 px
Then "Export" the image from "File" menu.
If you'd checked the results of stream.Read
, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;
.) However, it's easier to just call ToArray
:
settingsString = LocalEncoding.GetString(stream.ToArray());
(You'll need to change the type of stream
from Stream
to MemoryStream
, but that's okay as it's in the same method where you create it.)
Alternatively - and even more simply - just use StringWriter
instead of StreamWriter
. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.
I'm concerned by the way you're just catching Exception
and assuming that it means something harmless, by the way - without even logging anything. Note that using
statements are generally cleaner than writing explicit finally
blocks.
Try
var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);
I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.
Timing:
|------------|----------------|-------------------|
| | shape (10000) | shape (1,10000) |
|------------|----------------|-------------------|
| np.concat | 0.18280 | 0.17960 |
|------------|----------------|-------------------|
| np.stack | 0.21501 | 0.16465 |
|------------|----------------|-------------------|
| np.vstack | 0.21501 | 0.17181 |
|------------|----------------|-------------------|
| np.array | 0.21656 | 0.16833 |
|------------|----------------|-------------------|
As you can see I tried 2 experiments - using np.random.rand(10000)
and np.random.rand(1, 10000)
And if we use 2d arrays than np.stack
and np.array
create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.
Code:
from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
new_np = np.random.rand(10000)
l.append(new_np)
start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')
start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')
start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')
start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')
Ok, thanks to Charles Goodwin for the concept. Here is the answer:
import java.util.*;
public class Test {
public static void main(String[] args) {
List<String> argsList = new ArrayList<String>();
List<String> optsList = new ArrayList<String>();
List<String> doubleOptsList = new ArrayList<String>();
for (int i=0; i < args.length; i++) {
switch (args[i].charAt(0)) {
case '-':
if (args[i].charAt(1) == '-') {
int len = 0;
String argstring = args[i].toString();
len = argstring.length();
System.out.println("Found double dash with command " +
argstring.substring(2, len) );
doubleOptsList.add(argstring.substring(2, len));
} else {
System.out.println("Found dash with command " +
args[i].charAt(1) + " and value " + args[i+1] );
i= i+1;
optsList.add(args[i]);
}
break;
default:
System.out.println("Add a default arg." );
argsList.add(args[i]);
break;
}
}
}
}
my solution was - just remove '*' character from the expression ^__^
<div ngFor="let talk in talks">
Try this:
var req={StrContactDetails:'data',IsPrimary:'True'}
$.ajax({
type: 'POST',
data: req,
url: '@url.Action("SaveEmergencyContact","Dhp")',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(req),
success: function (data) {
alert("Success");
},
error: function (ob, errStr) {
alert("An error occured.Please try after sometime.");
}
});
final static String EXTRA_MESSAGE = "edit.list.message";
Context context;
public void onClick (View view)
{
Intent intent = new Intent(this,display.class);
RelativeLayout relativeLayout = (RelativeLayout) view.getParent();
TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
String message = textView.getText().toString();
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
I tried all these method but none worked for me. I removed .git file using rm -rf .git
form the local repository and then again did git init
and git add
and routine commands. It worked.
I had this same problem, and it only went away after a removed the .gradle folder from my project's root.
So make sure you:
I hope this helps. Good luck!
Look at the ToLookup
and/or ToDictionary
extension methods.
var origParseFloat = parseFloat;
parseFloat = function(str) {
alert("And I'm in your floats!");
return origParseFloat(str);
}
I had the similar issue - could not figure out what was the reason, but I fixed it using following code. Somehow it could not focus only the blank inputs:
$('input').click(function () {
var val = $(this).val();
if (val == "") {
this.select();
}
});
In case of Mac OS X Maverick when MySQL is installed via Homebrew it's located at /usr/local/opt/mysql/my.cnf
If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name
Declare @userName as varchar(50);
Declare @defaultDataBaseName as varchar(50);
Declare @LoginCreationScript as varchar(max);
Declare @UserCreationScript as varchar(max);
Declare @TempUserCreationScript as varchar(max);
set @defaultDataBaseName = 'data1';
set @userName = 'domain\userName';
set @LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS
WITH DEFAULT_DATABASE ={dataBaseName}'
set @UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set @LoginCreationScript=Replace(Replace(@LoginCreationScript, '{userName}', @userName), '{dataBaseName}', @defaultDataBaseName)
set @UserCreationScript =Replace(@UserCreationScript, '{userName}', @userName)
Execute(@LoginCreationScript)
/*User creation and role assignment*/
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', @defaultDataBaseName)
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db2')
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db3')
Execute(@TempUserCreationScript)
You could still use that event. Just check that the sender argument is the control you actually care about and if so, run the event code.
You might check Select2 plugin:
http://ivaynberg.github.io/select2/
Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.
It's quite popular and very maintainable. It should cover most of your needs if not all.
here's how you can do it with a cool shell trick:
mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'
'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.
use the -t flag to enable table-format output
While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable))
. Using the example from @X.X:
> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)
> freq_t
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
> data.frame(rbind(freq_t))
X3 X4 X5
4 1 8 2
6 2 4 1
8 12 0 2
If the column names do not start with numbers, the X
won't get added to the front of them.
select count(*)
from table_emp
where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'
New since 1.8 is a List.sort() method instead of using the Collection.sort() so you directly call mylistcontainer.sort()
Here is a code snippet which demonstrates the List.sort() feature:
List<Fruit> fruits = new ArrayList<Fruit>();
fruits.add(new Fruit("Kiwi","green",40));
fruits.add(new Fruit("Banana","yellow",100));
fruits.add(new Fruit("Apple","mixed green,red",120));
fruits.add(new Fruit("Cherry","red",10));
// a) using an existing compareto() method
fruits.sort((Fruit f1,Fruit f2) -> f1.getFruitName().compareTo(f2.getFruitName()));
System.out.println("Using String.compareTo(): " + fruits);
//Using String.compareTo(): [Apple is: mixed green,red, Banana is: yellow, Cherry is: red, Kiwi is: green]
// b) Using a comparable class
fruits.sort((Fruit f1,Fruit f2) -> f1.compareTo(f2));
System.out.println("Using a Comparable Fruit class (sort by color): " + fruits);
// Using a Comparable Fruit class (sort by color): [Kiwi is green, Apple is: mixed green,red, Cherry is: red, Banana is: yellow]
The Fruit class is:
public class Fruit implements Comparable<Fruit>
{
private String name;
private String color;
private int quantity;
public Fruit(String name,String color,int quantity)
{ this.name = name; this.color = color; this.quantity = quantity; }
public String getFruitName() { return name; }
public String getColor() { return color; }
public int getQuantity() { return quantity; }
@Override public final int compareTo(Fruit f) // sorting the color
{
return this.color.compareTo(f.color);
}
@Override public String toString()
{
return (name + " is: " + color);
}
} // end of Fruit class
If you make your project a war or ear type maven will copy the dependencies.
I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state.
Precisely. In fact, it's still being used for this purpose today because HTTP as we know it today is still, at least fundamentally, a stateless protocol.
This use case was actually first described in HTML 3.2 (I'm surprised HTML 2.0 didn't include such a description):
type=hidden
These fields should not be rendered and provide a means for servers to store state information with a form. This will be passed back to the server when the form is submitted, using the name/value pair defined by the corresponding attributes. This is a work around for the statelessness of HTTP. Another approach is to use HTTP "Cookies".<input type=hidden name=customerid value="c2415-345-8563">
While it's worth mentioning that HTML 3.2 became a W3C Recommendation only after JavaScript's initial release, it's safe to assume that hidden fields have pretty much always served the same purpose.
<style>
.nowrap {
white-space: nowrap;
}
</style>
...
<label for="id1" class="nowrap">label1:
<input type="text" id="id1"/>
</label>
Wrap your inputs within the label tag
A token
is a piece of data which only Server X
could possibly have created, and which contains enough data to identify a particular user.
You might present your login information and ask Server X
for a token
; and then you might present your token
and ask Server X
to perform some user-specific action.
Token
s are created using various combinations of various techniques from the field of cryptography as well as with input from the wider field of security research. If you decide to go and create your own token
system, you had best be really smart.
I had the same error on OSX Sierra, but in my case the ~/.android folder was owned by root (from a previous install) I changed the ownership to my User and now it works.
S3 is not used for real time development but if you really want to test your freshly deployed website use
http://yourdomain.com/index.html?v=2
http://yourdomain.com/init.js?v=2
Adding a version parameter in the end will stop using the cached version of the file and the browser will get a fresh copy of the file from the server bucket
I tried some of the other solutions listed here, but during unit testing the code would throw exceptions I wanted to ignore. I ended up creating the following recursive search method that will ignore certain exceptions like PathTooLongException and UnauthorizedAccessException.
private IEnumerable<string> RecursiveFileSearch(string path, string pattern, ICollection<string> filePathCollector = null)
{
try
{
filePathCollector = filePathCollector ?? new LinkedList<string>();
var matchingFilePaths = Directory.GetFiles(path, pattern);
foreach(var matchingFile in matchingFilePaths)
{
filePathCollector.Add(matchingFile);
}
var subDirectories = Directory.EnumerateDirectories(path);
foreach (var subDirectory in subDirectories)
{
RecursiveFileSearch(subDirectory, pattern, filePathCollector);
}
return filePathCollector;
}
catch (Exception error)
{
bool isIgnorableError = error is PathTooLongException ||
error is UnauthorizedAccessException;
if (isIgnorableError)
{
return Enumerable.Empty<string>();
}
throw error;
}
}
The key here is to visualise the call tree. Once done that, the complexity is:
nodes of the call tree * complexity of other code in the function
the latter term can be computed the same way we do for a normal iterative function.
Instead, the total nodes of a complete tree are computed as
C^L - 1
------- , when C>1
/ C - 1
/
# of nodes =
\
\
L , when C=1
Where C is number of children of each node and L is the number of levels of the tree (root included).
It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".
So, in the examples above:
n level 1 n-1 level 2 n-2 level 3 n-3 level 4 ... ~ n levels -> L = n
n n-5 n-10 n-15 ... ~ n/5 levels -> L = n/5
n n/5 n/5^2 n/5^3 ... ~ log5(n) levels -> L = log5(n)
n level 1 n-1 n-1 level 2 n-2 n-2 n-2 n-2 ... n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3 ... ... ~ n levels -> L = n
n n-5 n-10 n-15 ... ~ n/5 levels -> L = n/5
I have seen various answers which say when I uninstalled this or that it worked. I think that the uninstall is probably just sorting out an issue in the registry, rather it being an issue with the particular application that is being uninstalled.
I have also seen cases of people saying kill the RDP task but I don't have that and I still have the error.
I have seen cases of people saying clear the clipboard in Excel, but that doesn't work for me - nor does changing the settings in the Clipboard.
I believe that the issue is that an application has a lock on the clipboard and that application is not releasing it. The clipboard is a shared resource, so that implies that each application has to get a lock on it before changing it and then release the lock once it has completed the change, however, it looks like sometimes the lock is not released.
I found that the following cured it. Close down all MS applications including IE and Outlook. Check Task Manager processes to make sure that they are all gone.
Then restart the application where you had the Copy and Paste issue and it will probably then work.
Regards
Paul Simon