Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
I got this problem when I directly downloaded code files from GitHub but it was showing this error, but my colleague told me to use "Git bash here" and use the command to Gitclone it. After doing so it works fine.
To remove - Can't perform a React state update on an unmounted component warning, use componentDidMount method under a condition and make false that condition on componentWillUnmount method. For example : -
class Home extends Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
news: [],
};
}
componentDidMount() {
this._isMounted = true;
ajaxVar
.get('https://domain')
.then(result => {
if (this._isMounted) {
this.setState({
news: result.data.hits,
});
}
});
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
...
}
}
I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !
Another cause might be the fact that you're pointing to the wrong port.
Make sure you are actually pointing to the right SQL server. You may have a default installation of MySQL running on 3306 but you may actually be needing a different MySQL instance.
Check the ports and run some query against the db.
You have to install MongoDB
database server first in your system and start it.
Use the below link to install MongoDB
i solved it, try: click on open sdk settings and open flutter and then add sdk location when your download
This problem is commonly related to compiler errors in the Java code. Sometimes Android Studio does not show these errors in the Project explorer
. However, when a problematic .java
file is opened, errors are shown. Try to resolve errors and rebuild the project.
someone might get some help from my case
I just put a hard coded color hex value without #
like this by mistake android:textColor="FFA500"
almost made me mad to findout. #FFA500
this solved my issue
Steps to debug:-
In case you face any issue in kubernetes, first step is to check if kubernetes self applications are running fine or not.
Command to check:- kubectl get pods -n kube-system
If you see any pod is crashing, check it's logs
if getting NotReady
state error, verify network pod logs.
if not able to resolve with above, follow below steps:-
kubectl get nodes
# Check which node is not in ready state
kubectl describe node nodename
#nodename which is not in readystate
ssh to that node
execute systemctl status kubelet
# Make sure kubelet is running
systemctl status docker
# Make sure docker service is running
journalctl -u kubelet
# To Check logs in depth
Most probably you will get to know about error here, After fixing it reset kubelet with below commands:-
systemctl daemon-reload
systemctl restart kubelet
In case you still didn't get the root cause, check below things:-
Make sure your node has enough space and memory. Check for /var
directory space especially.
command to check: -df
-kh
, free -m
Verify cpu utilization with top command. and make sure any process is not taking an unexpected memory.
I had same problem, I installed all dependencies with root access :
In your case:
sudo pip install django
In my case, I had all dependencies in requirements.txt
, So:
sudo pip3 install -r requirements.txt
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">***Your URL(ex: 127.0.0.1)***</domain>
</domain-config>
</network-security-config>
In the suggestion provided above I was providing my URL as http://xyz.abc.com/mno/
I changed that to xyz.abc.com then it started working.
Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.11</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.
Add this dependency:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.28</version>
</dependency>
cf. https://stackoverflow.com/a/44536542/1070215
Make sure not to mix your Jersey dependency versions. This answer says version "2.28", but use whatever version your other Jersey dependency versions are.
Another possible recent solution is changing gradle version to:
classpath 'com.android.tools.build:gradle:3.0.0-rc2'
and updating build tool
you can either reuse the docker shell, with eval $(minikube docker-env)
, alternatively, you can leverage on docker save | docker load
across the shells.
It happened to me when I had a same port used in ssh tunnel SOCKS to run Proxy in 8080 port and my server and my firefox browser proxy was set to that port and got this issue.
This behavior is introduced in all major Tomcat releases:
To fix, do one of the following:
relaxedQueryChars
to allow this character
(recommended, see Lincoln's answer)requestTargetAllow
option
(deprecated in Tomcat 8.5) (see Jérémie's answer).Based on changelog, those changes could affect this behavior:
Tomcat 8.5.3:
Ensure that requests with HTTP method names that are not tokens (as required by RFC 7231) are rejected with a 400 response
Tomcat 8.5.7:
Add additional checks for valid characters to the HTTP request line parsing so invalid request lines are rejected sooner.
The best option (following the standard) - you want to encode your URL on client:
encodeURI("http://localhost:8080/app/handleResponse?msg=name|id|")
> http://localhost:8080/app/handleResponse?msg=name%7Cid%7C
or just query string:
encodeURIComponent("msg=name|id|")
> msg%3Dname%7Cid%7C
It will secure you from other problematic characters (list of invalid URI characters).
In case anyone stumbles with this problem again, the accepted solution did work for older versions of ionic and app scripts, I had used it many times in the past, but last week, after I updated some stuff, it got broken again, and this fix wasn't working anymore as this was already solved on the current version of app-scripts, most of the info is referred on this post https://forum.ionicframework.com/t/ionic-cordova-run-android-livereload-cordova-not-available/116790/18 but I'll make it short here:
First make sure you have this versions on your system
cli packages: (xxxx\npm\node_modules)
@ionic/cli-utils : 1.19.2 ionic (Ionic CLI) : 3.20.0
global packages:
cordova (Cordova CLI) : not installed
local packages:
@ionic/app-scripts : 3.1.9 Cordova Platforms : android 7.0.0 Ionic Framework : ionic-angular 3.9.2
System:
Node : v10.1.0 npm : 5.6.0
An this on your package.json
"@angular/cli": "^6.0.3", "@ionic/app-scripts": "^3.1.9", "typescript": "~2.4.2"
Now remove your platform with ionic cordova platform rm what-ever Then DELETE the node_modules and plugins folder and MAKE SURE the platform was deleted inside the platforms folder.
Finally, run
npm install ionic cordova platform add what-ever ionic cordova run
And everything should be working again
And by the way for you fellow googlers for selecting multiple folders in the search input you separate your directories with a comma. Works both for exclude and include
Example: ./src/public/,src/components/
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
Tried this option in learning Spark processing with setting up Spark context in local machine. Requisite 1)Keep Spark sessionr running in local 2)Add Spark maven dependency 3)Keep the input file at root\input folder 4)output will be placed at \output folder. Getting max share value for year. down load any CSV from yahoo finance https://in.finance.yahoo.com/quote/CAPPL.BO/history/ Maven dependency and Scala code below -
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.4.3</version>
<scope>provided</scope>
</dependency>
</dependencies>
object MaxEquityPriceForYear {
def main(args: Array[String]) {
val sparkConf = new SparkConf().setAppName("ShareMaxPrice").setMaster("local[2]").set("spark.executor.memory", "1g");
val sc = new SparkContext(sparkConf);
val input = "./input/CAPPL.BO.csv"
val output = "./output"
sc.textFile(input)
.map(_.split(","))
.map(rec => ((rec(0).split("-"))(0).toInt, rec(1).toFloat))
.reduceByKey((a, b) => Math.max(a, b))
.saveAsTextFile(output)
}
Well in my case i was accessing an static array of a class by reference of that class, but as we know we can directly access static member via class name. So when I replaced reference with class name where I was accessing that array. It fixed this error.
I had a semicolon at the end, and gave me this error.
In DefaultConfig Add multiDexEnabled = true
defaultConfig {
applicationId "com.test"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
multiDexEnabled = true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
Before doing a force deletion i would first do some checks. 1- node state: get the node name where your node is running, you can see this with the following command:
"kubectl -n YOUR_NAMESPACE describe pod YOUR_PODNAME"
Under the "Node" label you will see the node name. With that you can do:
kubectl describe node NODE_NAME
Check the "conditions" field if you see anything strange. If this is fine then you can move to the step, redo:
"kubectl -n YOUR_NAMESPACE describe pod YOUR_PODNAME"
Check the reason why it is hanging, you can find this under the "Events" section. I say this because you might need to take preliminary actions before force deleting the pod, force deleting the pod only deletes the pod itself not the underlying resource (a stuck docker container for example).
This is what helped me [src]:
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 !
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.
Quite recently they've added the depends_on
feature.
Edit:
As of compose version 2.1+ till version 3 you can use depends_on
in conjunction with healthcheck
to achieve this:
version: '2.1'
services:
web:
build: .
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
redis:
image: redis
db:
image: redis
healthcheck:
test: "exit 0"
Before version 2.1
You can still use depends_on
, but it only effects the order in which services are started - not if they are ready before the dependant service is started.
It seems to require at least version 1.6.0.
Usage would look something like this:
version: '2'
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
From the docs:
Express dependency between services, which has two effects:
- docker-compose up will start services in dependency order. In the following example, db and redis will be started before web.
- docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.
Note: As I understand it, although this does set the order in which containers are loaded. It does not guarantee that the service inside the container has actually loaded.
For example, you postgres container might be up. But the postgres service itself might still be initializing within the container.
The other answers to restarting a single node are on target, docker-compose restart worker
. That will bounce that container, but not include any changes, even if you rebuilt it separately. You can manually stop
, rm
, create
, and start
, but there are much easier methods.
If you've updated your code, you can do the build and reload in a single step with:
docker-compose up --detach --build
That will first rebuild your images from any changed code, which is fast if there are no changes since the cache is reused. And then it only replaces the changed containers. If your downloaded images are stale, you can precede the above command with:
docker-compose pull
To download any changed images first (the containers won't be restarted until you run a command like the up
above). Doing an initial stop is unnecessary.
And to only do this for a single service, follow the up or pull command with the services you want to specify, e.g.:
docker-compose up --detach --build worker
Here's a quick example of the first option, the Dockerfile is structured to keep the frequently changing parts of the code near the end. In fact the requirements are pulled in separately for the pip install
since that file rarely changes. And since the nginx and redis containers were up-to-date, they weren't restarted. Total time for the entire process was under 6 seconds:
$ time docker-compose -f docker-compose.nginx-proxy.yml up --detach --build
Building counter
Step 1 : FROM python:2.7-alpine
---> fc479af56697
Step 2 : WORKDIR /app
---> Using cache
---> d04d0d6d98f1
Step 3 : ADD requirements.txt /app/requirements.txt
---> Using cache
---> 9c4e311f3f0c
Step 4 : RUN pip install -r requirements.txt
---> Using cache
---> 85b878795479
Step 5 : ADD . /app
---> 63e3d4e6b539
Removing intermediate container 9af53c35d8fe
Step 6 : EXPOSE 80
---> Running in a5b3d3f80cd4
---> 4ce3750610a9
Removing intermediate container a5b3d3f80cd4
Step 7 : CMD gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0
---> Running in 0d69957bda4c
---> d41ff1635cb7
Removing intermediate container 0d69957bda4c
Successfully built d41ff1635cb7
counter_nginx_1 is up-to-date
counter_redis_1 is up-to-date
Recreating counter_counter_1
real 0m5.959s
user 0m0.508s
sys 0m0.076s
If the above solutions don't work on ubuntu/linux then you can try this
sudo fuser -k -n tcp port
Run it several times to kill processes on your port of choosing. port could be 3000 for example. You would have killed all the processes if you see no output after running the command
Not sure if you can get all the default settings easily, but specifically for the worker dir, it's quite straigt-forward:
from pyspark import SparkFiles
print SparkFiles.getRootDirectory()
Android Supports SSL implementation by default except for Android N (API level 24) and below Android 5.1 (API level 22)
I was getting the error when making the API call below API level 22 devices after implementing SSL at the server side; that was while creating OkHttpClient client object, and fixed by adding connectionSpecs() method OkHttpClient.Builder class.
the error received was
response failure: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb8882c00: I/O error during system call, Connection reset by peer
so I fixed this by added the check like
if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
// Do something for below api level 22
List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
if (specsList != null) {
okb.connectionSpecs(specsList);
}
}
Also for the Android N (API level 24); I was getting the error while making the HTTP call like
HTTP FAILED: javax.net.ssl.SSLHandshakeException: Handshake failed
and this is fixed by adding the check for Android 7 particularly, like
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
// Do something for naugat ; 7
okb.connectionSpecs(Collections.singletonList(getSpec()));
}
So my final OkHttpClient object will be like:
OkHttpClient client
HttpLoggingInterceptor httpLoggingInterceptor2 = new
HttpLoggingInterceptor();
httpLoggingInterceptor2.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okb = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor2)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request request2 = request.newBuilder().addHeader(AUTH_KEYWORD, AUTH_TYPE_JW + " " + password).build();
return chain.proceed(request2);
}
}).connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS);
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
// Do something for naugat ; 7
okb.connectionSpecs(Collections.singletonList(getSpec()));
}
if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
if (specsList != null) {
okb.connectionSpecs(specsList);
}
}
//init client
client = okb.build();
getSpecsBelowLollipopMR1 function be like,
private List<ConnectionSpec> getSpecsBelowLollipopMR1(OkHttpClient.Builder okb) {
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
okb.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));
ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
List<ConnectionSpec> specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
return specs;
} catch (Exception exc) {
Timber.e("OkHttpTLSCompat Error while setting TLS 1.2"+ exc);
return null;
}
}
The Tls12SocketFactory class will be found in below link (comment by gotev):
https://github.com/square/okhttp/issues/2372
For more support adding some links below this will help you in detail,
https://developer.android.com/training/articles/security-ssl
I came across the same error message and I have tried three ways mentioned above. I listed the results as a complementary reference to others.
PYTHON_SPARK
and PYTHON_DRIVER_SPARK
value in spark-env.sh
does not work for me.os.environ["PYSPARK_PYTHON"]="/usr/bin/python3.5"
os.environ["PYSPARK_DRIVER_PYTHON"]="/usr/bin/python3.5"
does not work for me.~/.bashrc
works like a charm~To add to already great and easy solution provided by Przemek315, the same config if you use Kotlin DSL:
tasks.test {
useJUnitPlatform()
}
There's elegant solution:
Just mount not whole directory, but only app directory. This way you'll you won't have troubles with npm_modules
.
Example:
frontend:
build:
context: ./ui_frontend
dockerfile: Dockerfile.dev
ports:
- 3000:3000
volumes:
- ./ui_frontend/src:/frontend/src
Dockerfile.dev:
FROM node:7.2.0
#Show colors in docker terminal
ENV COMPOSE_HTTP_TIMEOUT=50000
ENV TERM="xterm-256color"
COPY . /frontend
WORKDIR /frontend
RUN npm install update
RUN npm install --global typescript
RUN npm install --global webpack
RUN npm install --global webpack-dev-server
RUN npm install --global karma protractor
RUN npm install
CMD npm run server:dev
If you want your container ports to bind on your ipv4 address, just :
works for me on docker 1.9.1
This helped me: just wait about a minute or two.
Wait a few minutes, then retry your operation.
Add following Spark dependencies to POM file :
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.2.0</version>
</dependency>
//Spark configuration:
val spark = SparkSession.builder().master("local").appName("Sample App").getOrCreate()
//Read csv file:
val df = spark.read.option("header", "true").csv("FILE_PATH")
// Display output
df.show()
Today I also met this problem. Here is how I solved it:
xxx.9.png
. xxx9.png
and rebuilt. There were no errors, and the java files with the red wave under the name are gone too.Strangely, so many answers, and all of them are using surrogates like JS and keyboard shortcuts instead of just using a selenium feature:
def newTab(driver, url="about:blank"):
wnd = driver.execute(selenium.webdriver.common.action_chains.Command.NEW_WINDOW)
handle = wnd["value"]["handle"]
driver.switch_to.window(handle)
driver.get(url) # changes the handle
return driver.current_window_handle
This issue might also be caused by a broken Maven repository.
I observe the SEVERE: A child container failed during start
message from time to time when working with Eclipse. My Eclipse workspace has several projects. Some of the projects have common external dependencies. If Maven repository is empty (or I add new dependencies into pom.xml
files), Eclipse starts downloading libraries specified in pom.xml
into Maven repository. And Eclipse does that in parallel for several projects in the workspace. It might happen that several Eclipse threads would be downloading the same file simultaneously into the same place in Maven repository. As a result, this file becomes corrupted.
So, this is how you could resolve the issue.
rm -rf $HOME/.m2
).mvn package
in the command line. It is important to run the command for each project one-by-one, not in parallel; thus, you ensure that only one instance of Maven runs each time.This happened to me by having a link to external js outside the head just before the end of the body section. You know, one of these:
<script src="http://somesite.net/js/somefile.js">
It did not have anything to do with JQuery.
You would probably see the same doing something like this:
var script = $("<script></script>");
script.attr("src", basepath + "someotherfile.js");
$(document.body).append(script);
But I haven't tested that idea.
Add this line to your Dockerfile (You can run any linux command this way)
RUN useradd -ms /bin/bash yourNewUserName
I had the same problem. (My problem is with gradle 4.4 files)
Actually the problem is incorrect downloading of 4.4 gradle which already I had.
When I delete gradle 4.4 version
C:\Users\$Your_User\.gradle\wrapper\dists\gradle-4.4-all
Android studio again downloads gradle-4.4 and syncs with my project.
Now it had rectified with the help of Michelin Man
Thanks for your answer Michelin
For those who are getting the error as:
I/O error on POST request for "anothermachine:31112/url/path";: class path
resource [fileName.csv] cannot be resolved to URL because it does not exist.
It can be resolved by using the
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));
If the file is not present in the classpath, and an absolute path is required.
You can build command using following example
spark-submit --jars /usr/share/java/postgresql-jdbc.jar --class com.examples.WordCount3 /home/vaquarkhan/spark-scala-maven-project-0.0.1-SNAPSHOT.jar --jar --num-executors 3 --driver-memory 10g **--executor-memory 10g** --executor-cores 1 --master local --deploy-mode client --name wordcount3 --conf "spark.app.id=wordcount"
According Spring 4 MVC ResponseEntity.BodyBuilder and ResponseEntity Enhancements Example it could be written as:
....
return ResponseEntity.ok().build();
....
return ResponseEntity.noContent().build();
UPDATE:
If returned value is Optional
there are convinient method, returned ok()
or notFound()
:
return ResponseEntity.of(optional)
I had a similar error and in my case the fix was removing the '-' character from project name. Instead of my-app
, I used MyApp
I added @Service
before impl class and the error is gone.
@Service
public class FCSPAnalysisImpl implements FCSPAnalysis
{}
Django needs your application-specific settings. Since it is already inside your manage.py
, just use that. The faster, but perhaps temporary, solution is:
python manage.py shell
You can import the SSL cert manually and just add it to the keystore.
For linux users,
Syntax:
keytool -trustcacerts -keystore /jre/lib/security/cacerts -storepass changeit -importcert -alias nexus -file
Example :
keytool -trustcacerts -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/security/cacerts -storepass changeit -importcert -alias nexus -file ~/Downloads/abc.com-ssl.crt
On CentOS Linux release 7.5.1804, we were able to make this work by editing /etc/selinux/config and changing the setting of SELINUX like so:
SELINUX=disabled
For PySpark, you can also set the log level in your scripts with sc.setLogLevel("FATAL")
. From the docs:
Control our logLevel. This overrides any user-defined log settings. Valid log levels include: ALL, DEBUG, ERROR, FATAL, INFO, OFF, TRACE, WARN
Right-Click on your project -> Properties -> Deployment Assembly.
On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.
'Project and External Dependencies' will have all the spring related jars deployed along with your application
From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.
I think killing the process which is uses that port is more easy to handle than changing the ports in config files. Here is how to do it in Windows. You can follow same procedure to Linux but different commands. Run command prompt as Administrator. Then type below command to find out all of processes using the port.
netstat -ano
There will be plenty of processes using various ports. So to get only port we need use findstr
like below (here I use port 80)
netstat -ano | findstr 80
this will gave you result like this
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 7964
Last number is the process ID of the process. so what we have to do is kill the process using PID we can use taskkill
command for that.
taskkill /PID 7964 /F
Run your server again. This time it will be able to run. This can uses for Mysql server too.
Full disclosure - I'm the author of the previously mentioned talk in TLV DroidCon.
I had a chance to examine this issue across many Android applications, and discuss it with other developers who encountered it - and we all got to the same point: this issue cannot be avoided, only minimized.
I took a closer look at the default implementation of the Android Garbage collector code, to understand better why this exception is thrown and on what could be the possible causes. I even found a possible root cause during experimentation.
The root of the problem is at the point a device "Goes to Sleep" for a while - this means that the OS has decided to lower the battery consumption by stopping most User Land processes for a while, and turning Screen off, reducing CPU cycles, etc. The way this is done - is on a Linux system level where the processes are Paused mid run. This can happen at any time during normal Application execution, but it will stop at a Native system call, as the context switching is done on the kernel level. So - this is where the Dalvik GC joins the story.
The Dalvik GC code (as implemented in the Dalvik project in the AOSP site) is not a complicated piece of code. The basic way it work is covered in my DroidCon slides. What I did not cover is the basic GC loop - at the point where the collector has a list of Objects to finalize (and destroy). The loop logic at the base can be simplified like this:
starting_timestamp
,finalize()
and call native destroy()
if required,end_timestamp
,end_timestamp - starting_timestamp
) and compare against a hard coded timeout value of 10 seconds,java.util.concurrent.TimeoutException
and kill the process.Application runs along doing its thing.
This is not a user facing application, it runs in the background.
During this background operation, objects are created, used and need to be collected to release memory.
Application does not bother with a WakeLock - as this will affect the battery adversely, and seems unnecessary.
This means the Application will invoke the GC from time to time.
Normally the GC runs is completed without a hitch.
Sometimes (very rarely) the system will decide to sleep in the middle of the GC run.
This will happen if you run your application long enough, and monitor the Dalvik memory logs closely.
Now - consider the timestamp logic of the basic GC loop - it is possible for the device to start the run, take a start_stamp
, and go to sleep at the destroy()
native call on a system object.
When it wakes up and resumes the run, the destroy()
will finish, and the next end_stamp
will be the time it took the destroy()
call + the sleep time.
If the sleep time was long (more than 10 seconds), the java.util.concurrent.TimeoutException
will be thrown.
I have seen this in the graphs generated from the analysis python script - for Android System Applications, not just my own monitored apps.
Collect enough logs and you will eventually see it.
The issue cannot be avoided - you will encounter it if your app runs in the background.
You can mitigate by taking a WakeLock, and prevent the device from sleeping, but that is a different story altogether, and a new headache, and maybe another talk in another con.
You can minimize the problem by reducing GC calls - making the scenario less likely (tips are in the slides).
I have not yet had the chance to go over the Dalvik 2 (a.k.a ART) GC code - which boasts a new Generational Compacting feature, or performed any experiments on an Android Lollipop.
Added 7/5/2015:
After reviewing the Crash reports aggregation for this crash type, it looks like these crashes from version 5.0+ of Android OS (Lollipop with ART) only account for 0.5% of this crash type. This means that the ART GC changes has reduced the frequency of these crashes.
Added 6/1/2016:
Looks like the Android project has added a lot of info on how the GC works in Dalvik 2.0 (a.k.a ART).
You can read about it here - Debugging ART Garbage Collection.
It also discusses some tools to get information on the GC behavior for your app.
Sending a SIGQUIT to your app process will essentially cause an ANR, and dump the application state to a log file for analysis.
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
Exception clearly indicates the problem.
CompteDAOHib: No default constructor found
For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib
.
This was a Tomcat bug that resurfaced again with the Java 9 bytecode. The exact versions which fix this (for both Java 8/9 bytecode) are:
To those who tried everything in this thread and still stuck: This solved my problem. I updated /usr/local/nginx/conf/nginx.conf
Uncomment the line saying user
make it www-data
so it becomes: user www-data;
Save it (root access required)
Restart nginx
The reason is that when you use lazy load, the session is closed.
There are two solutions.
Don't use lazy load.
Set lazy=false
in XML or Set @OneToMany(fetch = FetchType.EAGER)
In annotation.
Use lazy load.
Set lazy=true
in XML or Set @OneToMany(fetch = FetchType.LAZY)
In annotation.
and add OpenSessionInViewFilter filter
in your web.xml
Detail See my post.
Found the solution in Spring security examples posted in Github.
WebSecurityConfigurerAdapter
has a overloaded configure
message that takes WebSecurity
as argument which accepts ant matchers on requests to be ignored.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/authFailure");
}
See Spring Security Samples for more details
Alright so I guess the thing to do is add my answer here to this long list versus creating a duplicate question...
If you are getting this in 2019, using .NET Core 3.0 (Preview at this time), the solution is to ensure all projects are targeting the same .NET Core version (in my case 3.0). I think I had one project in the solution targeting 2.1 and the rest were 2.2 so I probably could have stuck with 2.2...
I don't even have Newtonsoft.Json installed in any of the projects, and naturally adding it to them did not fix the issue.
If you have .NET Standard class libraries or w/e in your solution, they don't need to be on the same version, though they should probably be the latest you can go. For example, my .NET Standard class libraries are on 2.2 as there is not a .NET Standard 3.0 yet.
Add this class: d-flex align-items-center
to the element
If you had this:
<div class="col-3">
change it to this:
<div class="col-3 d-flex align-items-center>
try staring jboss with ./standalone.sh -c standalone-full.xml or any other alternative that allows you to start with the full profile
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..!
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
Hi same problem i have solved you can try this
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.NETWORK
// SET SSL
public static OkClient setSSLFactoryForClient(OkHttpClient client) {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client.setSslSocketFactory(sslSocketFactory);
client.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return new OkClient(client);
}
when working with spring boot the problem was that the tomcat library needs to set to provided
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
I've just had this issue without changing PATH.
My PC is Win7, 64-bit system, If you are also using 64-bit system, you may want to try:
It must be under "Program Files (x86)" NOT "Program Files"
Hope it can help.
Here is an example from my code (for threaded pool, but just change class name and you'll have process pool):
def execute_run(rp):
... do something
pool = ThreadPoolExecutor(6)
for mat in TESTED_MATERIAL:
for en in TESTED_ENERGIES:
for ecut in TESTED_E_CUT:
rp = RunParams(
simulations, DEST_DIR,
PARTICLE, mat, 960, 0.125, ecut, en
)
pool.submit(execute_run, rp)
pool.join()
Basically:
pool = ThreadPoolExecutor(6)
creates a pool for 6 threadspool.submit(execute_run, rp)
adds a task to pool, first arogument is a function called in in a thread/process, rest of the arguments are passed to the called function. pool.join
waits until all tasks are done. Instead of the JSON document, you can update the ObjectMapper object like below :
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
ok in addition to @user3096626 answer i think it will be more helpful if someone provided code example, the following example will show you how to fix image orientation comes from url (remote images):
Solution 1: using javascript (recommended)
because load-image library doesn't extract exif tags from url images only (file/blob), we will use both exif-js and load-image javascript libraries, so first add these libraries to your page as the follow:
<script src="https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.1.0/exif.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-load-image/2.12.2/load-image.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-load-image/2.12.2/load-image-scale.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-load-image/2.12.2/load-image-orientation.min.js"></script>
Note the version 2.2 of exif-js seems has issues so we used 2.1
then basically what we will do is
a - load the image using window.loadImage()
b - read exif tags using window.EXIF.getData()
c - convert the image to canvas and fix the image orientation using window.loadImage.scale()
d - place the canvas into the document
here you go :)
window.loadImage("/your-image.jpg", function (img) {
if (img.type === "error") {
console.log("couldn't load image:", img);
} else {
window.EXIF.getData(img, function () {
var orientation = EXIF.getTag(this, "Orientation");
var canvas = window.loadImage.scale(img, {orientation: orientation || 0, canvas: true});
document.getElementById("container").appendChild(canvas);
// or using jquery $("#container").append(canvas);
});
}
});
of course also you can get the image as base64 from the canvas object and place it in the img src attribute, so using jQuery you can do ;)
$("#my-image").attr("src",canvas.toDataURL());
here is the full code on: github: https://github.com/digital-flowers/loadimage-exif-example
Solution 2: using html (browser hack)
there is a very quick and easy hack, most browsers display the image in the right orientation if the image is opened inside a new tab directly without any html (LOL i don't know why), so basically you can display your image using iframe by putting the iframe src attribute as the image url directly:
<iframe src="/my-image.jpg"></iframe>
Solution 3: using css (only firefox & safari on ios)
there is css3 attribute to fix image orientation but the problem it is only working on firefox and safari/ios it is still worth mention because soon it will be available for all browsers (Browser support info from caniuse)
img {
image-orientation: from-image;
}
Since your server already includes the sites-enabled
folder ( notice the include /etc/nginx/sites-enabled/*
line ), then you better use that.
Create a file inside /etc/nginx/sites-available
and call it whatever you want, I'll call it django
since it's a djanog server
sudo touch /etc/nginx/sites-available/django
Then create a symlink that points to it
sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
Then edit that file with whatever file editor you use, vim
or nano
or whatever and create the server inside it
server {
# hostname or ip or multiple separated by spaces
server_name localhost example.com 192.168.1.1; #change to your setting
location / {
root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
}
}
Restart or reload nginx settings
sudo service nginx reload
Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server
My solution was to add a space between the $ and the {.
For example:
@Value("${project.ftp.adresse}")
becomes
@Value("$ {project.ftp.adresse}")
I think you should not rely on the implicit conversion. It is a bad practice.
Instead you should try like this:
datenum >= to_date('11/26/2013','mm/dd/yyyy')
or like
datenum >= date '2013-09-01'
In my case, the error "BeanFactory not initialized or already closed - call 'refresh' before" was a consequence of a previous error that I didn't noticed in the server startup. I think that it is not always the real cause of the problem.
in the new actionmailer, "razorengine" is a dependency. The latest version of Razorengine installs the dependency to System.Web.Razor 3.0.0.
If you use an earlier version in your application (i suppose you are using actionmailer in another project and that you reference the mail functionality from another project) than you get this issue of course.
In an earlier application, i had a webapplication MVC that uses system.web.Razor version 2.0.0. Of course, i got the issue to. How to fix? => Simple!
Install-Package RazorEngine -Version 3.3.0 (because version 3.3.0 will reference system.web.razor 2.0.0)
Missed to configure tag in manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
Since your JPA repository name is UserBoardRepository, your custom Interface name should be UserBoardRepositoryCustom (it should end with 'Custom') and your implementation class name should be UserBoardRepositoryImpl (should end with Impl; you can set it with a different postfix using the repository-impl-postfix property)
You need downbload the jQueryUI, this contains de images that you need
package sn;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
final String username = "[email protected]";//
final String password = "0000000";
try{
Session session = Session.getDefaultInstance(props,
new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]",false));
msg.setSubject("Hello");
msg.setText("How are you");
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent.");
}catch (MessagingException e){
System.out.println("Erreur d'envoi, cause: " + e);
}
}
}
When I installed Web Api 2.2 help this error started. I added this to the web.config and it solved my problem.
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
</dependentAssembly>
Data content is so variable, I think the best form is to define it as "ObjectNode" and next create his own class to parse:
Finally:
private ObjectNode data;
You forgot to add self
as a parameter to the function worker()
in the class KeyStatisticCollection
.
It is also good idea to use supervisord or runit[1] for service management.
Here's an approach that could resolve your problem, and if not would help with troubleshooting.
Create a second Apache virtual server identical to the current one
Send all "normal" user traffic to the original virtual server
Send special or long-running traffic to the new virtual server
Special or long-running traffic could be report-generation, maintenance ops or anything else you don't expect to complete in <<1 second. This can happen serving APIs, not just web pages.
If your resource utilization is low but you still exceed MaxClients, the most likely answer is you have new connections arriving faster than they can be serviced. Putting any slow operations on a second virtual server will help prove if this is the case. Use the Apache access logs to quantify the effect.
Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.
This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command
start -> run -> %temp%
I had the same problem after using zypper rm php*
to uninstall PHP and installing it again with zypper in php7 php7-gd php7-gettext php7-mbstring php7-mysql php7-pear
I solved it by enabling the apache2 module and restarting the webserver:
a2enmod php7 && service apache2 restart
In my maven project this error occurs, after i closed my projects and reopens them. The dependencys wasn´t build correctly at that time. So for me the solution was just to update the Maven Dependencies of the projects!
IMO, you should have a look at the Observer Pattern, and this is how most of the listeners work
Try this:
Original post: https://code.google.com/p/android/issues/detail?id=59018
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
For what it's worth: I just had the same problem, after editing the nginx.conf
file. I tried and tried restarting it by commanding sudo nginx restart
and various other commands. None of them produced any output. Commanding sudo nginx -t
to check the configuration file gave the output sudo: nginx: command not found
, which was puzzling. I was starting to think there were problems with the path.
Finally, I logged in as root (sudo su
) and commanded sudo nginx restart
. Now, the command displayed an error message concerning the configuration file. After fixing that, it restarted successfully.
This occurred to me when I applied the 2017 Fall Creator Update. I was able to resolve by repairing IIS 10.0 Express (I do not have IIS installed on my box.)
Note: As a user pointed out in the comments,
Repair can be found in "Programs and Features" - the "classic" control panel.
It means port 80 is already used by another one.
Simply follow these steps:
OR
For find the port of Apache (80) in Command Prompt simply type netstat -aon it displays present used ports on windows, under Local Address column it shown as 0.0.0.0:80. If it displays this port another connection is already used this port number.
Active Connections in Windows XP:
I solved my problem after installing xampp-win32-1.6.5-installer previously I used xampp version xampp-win32-1.8.2-0-VC9-installer at that time I got this error. Now it resolved my problem.
Well it's a very confusing kind of bug. There could be many reasons:
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
Could be due to the TCP protocol turned off.
How to check/enable: https://dba.stackexchange.com/questions/11377/cannot-connect-to-ms-sql-2008-r2-by-dbvisualizer-native-sspi-library-not-loade/144097#144097
In a hacky way it can be done for channels which one attempts to write to by recovering the raised panic. But you cannot check if a read channel is closed without reading from it.
Either you will
v <- c
)v, ok <- c
)v, ok <- c
)v <- c
)Only the last one technically doesn't read from the channel, but that's of little use.
This is another thread pool implementation that is very simple, easy to understand and use, uses only C++11 standard library, and can be looked at or modified for your uses, should be a nice starter if you want to get into using thread pools:
It works for me after getting rid of "::1" in /etc/hosts.
I've searched all over the web and after reading lot of docs regarding connection timeout exception, the thing I understood is that, preventing SocketTimeoutException
is beyond our limit. One way to effectively handle it is to define a connection timeout and later handle it by using a try-catch
block. Hope this will help anyone in future who are facing the same issue.
HttpUrlConnection conn = (HttpURLConnection) url.openConnection();
//set the timeout in milliseconds
conn.setConnectTimeout(7000);
try to add ojdbc6.jar or other version through the server lib "C:\apache-tomcat-7.0.47\lib",
Then restart the server in eclipse.
for refresh data gridview in any where you just need this code:
datagridview1.DataSource = "your DataSource";
datagridview1.Refresh();
Add foo1.c , foo2.c , foo3.c and makefile in one folder the type make in bash
if you do not want to use the makefile, you can run the command
gcc -c foo1.c foo2.c foo3.c
then
gcc -o output foo1.o foo2.o foo3.o
foo1.c
#include <stdio.h>
#include <string.h>
void funk1();
void funk1() {
printf ("\nfunk1\n");
}
int main(void) {
char *arg2;
size_t nbytes = 100;
while ( 1 ) {
printf ("\nargv2 = %s\n" , arg2);
printf ("\n:> ");
getline (&arg2 , &nbytes , stdin);
if( strcmp (arg2 , "1\n") == 0 ) {
funk1 ();
} else if( strcmp (arg2 , "2\n") == 0 ) {
funk2 ();
} else if( strcmp (arg2 , "3\n") == 0 ) {
funk3 ();
} else if( strcmp (arg2 , "4\n") == 0 ) {
funk4 ();
} else {
funk5 ();
}
}
}
foo2.c
#include <stdio.h>
void funk2(){
printf("\nfunk2\n");
}
void funk3(){
printf("\nfunk3\n");
}
foo3.c
#include <stdio.h>
void funk4(){
printf("\nfunk4\n");
}
void funk5(){
printf("\nfunk5\n");
}
makefile
outputTest: foo1.o foo2.o foo3.o
gcc -o output foo1.o foo2.o foo3.o
make removeO
outputTest.o: foo1.c foo2.c foo3.c
gcc -c foo1.c foo2.c foo3.c
clean:
rm -f *.o output
removeO:
rm -f *.o
Read my answer if recently you have been using a VPN connection.
Today I had the same exact issue and learned how to fix it without removing any plugins. So I thought maybe I would share my own experience.
My issue definitely had something to do with Spring Framework
I was using a VPN connection over my internet connection. Once I disconnected my VPN, everything instantly turned right.
intellij idea 2019
or ub Gradle set "compile" compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.2.2.jre11'
I figured I should share my solution, since I wasn't able to find it anywhere, and only figured it out through trial and error.
I indeed was able to transfer ownership of the repository to a team on BitBucket.
Don't add the remote URL that BitBuckets suggests:
git remote add origin https://[email protected]/teamName/repo.git
Instead, add the remote URL without your username:
git remote add origin https://bitbucket.org/teamName/repo.git
This way, when you go to pull from or push to a repo, it prompts you for your username, then for your password: everyone on the team has access to it under their own credentials. This approach only works with teams on BitBucket, even though you can manage user permissions on single-owner repos.
If you are using java 1.8, remove XX:-UseSplitVerifier
and use -noverify
in your JVM properties.
This is an older thread,but I will post my answer for others. I have to recreate the project in a different workspace after the changes to make it work, as discussed in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer
Download the following jars and add it to your WEB-INF/lib
directory:
@BrainSlugs83
You shouldn't blindly trust everything posted on stackoverflow. The comment in Jens code is incorrect, the parameter doesn't control whether exceptions are thrown or not.
MSDN is very clear what that parameter controls, have you read it? http://msdn.microsoft.com/en-us/library/dd321703(v=vs.110).aspx
If
throwOnFirstException
is true, an exception will immediately propagate out of the call to Cancel, preventing the remaining callbacks and cancelable operations from being processed. IfthrowOnFirstException
is false, this overload will aggregate any exceptions thrown into anAggregateException
, such that one callback throwing an exception will not prevent other registered callbacks from being executed.
The variable name is also wrong because Cancel is called on CancellationTokenSource
not the token itself and the source changes state of each token it manages.
There are a lot of reasons that you can be seeing w3wp.exe high CPU usage. I have selected six common causes to cover.
<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>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..
Both should be same ..Java version
mismatched ..Check it
Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.
If you are using II7 (and I guess you do) do the following.
Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool
Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.
As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....
The ?
and the OR
needs to be seperated by a space character. Do it wherever needed in the query string.
For CentOS 6.x and 7.x (including Amazon Linux) use:
sudo httpd -V
This will show you which of the MPMs are configured. Either prefork, worker, or event. Prefork is the earlier, threadsafe model. Worker is multi-threaded, and event supports php-mpm which is supposed to be a better system for handling threads and requests.
However, your results may vary, based on configuration. I've seen a lot of instability in php-mpm and not any speed improvements. An aggressive spider can exhaust the maximum child processes in php-mpm quite easily.
The setting for prefork, worker, or event is set in sudo nano /etc/httpd/conf.modules.d/00-mpm.conf (for CentOS 6.x/7.x/Apache 2.4).
# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:
# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#LoadModule mpm_event_module modules/mod_mpm_event.so
We ran into this problem and tracked it down to the Geocoding.net NuGet package that we were using to help with our Google Maps views (Geocoding.net version 3.1.0 published 2/4/2014).
The Geocoding dll appears to be .Net 4.0 when you examine the package file or view it using Jet Brains’ Dot Peek application; however, a colleague of mine says that it was compiled using ilmerge so it is most likely related to the ilmerge problems listed above.
It was a long process to track it down. We fetched different changesets from TFS till we narrowed it down to the changeset that added the aforementioned NuGet package. After removing it, we were able to deploy to our .NET 4 server.
I had the same issue. Fixed by adding a pom.xml in parent folder with <modules>
listed.
See this article for tips on how to help performance issues. This includes both performance issues related to starting up, under the "cold start" section. Most of this will matter no matter what type of server you are using, locally or in production.
If the application deserializes anything from XML (and that includes web services…) make sure SGEN is run against all binaries involved in deseriaization and place the resulting DLLs in the Global Assembly Cache (GAC). This precompiles all the serialization objects used by the assemblies SGEN was run against and caches them in the resulting DLL. This can give huge time savings on the first deserialization (loading) of config files from disk and initial calls to web services. http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx
If any IIS servers do not have outgoing access to the internet, turn off Certificate Revocation List (CRL) checking for Authenticode binaries by adding generatePublisherEvidence=”false” into machine.config. Otherwise every worker processes can hang for over 20 seconds during start-up while it times out trying to connect to the internet to obtain a CRL list. http://blogs.msdn.com/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx
http://msdn.microsoft.com/en-us/library/bb629393.aspx
Consider using NGEN on all assemblies. However without careful use this doesn’t give much of a performance gain. This is because the base load addresses of all the binaries that are loaded by each process must be carefully set at build time to not overlap. If the binaries have to be rebased when they are loaded because of address clashes, almost all the performance gains of using NGEN will be lost. http://msdn.microsoft.com/en-us/magazine/cc163610.aspx
I had a similar problem, and the solution for me was quite different from what the other users posted.
The problem with me was related to the project I was working last year, which required a certain proxy on maven settings (located at <path to maven folder>\maven\conf\settings.xml
and C:\Users\<my user>\.m2\settings.xml
). The proxy was blocking the download of required external packages.
The solution was to put back the original file (settings.xml
) on those places. Once things were restored, I was able to download the packages and everything worked.
The problem
You are using SimpleWorkerRequest in a scenario that it wasn't designed for. You are using it inside of IIS. If you look at the prior MSDN link (emphasis is mine):
Provides a simple implementation of the HttpWorkerRequest abstract class that can be used to host ASP.NET applications outside an Internet Information Services (IIS) application. You can employ SimpleWorkerRequest directly or extend it.
Also, if you look at the MSDN documentation for the System.Web.Hosting namespace (SimpleWorkerRequest
is in this namespace), you will also see something similar to the above (again, emphasis is mine):
The System.Web.Hosting namespace provides the functionality for hosting ASP.NET applications from managed applications outside Microsoft Internet Information Services (IIS).
The solution
I would recommend removing the call to SimpleWorkerRequest
. Instead, you can use a Microsoft solution to make sure your web site automatically starts up after it recycles. What you need is the Microsoft Application Initialization Module for IIS 7.5. It is not complicated to configure, but you need to understand the exact options. This is why I would also recommend the Application Initialization UI for IIS 7.5. The UI is written by an MSDN blogger.
So what exactly does the Microsoft solution do? It does what you are trying to do - IIS sends a "get" request to your website after the application pool is started.
Also it may cause some warnigs in logs like a Cglib2AopProxy Unable to proxy method. And many other reasons for this are described here Why always have single implementaion interfaces in service and dao layers?
I had the same problem. It was because I had accidentally used a relative path with the symbolic link.
Are you sure you used full paths, e.g.:
ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf
Was facing the same issue and unfortunately nothing here was working. Finally, I came across this link: https://blogs.msdn.microsoft.com/jjameson/2009/11/18/the-copy-local-bug-in-visual-studio/
Turns out the solution is sort of dumb: set copy-local for the microsoft.web.infrastructure dll to False, then set it back to True.
By the way, I think what is happening is that there are two versions of the microsoft.web.infrastructure dll, one that is pre-installed in the GAC, and another one that is now a nuget package. I think one is masking the other, hence causing issues. In my particular case, on my build server, I need it to be copied over to a folder (this folder is then zipped and sent off to deployment). I guess the system had a copy locally and just thought "nah, it'll be fine"
I had the exact same problem and since I read somewhere that the error was caused by a cached file, I fixed it by deleting all the files under the .m2 repository folder. The next time I built the project I had to download all the dependencies again but it was worth it - 0 errors!!
Just clean your server (in my case I was using Tomcat):
mvn clean
mvn install
Copy the diff file to the root of your repository, and then do:
git apply yourcoworkers.diff
More information about the apply
command is available on its man page.
By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch
on the sender and then git am
on the receiver, because it also transfers the authorship info and the commit message.
If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3
option of apply
that tries to merge in the changes.
It also works with Unix pipe as follows:
git diff d892531 815a3b5 | git apply
It seems the solutions for HTML/JS/CSS desktop apps are in no short supply.
One solution I have just come across is TideSDK: http://www.tidesdk.org/, which seems very promising, looking at the documentation.
You can develop with Python, PHP or Ruby, and package it for Mac, Windows or Linux.
I got the error in the following case:
I simply avoided the obfuscation and the error is gone. not a real solution, but at least I know what caused it...
"No suitable driver" usually means that the JDBC
URL you've supplied to connect has incorrect syntax or when the driver isn't loaded at all.
When the method getConnection is called, the DriverManager
will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.(using Class.forName()
)
For Example
import oracle.jdbc.driver.OracleDriver;
Class.forName("oracle.jdbc.driver.OracleDriver");
Also check that you have ojdbc6.jar
in your classpath. I would suggest to place .jar
at physical location to JBoss "$JBOSS_HOME/server/default/lib/"
directory of your project.
EDIT:
You have mentioned hibernate
lately.
Check that your hibernate.cfg.xml
file has connection properties something like this:
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
This is the better solution:
verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));
If you're using an embedded driver, the connectString is just
jdbc:derby:databaseName
(whith options like;create=true;user=xxx etc).
If you're using client driver, the connect string can be left as is, but if changing the driver gives no result... excuse the question, but are you 100% sure you have started the Derby Network Server as per the Derby Tutorial?
As others have mentioned the Lint warning is because of the potential memory leak. You can avoid the Lint warning by passing a Handler.Callback
when constructing Handler
(i.e. you don't subclass Handler
and there is no Handler
non-static inner class):
Handler mIncomingHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
// todo
return true;
}
});
As I understand it, this will not avoid the potential memory leak. Message
objects hold a reference to the mIncomingHandler
object which holds a reference the Handler.Callback
object which holds a reference to the Service
object. As long as there are messages in the Looper
message queue, the Service
will not be GC. However, it won't be a serious issue unless you have long delay messages in the message queue.
right click on your project and choose properties. click on Deployement Assembly. click add click on "Java Build Path Entries" select Maven Dependencies" click Finish.
For me the following method worked, Firstly ensure that windows update service is running from services.msc or you can run this command in an administrator Command Prompt -
net start wuauserv
Next edit the following registry from regedit
->
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp
-> MajorVersion
-> Change this value from 10 to 9.
Then try installing the AppFabric and it should work. Note :- revert back to registry value changes you made to ensure there are no problems in future if any.
I have had similar problems and worked around them by saving the WSDL locally. Don't forget to save any XSD files as well. You may need to edit the WSDL to specify an appropriate location for XSDs.
For similar assembly binding errors , following steps may help:
Currently there is a far simpler solution than the ones already provided. When running your application you just have to pass along the threaded=True
parameter to the app.run()
call, like:
app.run(host="your.host", port=4321, threaded=True)
Another option as per what we can see in the werkzeug docs, is to use the processes
parameter, which receives a number > 1 indicating the maximum number of concurrent processes to handle:
- threaded – should the process handle each request in a separate thread?
- processes – if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.
Something like:
app.run(host="your.host", port=4321, processes=3) #up to 3 processes
More info on the run()
method here, and the blog post that led me to find the solution and api references.
Note: on the Flask docs on the run()
methods it's indicated that using it in a Production Environment is discouraged because (quote): "While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well."
However, they do point to their Deployment Options page for the recommended ways to do this when going for production.
Is this endpoint taking too many time?
Maybe you are using flask without asynchronous support, so every request will block the call. To create async support without make difficult, add the gevent
worker.
With gevent, a new call will spawn a new thread, and you app will be able to receive more requests
pip install gevent
gunicon .... --worker-class gevent
If you are on windows then below port related server settings are present in file nginx.conf at < nginx installation path >/conf folder.
server {
listen 80;
server_name localhost;
....
Change the port number and restart the instance.
I'd consider also Apache Thrift http://thrift.apache.org/
It can bridge between several programming languages, is highly efficient and has support for async or sync calls. See full features here http://thrift.apache.org/docs/features/
The multi language can be useful for future plans, for example if you later want to do part of the computational task in C++ it's very easy to do add it to the mix using Thrift.
You need create /home/yozloy/html/test
folder. Or you can use alias
like below show:
location /test {
alias /home/yozloy/html/;
autoindex on;
}
If any project that you were using and now closed in workspace might lead to this issue, try deleting context from server folder inside eclipse or open the projects.
This example shows how to use a list of multiprocessing.Pipe instances to return strings from an arbitrary number of processes:
import multiprocessing
def worker(procnum, send_end):
'''worker function'''
result = str(procnum) + ' represent!'
print result
send_end.send(result)
def main():
jobs = []
pipe_list = []
for i in range(5):
recv_end, send_end = multiprocessing.Pipe(False)
p = multiprocessing.Process(target=worker, args=(i, send_end))
jobs.append(p)
pipe_list.append(recv_end)
p.start()
for proc in jobs:
proc.join()
result_list = [x.recv() for x in pipe_list]
print result_list
if __name__ == '__main__':
main()
Output:
0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
['0 represent!', '1 represent!', '2 represent!', '3 represent!', '4 represent!']
This solution uses fewer resources than a multiprocessing.Queue which uses
or a multiprocessing.SimpleQueue which uses
It is very instructive to look at the source for each of these types.
By reading your exception , It's sure that you forgot to autowire customerService
You should autowire your customerservice .
make following changes in your controller class
@Controller
public class CustomerController{
@Autowired
private Customerservice customerservice;
......other code......
}
Again your service implementation class
write
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerDAO customerDAO;
......other code......
.....add transactional methods
}
If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).
you should autowire sessionFactory set method in your DAO mplementation
please find samle application context :
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.sparkle" />
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" /> -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
</beans>
note that i am using jdbc.properties file for jdbc url and driver specification
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." />
add this to your ngnix conf file
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";
In general, the way to deal with circular dependencies is to use setter injection.
I tried the setter injection code that you posted, and it worked for me. I would imagine the reason you are getting the exception is because Bean1 and Bean2 are in the com.myapp.beans package, and you don't have component scanning enabled for that package.
You'd need to add the following to your spring configuration:
<context:component-scan base-package="com.bullethq.accounts.web"/>
or move the beans to a package which is being automatically scanned by Spring.
You should see the error log. By default, its location is in /var/log/nginx/error.log
In my case, 502 get way because of:
GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:28 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
When we know exactly what is wrong, then fix it. For these error, just modify the buffer:
fastcgi_buffers 16 512k;
fastcgi_buffer_size 512k;
starting from mihai-labo's answer, why not skip declaring the requrl variable altogether and put the url generating code directly in front of "url:", like:
$.ajax({
type: "POST",
url: '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)',
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
});
The first server block in the nginx config is the default for all requests that hit the server for which there is no specific server block.
So in your config, assuming your real domain is REAL.COM, when a user types that in, it will resolve to your server, and since there is no server block for this setup, the server block for FAKE.COM, being the first server block (only server block in your case), will process that request.
This is why proper Nginx configs have a specific server block for defaults before following with others for specific domains.
# Default server
server {
return 404;
}
server {
server_name domain_1;
[...]
}
server {
server_name domain_2;
[...]
}
etc
It seems some users are a bit confused by this example and think it is limited to a single conf file etc.
Please note that the above is a simple example for the OP to develop as required.
I personally use separate vhost conf files with this as so (CentOS/RHEL):
http {
[...]
# Default server
server {
return 404;
}
# Other servers
include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/
will contain domain_1.conf, domain_2.conf... domain_n.conf which will be included after the server block in the main nginx.conf file which will always be the first and will always be the default unless it is overridden it with the default_server directive elsewhere.
The alphabetical order of the file names of the conf files for the other servers becomes irrelevant in this case.
In addition, this arrangement gives a lot of flexibility in that it is possible to define multiple defaults.
In my specific case, I have Apache listening on Port 8080 on the internal interface only and I proxy PHP and Perl scripts to Apache.
However, I run two separate applications that both return links with ":8080" in the output html attached as they detect that Apache is not running on the standard Port 80 and try to "help" me out.
This causes an issue in that the links become invalid as Apache cannot be reached from the external interface and the links should point at Port 80.
I resolve this by creating a default server for Port 8080 to redirect such requests.
http {
[...]
# Default server block for undefined domains
server {
listen 80;
return 404;
}
# Default server block to redirect Port 8080 for all domains
server {
listen my.external.ip.addr:8080;
return 301 http://$host$request_uri;
}
# Other servers
include /etc/nginx/conf.d/*.conf;
}
As nothing in the regular server blocks listens on Port 8080, the redirect default server block transparently handles such requests by virtue of its position in nginx.conf.
I actually have four of such server blocks and this is a simplified use case.
This, strangely, can also be because of a missing package. Run pip to install all necessary packages:
pip install -r requirements.txt
autodiscover_tasks
wasn't picking up tasks that used missing packages.
Another good use for Dispatcher.Invoke
is for immediately updating the UI in a function that performs other tasks:
// Force WPF to render UI changes immediately with this magic line of code...
Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.ContextIdle);
I use this to update button text to "Processing..." and disable it while making WebClient
requests.
After 3.6 one is allowed to use database the following database triggers types:
Log into your Atlas account and select Triggers
interface and add new trigger:
Expand each section for more settings or details.
The answer @Ro Hit gave helped me a lot, but I was missing the user credentials because I had to fake a user for authentication unit testing. Hence, let me describe how I solved it.
According to this, if you add the method
// using System.Security.Principal;
GenericPrincipal FakeUser(string userName)
{
var fakeIdentity = new GenericIdentity(userName);
var principal = new GenericPrincipal(fakeIdentity, null);
return principal;
}
and then append
HttpContext.Current.User = FakeUser("myDomain\\myUser");
to the last line of the TestSetup
method you're done, the user credentials are added and ready to be used for authentication testing.
I also noticed that there are other parts in HttpContext you might require, such as the .MapPath()
method. There is a FakeHttpContext available, which is described here and can be installed via NuGet.
If this is a long calculation then I would go background worker. It has progress support. It also has support for cancel.
http://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx
Here I have a TextBox bound to contents.
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Debug.Write("backgroundWorker_RunWorkerCompleted");
if (e.Cancelled)
{
contents = "Cancelled get contents.";
NotifyPropertyChanged("Contents");
}
else if (e.Error != null)
{
contents = "An Error Occured in get contents";
NotifyPropertyChanged("Contents");
}
else
{
contents = (string)e.Result;
if (contentTabSelectd) NotifyPropertyChanged("Contents");
}
}
I tried to added those files into my .gitignore
and it was useless...
Nevertheless, as Petr Syrov said, you can use git rm -r --cached .idea
into your terminal and those files won't be a problem anymore!
I had a similar problem and although I made sure that referenced entities were saved first it keeps failing with the same exception. After hours of investigation it turns out that the problem was because the "version" column of the referenced entity was NULL. In my particular setup i was inserting it first in an HSQLDB(that was a unit test) a row like that:
INSERT INTO project VALUES (1,1,'2013-08-28 13:05:38','2013-08-28 13:05:38','aProject','aa',NULL,'bb','dd','ee','ff','gg','ii',NULL,'LEGACY','0','CREATED',NULL,NULL,1,'0',NULL,NULL,NULL,NULL,'0','0', NULL);
The problem of the above is the version column used by hibernate was set to null, so even if the object was correctly saved, Hibernate considered it as unsaved. When making sure the version had a NON-NULL(1 in this case) value the exception disappeared and everything worked fine.
I am putting it here in case someone else had the same problem, since this took me a long time to figure this out and the solution is completely different than the above.
My guess is that you've got something in method1
which wraps one exception in another, and uses the toString()
of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage()
behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message
It might also help to try to load and save the workspace with a newer eclipse version:
I am using eclipse 3.8. When starting up the splash screen would hang. There were no error messages in the log. What helped was to open the workspace with eclipse 4.2.2. After opening and closing the workspace I was able to load it again with 3.8.
I have similar trouble in test config, because of using AOP. I added this line of code in spring-config.xml
<aop:config proxy-target-class="true"/>
And it works !
I had a similar problem in IntelliJ IDEA. My code was 100% correct, but after starting the Tomcat, you receive an exception. java.lang.IllegalStateException: Neither BindingResult
I just removed and added again Tomcat configuration. And it worked for me.
A picture Tomcat configuration
I gathered insights from a bunch of answers here and I present a comprehensive solution:
So, if you setup nginx with php5-fpm and log a message using error_log()
you can see it in /var/log/nginx/error.log
by default.
A problem can arise if you want to log a lot of data (say an array) using error_log(print_r($myArr, true));
. If an array is large enough, it seems that nginx
will truncate your log entry.
To get around this you can configure fpm
(php.net fpm config) to manage logs. Here are the steps to do so.
Open /etc/php5/fpm/pool.d/www.conf
:
$ sudo nano /etc/php5/fpm/pool.d/www.conf
Uncomment the following two lines by removing ;
at the beginning of the line: (error_log is defined here: php.net)
;php_admin_value[error_log] = /var/log/fpm-php.www.log
;php_admin_flag[log_errors] = on
Create /var/log/fpm-php.www.log
:
$ sudo touch /var/log/fpm-php.www.log;
Change ownership of /var/log/fpm-php.www.log
so that php5-fpm can edit it:
$ sudo chown vagrant /var/log/fpm-php.www.log
Note: vagrant
is the user that I need to give ownership to. You can see what user this should be for you by running $ ps aux | grep php.*www
and looking at first column.
Restart php5-fpm:
$ sudo service php5-fpm restart
Now your logs will be in /var/log/fpm-php.www.log
.
For me useful code witch help me was http://rox-xmlrpc.sourceforge.net/niotut/src/NioServer.java
// The remote forcibly closed the connection, cancel
// the selection key and close the channel.
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// Clear out our read buffer so it's ready for new data
this.readBuffer.clear();
// Attempt to read off the channel
int numRead;
try {
numRead = socketChannel.read(this.readBuffer);
} catch (IOException e) {
// The remote forcibly closed the connection, cancel
// the selection key and close the channel.
key.cancel();
socketChannel.close();
return;
}
if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
key.channel().close();
key.cancel();
return;
}
...
In order to prevent StaleObjectStateException
, in your hbm
file write below code:
<timestamp name="lstUpdTstamp" column="LST_UPD_TSTAMP" source="db"/>
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.
I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:
public Integer getId() { return id; }
public void setId(Integer i){ id= i; }
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
See the "Threading" section of this page: http://msdn.microsoft.com/en-us/library/ff647786.aspx, in conjunction with the "Connections" section.
Have you tried upping the maxconnection attribute of your processModel setting?
I ran into the same issue when trying to run the ASP.Net precompiler, it turned out that I was not opening the command prompt as administrator. Once I did, I was able to run the asp.net compiler successfully.
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
If you want use Services in Ubuntu(Upstart): Node as a service in Ubuntu 11.04 with upstart, monit and forever.js
@Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.
Install a certificate from host:
> sudo ./java-cert-importer.sh example.com
Remove the certificate that installed already.
> sudo ./java-cert-importer.sh example.com --delete
java-cert-importer.sh
#!/usr/bin/env bash
# Exit on error
set -e
# Ensure script is running as root
if [ "$EUID" -ne 0 ]
then echo "WARN: Please run as root (sudo)"
exit 1
fi
# Check required commands
command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }
# Get command line args
host=$1; port=${2:-443}; deleteCmd=${3:-${2}}
# Check host argument
if [ ! ${host} ]; then
cat << EOF
Please enter required parameter(s)
usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]
EOF
exit 1
fi;
if [ "$JAVA_HOME" ]; then
javahome=${JAVA_HOME}
elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
javahome=$(readlink -f $(which java) | sed "s:bin/java::")
elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
javahome="$(/usr/libexec/java_home)/jre"
fi
if [ ! "$javahome" ]; then
echo "WARN: Java home cannot be found."
exit 1
elif [ ! -d "$javahome" ]; then
echo "WARN: Detected Java home does not exists: $javahome"
exit 1
fi
echo "Detected Java Home: $javahome"
# Set cacerts file path
cacertspath=${javahome}/lib/security/cacerts
cacertsbackup="${cacertspath}.$$.backup"
if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
echo "Certificate is deleted for ${host}"
exit 0
fi
# Get host info from user
#read -p "Enter server host (E.g. example.com) : " host
#read -p "Enter server port (Default 443) : " port
# create temp file
tmpfile="/tmp/${host}.$$.crt"
# Create java cacerts backup file
cp ${cacertspath} ${cacertsbackup}
echo "Java CaCerts Backup: ${cacertsbackup}"
# Get certificate from speficied host
openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}
# Import certificate into java cacerts file
sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit
# Remove temp certificate file
rm ${tmpfile}
# Check certificate alias name (same with host) that imported successfully
result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")
# Show results to user
if [ "$result" ]; then
echo "Success: Certificate is imported to java cacerts for ${host}";
else
echo "Error: Something went wrong";
fi;
The question is answered already, but I want add more information about the causes.
Android app unable to start activity componentinfo
This error often comes with appropriate logs. You can read logs and can solve this issue easily.
Here is a sample log. In which you can see clearly ClassCastException
. So this issue came because TextView
cannot be cast to EditText
.
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050): at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050): ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109): at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109): ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167): at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167): ... 11 more
findViewById()
of non existing viewLike when you use findViewById(R.id.button)
when button id does not exist in layout XML.
If you wrong cast some class, then you get this error. Like you cast RelativeLayout
to LinearLayout
or EditText
to TextView
.
manifest.xml
If you did not register Activity in manifest.xml
then this error comes.
findViewById()
with declaration at top levelBelow code is incorrect. This will create error. Because you should do findViewById()
after calling setContentView()
. Because an View can be there after it is created.
public class MainActivity extends Activity {
ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
//...
}
}
abstract
Activity class.When you try to start an Activity which is abstract, you will will get this error. So just remove abstract
keyword before activity class name.
If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.
Read about Downcast and Upcast
I got this kind of error too, but the problem was very different explained here. So in my case I got compiler error from temp file that I was using non existing namespace like:
using ImaginaryNamespaces;
I was sure that code "using ImaginaryNamespaces;" dosn't exists in my solution so of course I doubt cache problem. Finally I figured out that the temporary file was some generated source file from configs. My Views/Web.Config had a line:
<add namespace="ImaginaryNamespaces"/>
After removing this it worked. So I recommend to make sure that there is not any data in configs that might be related to the compiler error.
Go to file ---> switch workspace .It will work
If it is going to be a web based application, you can also use the ServletContextListener interface.
public class SLF4JBridgeListener implements ServletContextListener {
@Autowired
ThreadPoolTaskExecutor executor;
@Autowired
ThreadPoolTaskScheduler scheduler;
@Override
public void contextInitialized(ServletContextEvent sce) {
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
scheduler.shutdown();
executor.shutdown();
}
}
On linux: print('\007')
will make the system bell sound.
I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; //Tell the user how the process went
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}
//Start Process
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
//Check if background worker is doing anything and send a cancellation if it is
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
//Check if there is a request to cancel the process
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
//If the process exits the loop, ensure that progress is set to 100%
//Remember in the loop we set i < 100 so in theory the process will complete at 99%
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Process was cancelled";
}
else if (e.Error != null)
{
lblStatus.Text = "There was an error running the process. The thread aborted";
}
else
{
lblStatus.Text = "Process was completed";
}
}
A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.
The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.
Using the "Update project configuartion" messed up the build path of the project.
Fix: Open the "configure build path..." menu (right click on the project) and fix the Included/Excluded options for each source folder. That worked for me.
The simplest way to create a manifest is:
Project Properties -> Security -> Click "enable ClickOnce security settings"
(it will generate default manifest in your project Properties) -> then Click
it again in order to uncheck that Checkbox -> open your app.maifest and edit
it as you wish.
I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
I can’t think of any way to prevent it but maybe you can properly handle this. Ex:
try
{
…
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
…
}catch (HttpException ex)
{
if (ex.Message.StartsWith("The remote host closed the connection."))
;//do nothing
else
//handle other errors
}
catch (Exception e)
{
//handle other errors
}
finally
{//close streams etc..
}
An explicit call to a parent class constructor is required any time the parent class lacks a no-argument constructor. You can either add a no-argument constructor to the parent class or explicitly call the parent class constructor in your child class.
I found this (WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI. link) to contain the rest of the details which are missing from @Andrew's answer.
The one thing I found very useful was that the worker thread couldn't access the MainWindow's controls (in it's own method), however when using a delegate inside the main windows event handler it was possible.
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
pd.Close();
// Get a result from the asynchronous worker
T t = (t)args.Result
this.ExampleControl.Text = t.BlaBla;
};
<Resource>
tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password=""
maxActive="10"
maxIdle="10"
minIdle="5"
maxWait="10000"/>
<ResourceLink>
inside the <Context>
tag.<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource" />
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>
Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
this works:
if (WindowState == FormWindowState.Minimized)
WindowState = FormWindowState.Normal;
else
{
TopMost = true;
Focus();
BringToFront();
TopMost = false;
}
This worked for me.
Here I assume my attachment is of a PDF
type format.
Comments are made to understand it clearly.
public class MailAttachmentTester {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "[email protected]";
// Sender's email ID needs to be mentioned
String from = "[email protected]";
final String username = "[email protected]";//change accordingly
final String password = "test";//change accordingly
// Assuming you are sending email through relay.jangosmtp.net
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Attachment");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Please find the attachment below");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "D:/test.PDF";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Email Sent Successfully !!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
You can define style rules which only apply to specific elements inside your div
with id divContainer
like this:
#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */
Implementation of accepted answer for Django:
import hashlib
from django.db import models
class MyModel(models.Model):
file = models.FileField() # any field based on django.core.files.File
def get_hash(self):
hash = hashlib.md5()
for chunk in self.file.chunks(chunk_size=8192):
hash.update(chunk)
return hash.hexdigest()
it's simple .. you have to add solid border right, left to col-* and it should be work ..:)
it looks like this : http://i.stack.imgur.com/CF5ZV.png
HTML :
<div class="row">
<div class="col-sm-3" id="services_block">
</div>
<div class="col-sm-3" id="services_block">
</div>
<div class="col-sm-3" id="services_block">
</div>
<div class="col-sm-3" id="services_block">
</div>
</div>
CSS :
div#services_block {
height: 355px;
background-color: #33363a;
border-left:3px solid white;
border-right:3px solid white;
}
To convert it to a single dictionary with some decided keys value, you can use the code below.
data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
ListOfDictAsDict[PrecedingText + str(i)] = data[i]
Here's a quick overview that explains the different build targets.
From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."
The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.
You need to put the files into an array in order to sort and find the last modified file.
$files = array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort
ksort($files);
// find the last modification
$reallyLastModified = end($files);
foreach($files as $file) {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
if ($file == $reallyLastModified) {
// do stuff for the real last modified file
}
echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}
Not tested, but that's how to do it.
In Xcode 4 and possibly before, in the run script build phase there is an option "Show enviroment variables in build phase". If selected this will show then on a olive green background in the build log.
Here's another one:
=indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),""))))
With the final equation being this:
=DAYS360(A2,indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),"")))))
The other equations on here work, but I like this one because it makes getting the row number easy, which I find I need to do more often. Just the row number would be like this:
=max(arrayformula(if(A:A<>"",row(A:A),"")))
I originally tried to find just this to solve a spreadsheet issue, but couldn't find anything useful that just gave the row number of the last entry, so hopefully this is helpful for someone.
Also, this has the added advantage that it works for any type of data in any order, and you can have blank rows in between rows with content, and it doesn't count cells with formulas that evaluate to "". It can also handle repeated values. All in all it's very similar to the equation that uses max((G:G<>"")*row(G:G)) on here, but makes pulling out the row number a little easier if that's what you're after.
Alternatively, if you want to put a script on your sheet you can make it easy on yourself if you plan on doing this a lot. Here's that scirpt:
function lastRow(sheet,column) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
if (column == null) {
if (sheet != null) {
var sheet = ss.getSheetByName(sheet);
} else {
var sheet = ss.getActiveSheet();
}
return sheet.getLastRow();
} else {
var sheet = ss.getSheetByName(sheet);
var lastRow = sheet.getLastRow();
var array = sheet.getRange(column + 1 + ':' + column + lastRow).getValues();
for (i=0;i<array.length;i++) {
if (array[i] != '') {
var final = i + 1;
}
}
if (final != null) {
return final;
} else {
return 0;
}
}
}
Here you can just type in the following if you want the last row on the same of the sheet that you're currently editing:
=LASTROW()
or if you want the last row of a particular column from that sheet, or of a particular column from another sheet you can do the following:
=LASTROW("Sheet1","A")
And for the last row of a particular sheet in general:
=LASTROW("Sheet1")
Then to get the actual data you can either use indirect:
=INDIRECT("A"&LASTROW())
or you can modify the above script at the last two return lines (the last two since you would have to put both the sheet and the column to get the actual value from an actual column), and replace the variable with the following:
return sheet.getRange(column + final).getValue();
and
return sheet.getRange(column + lastRow).getValue();
One benefit of this script is that you can choose if you want to include equations that evaluate to "". If no arguments are added equations evaluating to "" will be counted, but if you specify a sheet and column they will now be counted. Also, there's a lot of flexibility if you're willing to use variations of the script.
Probably overkill, but all possible.
You can use placeholders and feed_dict.
Suppose we have numpy arrays like these:
trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33
You can declare two placeholders:
X = tf.placeholder("float")
Y = tf.placeholder("float")
Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...
Finally, when you run the model/cost, feed the numpy arrays using feed_dict:
with tf.Session() as sess:
....
sess.run(model, feed_dict={X: trY, Y: trY})
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php
and pass the serialized form to it so the PHP can read those values. Anything getResult.php
echos will be returned to the JavaScript function in the result
variable back on test.php
and (in this case) shown in an alert box.
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class Connectdatabase {
Connection con = null;
public static Connection ConnecrDb(){
try{
//String dir = System.getProperty("user.dir");
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
return con;
}
catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,"Problem with connection of database");
return null;
}
}
}
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
In a nutshell - you can have two String objects that contain the same characters but are different objects (in different memory locations). The == operator checks to see that two references are pointing to the same object (memory location), but the equals() method checks if the characters are the same.
Usually you are interested in checking if two Strings contain the same characters, not whether they point to the same memory location.
Put a div
inside td
and give following style width:50px;overflow: hidden;
to the div
Jsfiddle link
<td>
<div style="width:50px;overflow: hidden;">
<span>A long string more than 50px wide</span>
</div>
</td>
As some sugested you can use apache or jax-ws. You can also use tools that generate code from WSDL such as ws-import but in my opinion the best way to consume web service is to create a dynamic client and invoke only operations you want not everything from wsdl. You can do this by creating a dynamic client: Sample code:
String endpointUrl = ...;
QName serviceName = new QName("http://com/ibm/was/wssample/echo/",
"EchoService");
QName portName = new QName("http://com/ibm/was/wssample/echo/",
"EchoServicePort");
/** Create a service and add at least one port to it. **/
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl);
/** Create a Dispatch instance from a service.**/
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,
SOAPMessage.class, Service.Mode.MESSAGE);
/** Create SOAPMessage request. **/
// compose a request message
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
// Create a message. This example works with the SOAPPART.
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();
// Obtain the SOAPEnvelope and header and body elements.
SOAPEnvelope env = part.getEnvelope();
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();
// Construct the message payload.
SOAPElement operation = body.addChildElement("invoke", "ns1",
"http://com/ibm/was/wssample/echo/");
SOAPElement value = operation.addChildElement("arg0");
value.addTextNode("ping");
request.saveChanges();
/** Invoke the service endpoint. **/
SOAPMessage response = dispatch.invoke(request);
/** Process the response. **/
You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:
solution 1: call alpha's alphaMethod1()
from beta's alphaMethod1()
class Beta extends Alpha
{
public void alphaMethod1()
{
super.alphaMethod1();
}
}
or from any other method of Beta like:
class Beta extends Alpha
{
public void foo()
{
super.alphaMethod1();
}
}
class Test extends Beta
{
public static void main(String[] args)
{
Beta beta = new Beta();
beta.foo();
}
}
solution 2: create alpha's object and call alpha's alphaMethod1()
class Test extends Beta
{
public static void main(String[] args)
{
Alpha alpha = new Alpha();
alpha.alphaMethod1();
}
}
You can also do this without any code at all. If you right-click on the little sheet tab at the bottom of the sheet, and select "Move or Copy", you will get a dialog box that lets you choose which open workbook to transfer the sheet to.
See this link for more detailed instructions and screenshots.
By the time the image is loaded, the renderer has already drawn the scene, hence it is too late. The solution is to change
texture = THREE.ImageUtils.loadTexture('crate.gif'),
into
texture = THREE.ImageUtils.loadTexture('crate.gif', {}, function() {
renderer.render(scene);
}),
As others have pointed out
There's a clear recommendation about when to use which from Stroustrup/Sutter:
Use class if the class has an invariant; use struct if the data members can vary independently
However, keep in mind that it is not wise to forward declare sth. as a class (class X;
) and define it as struct (struct X { ... }
).
It may work on some linkers (e.g., g++) and may fail on others (e.g., MSVC), so you will find yourself in developer hell.
Did you try:
<Directory /path/to/your/wp-admin>
Order allow,deny
Allow from all
</Directory>
You can also resize the image to the desired width and height. For example:
<p align="center">
<img src="https://anyserver.com/image.png" width="750px" height="300px"/></p>
To add a centered caption to the image, just one more line:
<p align="center">This is a centered caption for the image<p align="center">
Fortunately, this works both for README.md and the GitHub Wiki pages.
You don't have to do anything special, it should just be working.
When I have a fresh rails app with this controller:
class FooController < ApplicationController
def index
raise "error"
end
end
and go to http://127.0.0.1:3000/foo/
I am seeing the exception with a stack trace.
You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.
See config/initializers/backtrace_silencers.rb
in your Rails project
If you have a bunch of chars and want to concat them into a string, why not do
System.out.println("" + char1 + char2 + char3);
?
Probably the cleanest solution:
abstract class NavigationChildFragment : Fragment() {
abstract fun onCreateChildView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View?
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val activity = activity as? MainActivity
activity?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
setHasOptionsMenu(true)
return onCreateChildView(inflater, container, savedInstanceState)
}
override fun onDestroyView() {
val activity = activity as? MainActivity
activity?.supportActionBar?.setDisplayHomeAsUpEnabled(false)
setHasOptionsMenu(false)
super.onDestroyView()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val activity = activity as? MainActivity
return when (item.itemId) {
android.R.id.home -> {
activity?.onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
Just use this class as parent for all Fragments that should support navigation.
If this string is for presentation to the end user, you should use NSNumberFormatter
. This will add thousands separators, and will honor the localization settings for the user:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];
In the US, for example, that would create a string 10,000
, but in Germany, that would be 10.000
.
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
declare @T table(Roles xml)
insert into @T values
('<root>
<role>Alpha</role>
<role>Beta</role>
<role>Gamma</role>
</root>')
declare @Role varchar(10)
set @Role = 'Beta'
select Roles
from @T
where Roles.exist('/root/role/text()[. = sql:variable("@Role")]') = 1
If you want the query to work as where col like '%Beta%'
you can use contains
declare @T table(Roles xml)
insert into @T values
('<root>
<role>Alpha</role>
<role>Beta</role>
<role>Gamma</role>
</root>')
declare @Role varchar(10)
set @Role = 'et'
select Roles
from @T
where Roles.exist('/root/role/text()[contains(., sql:variable("@Role"))]') = 1
Your mistake is using the datetime
module instead of the date
module. You meant to do this:
from datetime import date
date = models.DateField(_("Date"), default=date.today)
If you only want to capture the current date the proper way to handle this is to use the auto_now_add
parameter:
date = models.DateField(_("Date"), auto_now_add=True)
However, the modelfield docs clearly state that auto_now_add
and auto_now
will always use the current date and are not a default value that you can override.
The following should work:
from matplotlib import pyplot as plt
plt.imshow(data, interpolation='nearest')
plt.show()
If you are using Jupyter notebook/lab, use this inline command before importing matplotlib:
%matplotlib inline
If you could live with the fact that you log are coming from an extra terminal window, I could recommend pidcat (Take only the package name and tracks PID changes.)
CSS:
selector{
padding:0 0 10px 0; // Top left bottom right
}
I was having some difficulty translating actual VB.NET to the Expression subset that SSRS uses. You definitely inspired me though and this is what I came up with.
StartDate
=dateadd("d",0,dateserial(year(dateadd("d",-1,dateserial(year(Today),month(Today),1))),month(dateadd("d",-1,dateserial(year(Today),month(Today),1))),1))
End Date
=dateadd("d",0,dateserial(year(Today),month(Today),1))
I know it's a bit recursive for the StartDate (first day of last month). Is there anything I'm missing here? These are strictly date fields (i.e. no time), but I think this should capture leap year, etc.
How did I do?
Essentially, you want to override the __init__
method of models.Model
so that you keep a copy of the original value. This makes it so that you don't have to do another DB lookup (which is always a good thing).
class Person(models.Model):
name = models.CharField()
__original_name = None
def __init__(self, *args, **kwargs):
super(Person, self).__init__(*args, **kwargs)
self.__original_name = self.name
def save(self, force_insert=False, force_update=False, *args, **kwargs):
if self.name != self.__original_name:
# name changed - do something here
super(Person, self).save(force_insert, force_update, *args, **kwargs)
self.__original_name = self.name
Why you are using PHP for the conversion. Now, there are so many front end languages available, Why you are still including a server? You can convert the password into the binary number in the front-end and send the converted string in the Database. According to my point of view, this would be convenient.
var bintext, textresult="", binlength;
this.aaa = this.text_value;
bintext = this.aaa.replace(/[^01]/g, "");
binlength = bintext.length-(bintext.length%8);
for(var z=0; z<binlength; z=z+8) {
textresult += String.fromCharCode(parseInt(bintext.substr(z,8),2));
this.ans = textresult;
This is a Javascript code which I have found here: http://binarytotext.net/, they have used this code with Vue.js. In the code, this.aaa is the v-model dynamic value. To convert the binary into the text values, they have used big numbers. You need to install an additional package and convert it back into the text field. In my point of view, it would be easy.
Are you looking for the SQL used to generate a table? For that, you can query the sqlite_master
table:
sqlite> CREATE TABLE foo (bar INT, quux TEXT);
sqlite> SELECT * FROM sqlite_master;
table|foo|foo|2|CREATE TABLE foo (bar INT, quux TEXT)
sqlite> SELECT sql FROM sqlite_master WHERE name = 'foo';
CREATE TABLE foo (bar INT, quux TEXT)
You cannot add AM / PM to a TimeSpan
. You'll anyway have to associate the TimaSpan
value with DateTime
if you want to display the time in 12-hour clock format.
TimeSpan
is not intended to use with a 12-hour clock format, because we are talking about a time interval here.
As it says in the documentation;
A
TimeSpan
object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. TheTimeSpan
structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, theDateTime
orDateTimeOffset
structure should be used instead.
Also Microsoft Docs describes as follows;
A
TimeSpan
value can be represented as[-]d.hh:mm:ss.ff
, where the optional minus sign indicates a negative time interval, thed
component is days,hh
is hours as measured on a 24-hour clock,mm
is minutes,ss
is seconds, andff
is fractions of a second.
So in this case, you can display using AM/PM as follows.
TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");
Side note :
Also should note that the TimeOfDay property of DateTime
is a TimeSpan
, where it represents
a time interval that represents the fraction of the day that has elapsed since midnight.
I found superagent to be really useful, it is very simple for example
const superagent=require('superagent')
superagent
.get('google.com')
.set('Authorization','Authorization object')
.set('Accept','application/json')
The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).
The advantage of having a function such as
foo(string const& myname)
over
foo(string const* myname)
is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.
Your second example:
const string &GetMethodName() { ... }
Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:
class A
{
public:
int bar() const {return someValue;}
//Big, expensive to copy class
}
class B
{
public:
A const& getA() { return mA;}
private:
A mA;
}
void someFunction()
{
B b = B();
//Access A, ability to call const functions on A
//No need to check for null, since reference is guaranteed to be valid.
int value = b.getA().bar();
}
You have to of course be careful to not return invalid references. Compilers will happily compile the following (depending on your warning level and how you treat warnings)
int const& foo()
{
int a;
//This is very bad, returning reference to something on the stack. This will
//crash at runtime.
return a;
}
Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.
To add bold, italic and underline, just add the following to the font argument:
font=("Arial", 8, 'normal', 'bold', 'italic', 'underline')
Googling a bit gives you the following result from wikibooks:
set argC=0
for %%x in (%*) do Set /A argC+=1
echo %argC%
Seems like cmd.exe has evolved a bit from the old DOS days :)
I don't yet have the comprehension of Pythonology necessary to see the intended way of sharing code amongst unrelated projects without a sibling/relative import hack. Until that day, this is my solution. For examples
or tests
to import stuff from ..\api
, it would look like:
import sys.path
import os.path
# Import from sibling directory ..\api
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
import api.api
import api.api_key
In the case of winforms:
If you include the images to your resources you can do it like this, very simple and straight forward:
public Form1()
{
InitializeComponent();
button1.MouseEnter += new EventHandler(button1_MouseEnter);
button1.MouseLeave += new EventHandler(button1_MouseLeave);
}
void button1_MouseLeave(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}
void button1_MouseEnter(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
I would not recommend hardcoding image paths.
As you have altered your question ...
There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :
in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover);
button1.MouseMove += new MouseEventHandler(button1_MouseMove);
void button1_MouseMove(object sender, MouseEventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
void button1_MouseHover(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
To add images to your resources: Projectproperties/resources/add/existing file
This was a strange problem since my hosts IIS shouldn't complain that it requires integrated pipeline mode when it already is in that mode as I stated in my question as:
I have searched a lot and unable to find anything except for directing the reader to change the pipeline from classic mode to integrated mode that which I already did with no luck..
Using Levi's directions, I put and <%: System.Web.Hosting.HttpRuntime.UsingIntegratedPipeline %>
* on an empty aspx page and told my host what going on and asked them to fix the problem and confirm the problem using the page I uploaded... I checked very often if something has changed at the state of the page and I can see that they struggled 3-4 hours to solve it... <%: System.Web.Hosting.HttpRuntime.IISVersion %>
When I asked what they have done to solve the problem, their answer was kind of 'classified', since they said:
Our team made the required changes on the server
The problem was all with my host.
* Update: As Ben stated in the comments
<%: System.Web.Hosting.HttpRuntime.UsingIntegratedPipeline %>
and<%: System.Web.Hosting.HttpRuntime.IISVersion %>
are no longer valid and they are now:
The size is four bytes because the enum
is stored as an int
. With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.
0 0 0 0 January
0 0 0 1 February
0 0 1 0 March
0 0 1 1 April
0 1 0 0 May
0 1 0 1 June
0 1 1 0 July
0 1 1 1 August
1 0 0 0 September
1 0 0 1 October
1 0 1 0 November
1 0 1 1 December
1 1 0 0 ** unused **
1 1 0 1 ** unused **
1 1 1 0 ** unused **
1 1 1 1 ** unused **
Without enums, you might be tempted to use raw integers to represent the months. That would work and be efficient, but it would make your code hard to read. With enums, you get efficient storage and readability.
Yes -- the X509Store.Certificates
property returns a snapshot of the X.509 certificate store.
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
You can use the return
statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.
If no return
is explicitly set, then the stored procedure returns zero.
CREATE PROCEDURE GetImmediateManager
@employeeID INT,
@managerID INT OUTPUT
AS
BEGIN
SELECT @managerID = ManagerID
FROM HumanResources.Employee
WHERE EmployeeID = @employeeID
if @@rowcount = 0 -- manager not found?
return 1;
END
And you call it this way:
DECLARE @return_status int;
DECLARE @managerID int;
EXEC @return_status = GetImmediateManager 2, @managerID output;
if @return_status = 1
print N'Immediate manager not found!';
else
print N'ManagerID is ' + @managerID;
go
You should use the return value for status codes only. To return data, you should use output parameters.
If you want to return a dataset, then use an output parameter of type cursor
.
You cant delete local git repository when its already connected. so close the solution, open another solution and then remove the local git repository. dont forget to delete .git hidden folder works for me
You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):
SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
String input = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
...
JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))
This is solve your encode error
also.
Make sure you wrap the condition in the correct precedence
ng-disabled="((!product.img) || (!product.name))"
I didn't love the syntax of any of those. I really wanted to just specify what the items were and what the weighting of each was. I realize I could have used random.choices
but instead I quickly wrote the class below.
import random, string
from numpy import cumsum
class randomChoiceWithProportions:
'''
Accepts a dictionary of choices as keys and weights as values. Example if you want a unfair dice:
choiceWeightDic = {"1":0.16666666666666666, "2": 0.16666666666666666, "3": 0.16666666666666666
, "4": 0.16666666666666666, "5": .06666666666666666, "6": 0.26666666666666666}
dice = randomChoiceWithProportions(choiceWeightDic)
samples = []
for i in range(100000):
samples.append(dice.sample())
# Should be close to .26666
samples.count("6")/len(samples)
# Should be close to .16666
samples.count("1")/len(samples)
'''
def __init__(self, choiceWeightDic):
self.choiceWeightDic = choiceWeightDic
weightSum = sum(self.choiceWeightDic.values())
assert weightSum == 1, 'Weights sum to ' + str(weightSum) + ', not 1.'
self.valWeightDict = self._compute_valWeights()
def _compute_valWeights(self):
valWeights = list(cumsum(list(self.choiceWeightDic.values())))
valWeightDict = dict(zip(list(self.choiceWeightDic.keys()), valWeights))
return valWeightDict
def sample(self):
num = random.uniform(0,1)
for key, val in self.valWeightDict.items():
if val >= num:
return key
For windows user, Just simple stop all processes of Node.js in Task Manager
Hope it will help
In SQL Server I would use:
WHERE CHARINDEX(CHAR(13), name) <> 0 OR CHARINDEX(CHAR(10), name) <> 0
This will search for both carriage returns and line feeds.
If you want to search for tabs too just add:
OR CHARINDEX(CHAR(9), name) <> 0
After editing .gitignore
to match the ignored files, you can do git ls-files -ci --exclude-standard
to see the files that are included in the exclude lists; you can then do
git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"
to remove them from the repository (without deleting them from disk).
Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):
apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
(The -r
flag in xargs
prevents git rm
from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs
may or may not have a similar option.)
Now you can just type git apply-gitignore
in your repo, and it'll do the work for you!
IF you are using Vector3 this is what i did
1- I create a class Name it Player
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
public Vector3[] Position;
}
2- then i call it like this
if ( _ispressed == true)
{
Player playerInstance = new Player();
playerInstance.Position = newPos;
string jsonData = JsonUtility.ToJson(playerInstance);
reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
Debug.Log(jsonData);
_ispressed = false;
}
3- and this is the result
"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}
Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL
I'm not sure what version of Windows introduced this command.
To encode a file:
certutil -encode inputFileName encodedOutputFileName
To decode a file:
certutil -decode encodedInputFileName decodedOutputFileName
There are a number of available verbs and options available to CERTUTIL.
To get a list of nearly all available verbs:
certutil -?
To get help on a particular verb (-encode for example):
certutil -encode -?
To get complete help for nearly all verbs:
certutil -v -?
Mysteriously, the -encodehex
verb is not listed with certutil -?
or certutil -v -?
. But it is described using certutil -encodehex -?
. It is another handy function :-)
Regarding David Morales' comment, there is a poorly documented type option to the -encodehex
verb that allows creation of base64 strings without header or footer lines.
certutil [Options] -encodehex inFile outFile [type]
A type of 1 will yield base64 without the header or footer lines.
See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.
Not investigated, but the -decodehex
verb also has an optional trailing type argument.
For django forms you can do this;
form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))
you could name all fields and add an outer select on those fields:
SELECT A, B, C FROM ( your initial query here ) TableAlias
That should do the trick.
You can do that with list-style-position: inside;
on the ul
element :
ul {
list-style-position: inside;
}
For linux/unix OS, you can use the shell syntax
const shell = require('child_process').execSync ;
const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;
shell(`mv ${currentPath} ${newPath}`);
That's it!
I was originally trying to escape special characters in a file name only, not on the path, from a full URL string.
ERB::Util.url_encode
didn't work for my use:
helper.send(:url_encode, "http://example.com/?a=\11\15")
# => "http%3A%2F%2Fexample.com%2F%3Fa%3D%09%0D"
Based on two answers in "Why is URI.escape() marked as obsolete and where is this REGEXP::UNSAFE constant?", it looks like URI::RFC2396_Parser#escape
is better than using URI::Escape#escape
. However, they both are behaving the same to me:
URI.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"
URI::Parser.new.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"
Is it possible to make a search by
querySelectorAll
using multiple unrelated conditions?
Yes, because querySelectorAll
accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:
var list = document.querySelectorAll("form, p, legend");
...will return a list containing any element that is a form
or p
or legend
.
CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:
var list = document.querySelectorAll("div.foo");
...will return a list of all div
elements that also (and) have the class foo
, ignoring other div
elements.
You can, of course, combine them:
var list = document.querySelectorAll("div.foo, p.bar, div legend");
...which means "Include any div
element that also has the foo
class, any p
element that also has the bar
class, and any legend
element that's also inside a div
."
You can't pass parameters like this - the success object maps to an anonymous function with one parameter and that's the received data. Create a function outside of the for loop which takes (data, i)
as parameters and perform the code there:
function image_link(data, i) {
$(data).find("a:contains(.jpg)").each(function(){
new Image().src = url[i] + $(this).attr("href");
}
}
...
success: function(data){
image_link(data, i)
}
Ok solved it.
Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting
In my app.js routing config:
$routeProvider.when('/pages/:name', {
templateUrl: '/pages/home.html',
controller: CMSController
});
Then in my CMS controller:
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
$.get($route.current.templateUrl, function (data) {
$scope.$apply(function () {
$('#views').html($compile(data)($scope));
});
});
...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
With #views being my <div id="views" ng-view></div>
So now it works with standard routing and dynamic routing.
To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio
into my browser and hey presto portfolio.html was displayed....
Updated Added $apply and $compile to the html so that dynamic content can be injected.
In case you need this to write a .properties
file you can just add the Strings into a Properties object and then save it to a file. It will take care for the conversion.
I used
a2ensite default-ssl
and it worked like a charm.
If you want to force e.g. phpmyadmin to use SSL/https you will run into this problem if this link is missing.
I have read your problem, And i had the same problem. But af ter i changed some, my problem "Permission Denied" is solved.
Private Sub Addi_Click()
'On Error Resume Next
'call ds
browsers ("false")
Call makeAdir
ffgg = "C:\Users\Backups\user\" & User & "1\data\"
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.Getfolder("c:\users\Backups\user\" & User & "1\data")
f.Attributes = 0
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Call fso.Copyfile(filetarget, ffgg, True)
Look at ffgg = "C:\Users\Backups\user\" & User & "1\data\"
, Before I changed it was ffgg = "C:\Users\Backups\user\" & User & "1\data"
When i add backslash after "\data\"
, my problem is solved. Try to add back slash. Maybe solved your problem. Good luck.
In case you are using node.js (with express)
If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:
app.use(express.static("public"));
Where app is:
const express = require("express");
const app = express();
Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)
Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.
After you add them change the stylesheet accordingly. For example if it was:
href="cssFileName.css"
and
src="imgName.png"
Make them:
href="css/cssFileName.css"
src="css/images/imgName.png"
That should work
It's not a big deal on a small/personal scale, but it can become a bigger deal quickly on a larger scale. My employer is a large Microsoft shop, but won't/can't buy into Team System/TFS for a number of reasons. We currently use Subversion + Orcas + MBUnit + TestDriven.NET and it works well, but getting TD.NET was a huge hassle. The version sensitivity of MBUnit + TestDriven.NET is also a big hassle, and having one additional commercial thing (TD.NET) for legal to review and procurement to handle and manage, isn't trivial. My company, like a lot of companies, are fat and happy with a MSDN Subscription model, and it's just not used to handling one off procurements for hundreds of developers. In other words, the fully integrated MS offer, while definitely not always best-of-bread, is a significant value-add in my opinion.
I think we'll stay with our current step because it works and we've already gotten over the hump organizationally, but I sure do wish MS had a compelling offering in this space so we could consolidate and simplify our dev stack a bit.
Additionally to the solutions that were suggested in sibling comments, you may change your testing approach a little bit and test not the whole page all at once (with a deep children components tree), but do an isolated component testing. This will simplify testing of onClick()
and similar events (see example below).
The idea is to test only one component at a time and not all of them together. In this case all children components will be mocked using the jest.mock() function.
Here is an example of how the onClick()
event may be tested in an isolated SearchForm
component using Jest and react-test-renderer.
import React from 'react';
import renderer from 'react-test-renderer';
import { SearchForm } from '../SearchForm';
describe('SearchForm', () => {
it('should fire onSubmit form callback', () => {
// Mock search form parameters.
const searchQuery = 'kittens';
const onSubmit = jest.fn();
// Create test component instance.
const testComponentInstance = renderer.create((
<SearchForm query={searchQuery} onSearchSubmit={onSubmit} />
)).root;
// Try to find submit button inside the form.
const submitButtonInstance = testComponentInstance.findByProps({
type: 'submit',
});
expect(submitButtonInstance).toBeDefined();
// Since we're not going to test the button component itself
// we may just simulate its onClick event manually.
const eventMock = { preventDefault: jest.fn() };
submitButtonInstance.props.onClick(eventMock);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenCalledWith(searchQuery);
});
});
background-position: center center;
doesn't work for me without...
background-attachment: fixed;
using both centered my image on x and y axis
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
FOR
is essentially iterating over the "lines" in the data set. In this case, there is one line that contains the path. The "delims=;"
is just telling it to separate on semi-colons. If you change the body to echo %%g,%%h,%%i,%%j,%%k
you'll see that it is treating the input as a single line and breaking it into multiple tokens.
I had the same problem today, here's how I solved it so I could keep lexical_cast<>
typedef unsigned int uint32;
typedef signed int int32;
class uint32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator uint32() const { return value; }
friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
{
in >> std::hex >> outValue.value;
}
};
class int32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator int32() const { return static_cast<int32>( value ); }
friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
{
in >> std::hex >> outvalue.value;
}
};
uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );
int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...
(Found this page when I was looking for a less sucky way :-)
Cheers, A.
Right click on the folder where you put your main class then click on Build Path
--> Use as Source Folder
.
Finally run your main file as java application. Hope this problem will be solved.
data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.
You can use DT[order(-rank(x), y)]
.
x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6
I hope the below example will provide more clarity.
package main
type EmployeeManager struct{
category string
city string
calculateSalary func() int64
}
func NewEmployeeManager() (*EmployeeManager,error){
return &EmployeeManager{
category : "MANAGEMENT",
city : "NY",
calculateSalary: func() int64 {
var calculatedSalary int64
// some formula
return calculatedSalary
},
},nil
}
func (self *EmployeeManager) emWithSalaryCalculation(){
self.calculateSalary = func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}
}
func updateEmployeeInfo(em EmployeeManager){
// Some code
}
func processEmployee(){
updateEmployeeInfo(struct {
category string
city string
calculateSalary func() int64
}{category: "", city: "", calculateSalary: func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}})
}
One liner to make truncate operation:
FileChannel.open(Paths.get("/home/user/file/to/truncate"), StandardOpenOption.WRITE).truncate(0).close();
More information available at Java Documentation: https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html
On Debian/Ubuntu:
aptitude install python-numpy
On Windows, download the installer:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems, download the tar.gz and run the following:
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
The -jar option is mutually exclusive of -classpath. See an old description here
-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.
See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
A quick and dirty hack is to append your classpath to the bootstrap classpath:
-Xbootclasspath/a:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.
However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.
You need to remove the static
from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard
and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new
a new instance of the IDCard
will be created and it will have it's own copies of the 3 variables.
If you use the static
keyword then those variables are common across every instance of IDCard
.
A couple of things to bear in mind:
name
not Name
.This page explains it pretty well.
As a numeric
the allowable range that can be stored in that field is -10^38 +1
to 10^38 - 1
.
The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.
The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.
So the range that can be stored in this particular field is -(10^18 - 1)
to (10^18 - 1)
Or -999999999999999999
to 999999999999999999
Integers only
A remote repository is generally a bare repository — a Git repository that has no working directory. Because the repository is only used as a collaboration point, there is no reason to have a snapshot checked out on disk; it’s just the Git data. In the simplest terms, a bare repository is the contents of your project’s .git directory and nothing else.
You can make a bare git repository with the following code:
$ git clone --bare /path/to/project project.git
One options for having a remote git repository is using SSH protocol:
A common transport protocol for Git when self-hosting is over SSH. This is because SSH access to servers is already set up in most places — and if it isn’t, it’s easy to do. SSH is also an authenticated network protocol and, because it’s ubiquitous, it’s generally easy to set up and use.
To clone a Git repository over SSH, you can specify an
ssh://
URL like this:$ git clone ssh://[user@]server/project.git
Or you can use the shorter scp-like syntax for the SSH protocol:
$ git clone [user@]server:project.git
In both cases above, if you don’t specify the optional username, Git assumes the user you’re currently logged in as.
The Pros
The pros of using SSH are many. First, SSH is relatively easy to set up — SSH daemons are commonplace, many network admins have experience with them, and many OS distributions are set up with them or have tools to manage them. Next, access over SSH is secure — all data transfer is encrypted and authenticated. Last, like the HTTPS, Git and Local protocols, SSH is efficient, making the data as compact as possible before transferring it.
The Cons
The negative aspect of SSH is that it doesn’t support anonymous access to your Git repository. If you’re using SSH, people must have SSH access to your machine, even in a read-only capacity, which doesn’t make SSH conducive to open source projects for which people might simply want to clone your repository to examine it. If you’re using it only within your corporate network, SSH may be the only protocol you need to deal with. If you want to allow anonymous read-only access to your projects and also want to use SSH, you’ll have to set up SSH for you to push over but something else for others to fetch from.
For more information, check the reference: Git on the Server - The Protocols
You can also use Date.now() function.
I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.
The following code works lately:
string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";
using (MySqlConnection cn = new MySqlConnection(connetionString))
{
try
{
string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
cn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, cn))
{
cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
cmd.ExecuteNonQuery();
}
}
catch (MySqlException ex)
{
MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
}
}
The Clear
method is defined as
public void Clear() {
Text = null;
}
The Text
property's setter starts with
set {
if (value == null) {
value = "";
}
I assume this answers your question.
The first day of the previous month is always 1, to get the last day of the previous month, use 0 with DateSerial:
''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013
DateSerial(Year(Date),1,0) = 31/12/2012
You can get the first day from the above like so:
LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1
See also: How to caculate last business day of month in VBScript
int sum = 0;
for (int i = 0; i < yourArray.length; i++)
{
sum = sum + yourArray[i];
}
For React 16 and React >=15.6
Setter .value=
is not working as we wanted because React library overrides input value setter but we can call the function directly on the input
as context.
var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeInputValueSetter.call(input, 'react 16 value');
var ev2 = new Event('input', { bubbles: true});
input.dispatchEvent(ev2);
For textarea element you should use prototype
of HTMLTextAreaElement
class.
New codepen example.
All credits to this contributor and his solution
Outdated answer only for React <=15.5
With react-dom ^15.6.0
you can use simulated
flag on the event object for the event to pass through
var ev = new Event('input', { bubbles: true});
ev.simulated = true;
element.value = 'Something new';
element.dispatchEvent(ev);
I made a codepen with an example
To understand why new flag is needed I found this comment very helpful:
The input logic in React now dedupe's change events so they don't fire more than once per value. It listens for both browser onChange/onInput events as well as sets on the DOM node value prop (when you update the value via javascript). This has the side effect of meaning that if you update the input's value manually input.value = 'foo' then dispatch a ChangeEvent with { target: input } React will register both the set and the event, see it's value is still `'foo', consider it a duplicate event and swallow it.
This works fine in normal cases because a "real" browser initiated event doesn't trigger sets on the element.value. You can bail out of this logic secretly by tagging the event you trigger with a simulated flag and react will always fire the event. https://github.com/jquense/react/blob/9a93af4411a8e880bbc05392ccf2b195c97502d1/src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js#L128
I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.
I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log
MySQL could not start.
I resolved it by removing the following directory: /var/lib/mysql/mysql
sudo rm -rf /var/lib/mysql/mysql
This leaves your other DB related files in place, only removing the mysql related files.
After running these:
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
Then reinstalling mysql:
sudo apt-get install mysql-server
It worked perfectly.
It's perfectly safe as long as you always access the values through the struct via the .
(dot) or ->
notation.
What's not safe is taking the pointer of unaligned data and then accessing it without taking that into account.
Also, even though each item in the struct is known to be unaligned, it's known to be unaligned in a particular way, so the struct as a whole must be aligned as the compiler expects or there'll be trouble (on some platforms, or in future if a new way is invented to optimise unaligned accesses).
We can decode json string into array using json_decode function in php
1) json_decode($json_string) // it returns object
2) json_decode($json_string,true) // it returns array
$json_string = '{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$array = json_decode($json_string,true);
echo $array['type']; //it gives donut
Here are the step:
You are done! :)
One-liner:
$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))"
Yes, you can set the screen orientation programatically anytime you want using:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.
And this is how you can get the current screen orientation and set it adequatly depending on its current state:
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
final int orientation = display.getOrientation();
// OR: orientation = getRequestedOrientation(); // inside an Activity
// set the screen orientation on button click
Button btn = (Button) findViewById(R.id.yourbutton);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}
});
Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/
EDIT
Also, you can get the screen orientation using the Configuration
:
Activity.getResources().getConfiguration().orientation
The main problem was that you were opening/closing files repeatedly inside your loop.
Try this approach:
with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:
for line in text_file:
var1, var2 = line.split(",");
myfile.write(var1+'\n')
We open both files at once and because we are using with
they will be automatically closed when we are done (or an exception occurs). Previously your output file was repeatedly openend inside your loop.
We are also processing the file line-by-line, rather than reading all of it into memory at once (which can be a problem when you deal with really big files).
Note that write()
doesn't append a newline ('\n'
) so you'll have to do that yourself if you need it (I replaced your writelines()
with write()
as you are writing a single item, not a list of items).
When opening a file for r
read, the 'r'
is optional since it's the default mode.
This class-based javascript animation works in AngularJS 1.2 (and 1.4 tested)
Edit: I ended up abandoning this code and went a completely different direction. I like my other answer much better. This answer will give you some problems in certain situations.
myApp.animation('.ng-show-toggle-slidedown', function(){
return {
beforeAddClass : function(element, className, done){
if (className == 'ng-hide'){
$(element).slideUp({duration: 400}, done);
} else {done();}
},
beforeRemoveClass : function(element, className, done){
if (className == 'ng-hide'){
$(element).css({display:'none'});
$(element).slideDown({duration: 400}, done);
} else {done();}
}
}
});
Simply add the .ng-hide-toggle-slidedown
class to the container element, and the jQuery slide down behavior will be implemented based on the ng-hide class.
You must include the $(element).css({display:'none'})
line in the beforeRemoveClass
method because jQuery will not execute a slideDown unless the element is in a state of display: none
prior to starting the jQuery animation. AngularJS uses the CSS
.ng-hide:not(.ng-hide-animate) {
display: none !important;
}
to hide the element. jQuery is not aware of this state, and jQuery will need the display:none
prior to the first slide down animation.
The AngularJS animation will add the .ng-hide-animate
and .ng-animate
classes while the animation is occuring.
Though the string parsing solution is the most popular, I don't like it, because parsing string can be a great performance hit in some situations.
When there is needed a kind of a bitfield or binary mask, I'd rather write it like
long bitMask = 1011001;
And later
int bit5 = BitField.GetBit(bitMask, 5);
Or
bool flag5 = BitField.GetFlag(bitMask, 5);`
Where BitField class is
public static class BitField
{
public static int GetBit(int bitField, int index)
{
return (bitField / (int)Math.Pow(10, index)) % 10;
}
public static bool GetFlag(int bitField, int index)
{
return GetBit(bitField, index) == 1;
}
}
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
You can read more about share button here on Facebook developers website
Working JSFIDDLE
Also take a look at custom Facebook Share button JSFIDDLE
Include Facebook JavaScript SDK code right after the opening <body>
tag
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
And place below code wherever you want to show Facebook Share button
<div class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-width="200" data-type="button_count"></div>
Check working JSFIDDLE
Add this statement on your header tag:
<style>
a:link{
text-decoration: none!important;
cursor: pointer;
}
</style>
You can handle the Firefox driver automatically using WebDriverManager.
This library downloads the proper binary (geckodriver) for your platform (Mac, Windows, Linux) and then exports the proper value of the required Java environment variable (webdriver.gecko.driver).
Take a look at a complete example as a JUnit test case:
public class FirefoxTest {
private WebDriver driver;
@BeforeClass
public static void setupClass() {
WebDriverManager.firefoxdriver().setup();
}
@Before
public void setupTest() {
driver = new FirefoxDriver();
}
@After
public void teardown() {
if (driver != null) {
driver.quit();
}
}
@Test
public void test() {
// Your test code here
}
}
If you are using Maven you have to put at your pom.xml
:
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>4.3.1</version>
</dependency>
WebDriverManager does magic for you:
So far, WebDriverManager supports Chrome
, Opera
, Internet Explorer
, Microsoft Edge
, PhantomJS
, and Firefox
.
The difference between "" and () is:
With "" you are not calling anything.
With () you are calling a sub.
Example with sub:
Sub = MsgBox("Msg",vbYesNo,vbCritical,"Title")
Select Case Sub
Case = vbYes
MsgBox"You said yes"
Case = vbNo
MsgBox"You said no"
End Select
vs Normal:
MsgBox"This is normal"
dplyr
definitely does things that data.table
can not.Your point #3
dplyr abstracts (or will) potential DB interactions
is a direct answer to your own question but isn't elevated to a high enough level. dplyr
is truly an extendable front-end to multiple data storage mechanisms where as data.table
is an extension to a single one.
Look at dplyr
as a back-end agnostic interface, with all of the targets using the same grammer, where you can extend the targets and handlers at will. data.table
is, from the dplyr
perspective, one of those targets.
You will never (I hope) see a day that data.table
attempts to translate your queries to create SQL statements that operate with on-disk or networked data stores.
dplyr
can possibly do things data.table
will not or might not do as well.Based on the design of working in-memory, data.table
could have a much more difficult time extending itself into parallel processing of queries than dplyr
.
Are there analytical tasks that are a lot easier to code with one or the other package for people familiar with the packages (i.e. some combination of keystrokes required vs. required level of esotericism, where less of each is a good thing).
This may seem like a punt but the real answer is no. People familiar with tools seem to use the either the one most familiar to them or the one that is actually the right one for the job at hand. With that being said, sometimes you want to present a particular readability, sometimes a level of performance, and when you have need for a high enough level of both you may just need another tool to go along with what you already have to make clearer abstractions.
Are there analytical tasks that are performed substantially (i.e. more than 2x) more efficiently in one package vs. another.
Again, no. data.table
excels at being efficient in everything it does where dplyr
gets the burden of being limited in some respects to the underlying data store and registered handlers.
This means when you run into a performance issue with data.table
you can be pretty sure it is in your query function and if it is actually a bottleneck with data.table
then you've won yourself the joy of filing a report. This is also true when dplyr
is using data.table
as the back-end; you may see some overhead from dplyr
but odds are it is your query.
When dplyr
has performance issues with back-ends you can get around them by registering a function for hybrid evaluation or (in the case of databases) manipulating the generated query prior to execution.
Also see the accepted answer to when is plyr better than data.table?
Basically, you're trying to use int
as if it was an Object
, which it isn't (well...it's complicated)
id.equals(list[pos].getItemNumber())
Should be...
id == list[pos].getItemNumber()
It is only required if you aren't using the default values for version
and encoding
(which you are in that example).
http://jsfiddle.net/isherwood/gfgux
html, body {
height: 100%;
}
#table-row, #table-col, #table-wrapper {
height: 80%;
}
<div id="content" class="container">
<div id="table-row" class="row">
<div id="table-col" class="col-md-7 col-xs-10 pull-left">
<p>Hello</p>
<div id="table-wrapper" class="table-responsive">
<table class="table table-bordered ">
Build up a JavaScript data structure with the required information, then turn it into the json string at the end.
Based on what I think you're doing, try something like this:
var result = [];
for (var name in goals) {
if (goals.hasOwnProperty(name)) {
result.push({name: name, goals: goals[name]});
}
}
res.contentType('application/json');
res.send(JSON.stringify(result));
or something along those lines.
Inside a class definition, $this
refers to the current object, while self
refers to the current class.
It is necessary to refer to a class element using self
, and refer to an object element using $this
.
self::STAT // refer to a constant value
self::$stat // static variable
$this->stat // refer to an object variable
You config proxy settings for some network and now you connect another network. Now have to remove the proxy settings. For that use these commands:
git config --global --unset https.proxy
git config --global --unset http.proxy
Now you can push too. (If did not remove proxy configuration still you can use git commands like add , commit and etc)
remove it and run eclipse-installer again without root
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Source: W3Schools
Edit: as @zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
You can use the following line to drop the first two columns (or any column you don't need):
df.drop([df.columns[0], df.columns[1]], axis=1)
package main
import (
"fmt"
"time"
)
// @link https://golang.org/pkg/time/
func main() {
//caution : format string is `2006-01-02 15:04:05.000000000`
current := time.Now()
fmt.Println("origin : ", current.String())
// origin : 2016-09-02 15:53:07.159994437 +0800 CST
fmt.Println("mm-dd-yyyy : ", current.Format("01-02-2006"))
// mm-dd-yyyy : 09-02-2016
fmt.Println("yyyy-mm-dd : ", current.Format("2006-01-02"))
// yyyy-mm-dd : 2016-09-02
// separated by .
fmt.Println("yyyy.mm.dd : ", current.Format("2006.01.02"))
// yyyy.mm.dd : 2016.09.02
fmt.Println("yyyy-mm-dd HH:mm:ss : ", current.Format("2006-01-02 15:04:05"))
// yyyy-mm-dd HH:mm:ss : 2016-09-02 15:53:07
// StampMicro
fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000"))
// yyyy-mm-dd HH:mm:ss: 2016-09-02 15:53:07.159994
//StampNano
fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000000"))
// yyyy-mm-dd HH:mm:ss: 2016-09-02 15:53:07.159994437
}
An image may say more than a thousand words:
* Figure describing the complexity of a modern multi-processor, multi-core system.
Source:
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
I had a similar problem, however in my case I could pull/push to the remote branch but git status
didn't show the local branch state w.r.t the remote ones.
Also, in my case git config --get remote.origin.fetch
didn't return anything
The problem is that there was a typo in the .git/config
file in the fetch line of the respective remote block. Probably something I added by mistake previously (sometimes I directly look at this file, or even edit it)
So, check if your remote entry in the .git/config
file is correct, e.g.:
[remote "origin"]
url = https://[server]/[user or organization]/[repo].git
fetch = +refs/heads/*:refs/remotes/origin/*
If you are coming here because you are using Apache commons logging with log4j and log4j isn't working as you expect then check that you actually have a log4j.jar in your run-time classpath. That one had me puzzled for a little while. I have now configured the runner in my dev environment to include -Dlog4j.debug in the Java command line so I can always see that Log4j is being initialized correctly
Are you looking for...
a if b else c
Or perhaps you misunderstand Python's or
? True or True
is True
.
Very annoying, no cookie file exmpale on the official website https://ec.haxx.se/http/http-cookies.
Finnaly, I find it does not work, if your file content is just copyied like this
foo1=bar;foo2=bar2
I gusess the format must looks the style said by @Agustí Sánchez . You can test it by -c to create a cookie file on a website.
So try this way, it works
curl -H "Cookie:`cat ./my.cookie`" http://xxxx.com
You can just copy the cookie from chrome console network tab.
This might help http://docs.pytest.org/en/latest/xunit_setup.html
In my test suite, I group my test cases into classes. For the setup and teardown I need for all the test cases in that class, I use the setup_class(cls)
and teardown_class(cls)
classmethods.
And for the setup and teardown I need for each of the test case, I use the setup_method(method)
and teardown_method(methods)
Example:
lh = <got log handler from logger module>
class TestClass:
@classmethod
def setup_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
@classmethod
def teardown_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
def setup_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def teardown_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def test_tc1(self):
<tc_content>
assert
def test_tc2(self):
<tc_content>
assert
Now when I run my tests, when the TestClass execution is starting, it logs the details for when it is beginning execution, when it is ending execution and same for the methods..
You can add up other setup and teardown steps you might have in the respective locations.
Hope it helps!
I would EXPECT the first query to be quicker, mainly because you have an equivalence and an explicit JOIN. In my experience IN
is a very slow operator, since SQL normally evaluates it as a series of WHERE
clauses separated by "OR" (WHERE x=Y OR x=Z OR...
).
As with ALL THINGS SQL though, your mileage may vary. The speed will depend a lot on indexes (do you have indexes on both ID columns? That will help a lot...) among other things.
The only REAL way to tell with 100% certainty which is faster is to turn on performance tracking (IO Statistics is especially useful) and run them both. Make sure to clear your cache between runs!
Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.
Let me tell you an annoying thing that happened with the N'
prefix - I wasn't able to fix it for two days.
My database collation is SQL_Latin1_General_CP1_CI_AS.
It has a table with a column called MyCol1. It is an Nvarchar
This query fails to match Exact Value That Exists.
SELECT TOP 1 * FROM myTable1 WHERE MyCol1 = 'ESKI'
// 0 result
using prefix N'' fixes it
SELECT TOP 1 * FROM myTable1 WHERE MyCol1 = N'ESKI'
// 1 result - found!!!!
Why? Because latin1_general doesn't have big dotted I that's why it fails I suppose.
This search engine was made to solve exactly the kind of problem you're having: http://symbolhound.com/
I am the developer of SymbolHound.
I used this code where you subtract 0.5 from the number and when you round it, it is the original number rounded down.
round(a-0.5)
Although JavaScript gives you many great ways of formatting and calculations, I prefer using the Moment.js (momentjs.com) library during application development as it's very intuitive and saves a lot of time.
Nonetheless, I suggest everyone to learn about the basic JavaScript API too for a better understanding.
The following code can be used to read the input string from a user. But it's space is limited to 64.
char word[64] = { '\0' }; //initialize all elements with '\0'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
scanf_s("%c", &word[i++], 1);
}
Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.
I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch
sentence.
def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
val props = new Properties()
props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
props.put("group.id", kafkaParams.get("group.id").get.toString)
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
val simpleConsumer = new KafkaConsumer[String, String](props)
simpleConsumer.listTopics()
}
First method you can try this
$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();
Another way to insert records into the database with create function
$department = new Department;
// Another Way to insert records
$department->create($request->all());
return redirect('admin/departments');
You need to set the filledby in Department model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $fillable = ['department_name','status'];
}
You can pass values from one page to another by followings..
Response.Redirect
Cookies
Application Variables
HttpContext
Response.Redirect
SET :
Response.Redirect("Defaultaspx?Name=Pandian");
GET :
string Name = Request.QueryString["Name"];
Cookies
SET :
HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian";
GET :
string name = Request.Cookies["Name"].Value;
Application Variables
SET :
Application["Name"] = "pandian";
GET :
string Name = Application["Name"].ToString();
Refer the full content here : Pass values from one to another
On linux distributions (@least on Debian with plasma) the default shortcut is
Ctrl + 0
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).
printf("%llu", 285212672);
If you need to include non-ASCII alphabetic characters, and if your regex flavor supports Unicode, then
\A\pL+\z
would be the correct regex.
Some regex engines don't support this Unicode syntax but allow the \w
alphanumeric shorthand to also match non-ASCII characters. In that case, you can get all alphabetics by subtracting digits and underscores from \w
like this:
\A[^\W\d_]+\z
\A
matches at the start of the string, \z
at the end of the string (^
and $
also match at the start/end of lines in some languages like Ruby, or if certain regex options are set).
if you have properties in your class this line of code is OK !!
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
but if you have all public fields then use this:
public static DataTable ToDataTable<T>( IList<T> data)
{
FieldInfo[] myFieldInfo;
Type myType = typeof(T);
// Get the type and fields of FieldInfoClass.
myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.Public);
DataTable dt = new DataTable();
for (int i = 0; i < myFieldInfo.Length; i++)
{
FieldInfo property = myFieldInfo[i];
dt.Columns.Add(property.Name, property.FieldType);
}
object[] values = new object[myFieldInfo.Length];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = myFieldInfo[i].GetValue(item);
}
dt.Rows.Add(values);
}
return dt;
}
the original answer is from above , I just edited to use fields instead of properties
and to use it do this
DataTable dt = new DataTable();
dt = ToDataTable(myBriefs);
gridData.DataSource = dt;
gridData.DataBind();
Using union will help in this case.
You can also use join on a condition that always returns true and is not related to data in these tables.See below
select tmd .name,tbc.goals from tblMadrid tmd join tblBarcelona tbc on 1=1;
The easiest way would be
Section = 'Sec_' + Section
But for efficiency, see: https://waymoot.org/home/python_string/
Just to make your script more readable, maybe use this proc:
DELIMITER ;;
DROP PROCEDURE IF EXISTS printf;
CREATE PROCEDURE printf(thetext TEXT)
BEGIN
select thetext as ``;
END;
;;
DELIMITER ;
Now you can just do:
call printf('Counting products that have missing short description');
Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat',
data = fake,
color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()
instead of just table name, you can also write a query for getting only selected column data.
COPY (select id,name from tablename) TO 'filepath/aa.csv' DELIMITER ',' CSV HEADER;
with admin privilege
\COPY (select id,name from tablename) TO 'filepath/aa.csv' DELIMITER ',' CSV HEADER;
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
I'm using below excel file url: https://github.com/inventorbala/Sample-Excel-files/blob/master/sample-excel-files.xlsx
Output:
Array
(
[0] => Array
(
[store_id] => 3716
[employee_uid] => 664368
[opus_id] => zh901j
[item_description] => PRE ATT $75 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => X2MBV1DJKSLQW
[opus_invoice_num] => O3716IN3409
[customer_name] => BILL PHILLIPS
[mobile_num] => 4052380136
[opus_amount] => 75
[rq4_amount] => 0
[difference] => -75
[ocomment] => Re-Upload: We need RQ4 transaction for October. If you're unable to provide the October invoice, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[1] => Array
(
[store_id] => 2710
[employee_uid] => 75899
[opus_id] => dc288t
[item_description] => PRE ATT $50 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => XJ90419JKT9R9
[opus_invoice_num] => M2710IN868
[customer_name] => CALEB MENDEZ
[mobile_num] => 6517672079
[opus_amount] => 50
[rq4_amount] => 0
[difference] => -50
[ocomment] => No Response. Re-Upload
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[2] => Array
(
[store_id] => 0136
[employee_uid] => 70167
[opus_id] => fv766x
[item_description] => PRE ATT $50 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => XQ57316JKST1V
[opus_invoice_num] => GONZABP25622
[customer_name] => FAUSTINA CASTILLO
[mobile_num] => 8302638628
[opus_amount] => 100
[rq4_amount] => 50
[difference] => -50
[ocomment] => Re-Upload: We have been charged in opus for $100. Provide RQ4 invoice number for remaining amount
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[3] => Array
(
[store_id] => 3264
[employee_uid] => 23723
[opus_id] => aa297h
[item_description] => PRE ATT $25 PNLS 90EXP
[opus_transaction_date] => 2019-10-19
[opus_transaction_num] => XR1181HJKW9MP
[opus_invoice_num] => C3264IN1588
[customer_name] => SOPHAT VANN
[mobile_num] => 9494668372
[opus_amount] => 70
[rq4_amount] => 25
[difference] => -45
[ocomment] => No Response. Re-Upload
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[4] => Array
(
[store_id] => 4166
[employee_uid] => 568494
[opus_id] => ab7598
[item_description] => PRE ATT $40 RTR
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => X8F58P3JL2RFU
[opus_invoice_num] => I4166IN2481
[customer_name] => KELLY MC GUIRE
[mobile_num] => 6189468180
[opus_amount] => 40
[rq4_amount] => 0
[difference] => -40
[ocomment] => Re-Upload: The invoice number that you provided (I4166IN2481) belongs to September transaction. We need RQ4 transaction for October. If you're unable to provide the October invoice, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[5] => Array
(
[store_id] => 4508
[employee_uid] => 552502
[opus_id] => ec850x
[item_description] => $30 RTR
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XPL7M1BJL1W5D
[opus_invoice_num] => M4508IN6024
[customer_name] => PREPAID CUSTOMER
[mobile_num] => 6019109730
[opus_amount] => 30
[rq4_amount] => 0
[difference] => -30
[ocomment] => Re-Upload: The invoice number you provided (M4508IN7217) belongs to a different phone number. We need RQ4 transaction for the phone number in question. If you're unable to provide the RQ4 invoice for this transaction, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[6] => Array
(
[store_id] => 3904
[employee_uid] => 35818
[opus_id] => tj539j
[item_description] => PRE $45 PAYG PINLESS REFILL
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XM1PZQSJL215F
[opus_invoice_num] => N3904IN1410
[customer_name] => DORTHY JONES
[mobile_num] => 3365982631
[opus_amount] => 90
[rq4_amount] => 45
[difference] => -45
[ocomment] => Re-Upload: Please email the details to Treasury and confirm
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[7] => Array
(
[store_id] => 1820
[employee_uid] => 59883
[opus_id] => cb9406
[item_description] => PRE ATT $25 PNLS 90EXP
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XTBJO14JL25OE
[opus_invoice_num] => SEVIEIN19013
[customer_name] => RON NELSON
[mobile_num] => 8653821076
[opus_amount] => 25
[rq4_amount] => 5
[difference] => -20
[ocomment] => Re-Upload: We have been charged in opus for $25. Provide RQ4 invoice number for remaining amount
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[8] => Array
(
[store_id] => 0178
[employee_uid] => 572547
[opus_id] => ms5674
[item_description] => PRE $45 PAYG PINLESS REFILL
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XT29916JL4S69
[opus_invoice_num] => T0178BP1590
[customer_name] => GABRIEL LONGORIA JR
[mobile_num] => 4322133450
[opus_amount] => 45
[rq4_amount] => 0
[difference] => -45
[ocomment] => Re-Upload: Please email the details to Treasury and confirm
[mark_delete] => 0
[upload_date] => 2019-10-22
)
[9] => Array
(
[store_id] => 2180
[employee_uid] => 7842
[opus_id] => lm854y
[item_description] => $30 RTR
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XC9U712JL4LA4
[opus_invoice_num] => KETERIN1836
[customer_name] => PETE JABLONSKI
[mobile_num] => 9374092680
[opus_amount] => 30
[rq4_amount] => 40
[difference] => 10
[ocomment] => Re-Upload: Credit the remaining balance to customers account in OPUS and email confirmation to Treasury
[mark_delete] => 0
[upload_date] => 2019-10-22
)
.
.
.
[63] => Array
(
[store_id] => 0175
[employee_uid] => 33738
[opus_id] => ph5953
[item_description] => PRE ATT $40 RTR
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XE5N31DJL51RA
[opus_invoice_num] => T0175IN4563
[customer_name] => WILLIE TAYLOR
[mobile_num] => 6822701188
[opus_amount] => 40
[rq4_amount] => 50
[difference] => 10
[ocomment] => Re-Upload: Credit the remaining balance to customers account in OPUS and email confirmation to Treasury
[mark_delete] => 0
[upload_date] => 2019-10-22
)
)
As far as "built-in" libraries go, the <<
and >>
have been reserved specifically for serialization.
You should override <<
to output your object to some serialization context (usually an iostream
) and >>
to read data back from that context. Each object is responsible for outputting its aggregated child objects.
This method works fine so long as your object graph contains no cycles.
If it does, then you will have to use a library to deal with those cycles.
This can also be caused by leaving the Services console open. Windows won't actually delete the service until it is closed.
This would definitely help Many!
private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
{
if(e.nButton==2)
{
contextMenuStrip1.Show(MousePosition);
}
}
[ e.nbutton==2 ] is like [ e.button==MouseButtons.Right ]
That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.
I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.
I like Get-Command | Format-List
, or shorter, using aliases for the two and only for powershell.exe
:
gcm powershell | fl
You can find aliases like this:
alias -definition Format-List
Tab completion works with gcm
.
There some issues with pow method:
Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.
public static long pow(long x, int y) {
long result = 1;
while (y > 0) {
if ((y & 1) == 0) {
x *= x;
y >>>= 1;
} else {
result *= x;
y--;
}
}
return result;
}
Do your trouble shooting in controlled steps:
(1) Does the script looks ok?
DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
type ansi.sql
show databases
(2) Can you connect to your database (even without specified the host)?
DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
mysql -u root -p mysql
Enter password: ********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.0.51b-community-nt MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
(3) Can you source the script? (Hoping for more/better error info)
mysql> source ansi.sql
+--------------------+
| Database |
+--------------------+
| information_schema |
| ... |
| test |
+--------------------+
7 rows in set (0.01 sec)
mysql> quit
Bye
(4) Why does it (still not) work?
DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
mysql -u root -p mysql < ansi.sql
Enter password: ********
Database
information_schema
...
test
I suspected that the encoding of the script could be the culprit, but I got syntax errors for UTF8 or UTF16 encoded files:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '´++
show databases' at line 1
This could be a version thing; so I think you should make sure of the encoding of your script.
In my case I have added the jars twice in build path after importing from war. It worked fine after removing the extra jars which was showing error deployment descriptor error pages
adding
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>service.package.name</param-value>
</init-param>
Node.js is an open source command line tool built for the server side JavaScript code.
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.
Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
The basic philosophy of node.js is:
Non-blocking I/O - every I/O call must take a callback, whether it is to retrieve information from disk, network or another process. Built-in support for the most important protocols (HTTP, DNS, TLS) Low-level. Do not remove functionality present at the POSIX layer. For example, support half-closed TCP connections. Stream everything; never force the buffering of data.
Extension method should be inside a static class. So please add your extension method inside a static class.
so for example it should be like this
public static class myclass
{
public static Byte[] ToByteArray(this Stream stream)
{
Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
Byte[] buffer = new Byte[length];
stream.Read(buffer, 0, length);
return buffer;
}
}
When maven is working outside of Eclipse, but giving this error after a JDK change, Go to your Maven Run Configuration, and at the bottom of the Main page, there's a 'Maven Runtime' option. Mine was using the Embedded Maven, so after switching it to use my external maven, it worked.
Thanks to Andrey Egorov, in my case with python setAttribute
not working, but I found I can set the property directly,
Try this code:
driver.execute_script("document.getElementById('q').value='value here'")
You could use the synchronize module. The example from the documentation:
# Synchronize two directories on one remote host.
- synchronize:
src: /first/absolute/path
dest: /second/absolute/path
delegate_to: "{{ inventory_hostname }}"
This has the added benefit that it will be more efficient for large/many files.
I managed to connect to postgres with SQL Developer. I downloaded postgres jdbc driver and saved it in a folder. I run SQL Developer -> Tools -> Preferences -> Search -> JDBC I defined postgres jdbc driver for the Database and Data Modeler (optional).
This is the trick. When creating new connection define Hostname like localhost/crm? where crm is the database name. Test the connection, works fine.
Just npm install
to install node_modules
Since you have textfields in a table, the best way really is to resize the table - you need to set the tableView.frame to be smaller in height by the size of the keyboard (I think around 165 pixels) and then expand it again when the keyboard is dismissed.
You can optionally also disable user interaction for the tableView at that time as well, if you do not want the user scrolling.
Try this in web.config to replace IIS error pages. This is the best solution I guess, and it sends out the correct status code too.
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="404" path="Error404.html" responseMode="File" />
<error statusCode="500" path="Error.html" responseMode="File" />
</httpErrors>
</system.webServer>
More info from Tipila - Use Custom Error Pages ASP.NET MVC
Add this line to your change
event handler
$("#theSelect option:selected").attr('disabled','disabled')
.siblings().removeAttr('disabled');
This will disable the selected option, and enable any previously disabled options.
EDIT:
If you did not want to re-enable the previous ones, just remove this part of the line:
.siblings().removeAttr('disabled');
EDIT:
To re-enable when you click remove, add this to your click handler.
$("#theSelect option[value=" + value + "]").removeAttr('disabled');
I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
instead of modifying adb_usb.ini file I made changes on the file android_winusb.inf under directory android-sdk\extras\google\usb_driver\ alone and it worked for the tablet MID Q88 but i copied both sections [Google.NTamd64] and [Google.NTx86]
;Google MID Q88
%SingleAdbInterface% = USB_INSTALL, USB\VID_18D1&PID_0003&MI_01
%CompositeAdbInterface% = USB_INSTALL, USB\VID_18D1&PID_0003&REV_0230&MI_01
.NET Core will install and run on macOS - and just about any other desktop OS.
IDEs are available for the mac, including:
Mono is a good option that I've used in the past. But with Core 3.0 out now, I would go that route.
You can use
CharSequence[] cs = String[] {"String to CharSequence"};
Use the following command before defining them:
cmd.Parameters.Clear()
To match regexes you need to use the =~
operator.
Try this:
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
Alternatively, you can use wildcards (instead of regexes) with the ==
operator:
[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched
If portability is not a concern, I recommend using [[
instead of [
or test
as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.
CREATE TABLE NEW_TABLENAME LIKE OLD_TABLENAME;
Works for DB2 V 9.7
You could write a simple jQuery plugin to do this. The plugin would look like:
(function($) {
$.fn.expandcollapse = function() {
return this.each(function() {
obj = $(this);
switch (obj.css("display")) {
case "block":
displayValue = "none";
break;
case "none":
default:
displayValue = "block";
}
obj.css("display", displayValue);
});
};
} (jQuery));
Then wire the plugin up to the click event for the anchor tag:
$(document).ready(function() {
$("#mylink").click(function() {
$("div").expandcollapse();
});
});
Providing that you set the initial 'display' attributes for each div to be 'block' and 'none' respectively, they should switch to being shown/hidden when the link is clicked.
You can use cvResize
. Or better use c++ interface (eg cv::Mat
instead of IplImage
and cv::imread
instead of cvLoadImage
) and then use cv::resize
which handles memory allocation and deallocation itself.
I found that focus
does not work when trying to get a focus on a text element (such as a notice div
), but does work when focusing on input fields.
While specifying spellcheck="false" in the < tag > will certainly disable that feature, it's handy to be able to toggle that functionality on and off as needed after the page has loaded. So here's a non-jQuery way to set the spellcheck attribute programmatically:
:
<textarea id="my-ta" spellcheck="whatever">abcd dcba</textarea>
:
function setSpellCheck( mode ) {
var myTextArea = document.getElementById( "my-ta" )
, myTextAreaValue = myTextArea.value
;
myTextArea.value = '';
myTextArea.setAttribute( "spellcheck", String( mode ) );
myTextArea.value = myTextAreaValue;
myTextArea.focus();
}
:
setSpellCheck( true );
setSpellCheck( 'false' );
The function argument may be either boolean or string.
No need to loop through the textarea contents, we just cut 'n paste what's there, and then set focus.
Tested in blink engines (Chrome(ium), Edge, etc.)
I wrote the following, which works in vanilla Python 2 or Python 3.
import sys
try:
import urllib.request
python3 = True
except ImportError:
import urllib2
python3 = False
def progress_callback_simple(downloaded,total):
sys.stdout.write(
"\r" +
(len(str(total))-len(str(downloaded)))*" " + str(downloaded) + "/%d"%total +
" [%3.2f%%]"%(100.0*float(downloaded)/float(total))
)
sys.stdout.flush()
def download(srcurl, dstfilepath, progress_callback=None, block_size=8192):
def _download_helper(response, out_file, file_size):
if progress_callback!=None: progress_callback(0,file_size)
if block_size == None:
buffer = response.read()
out_file.write(buffer)
if progress_callback!=None: progress_callback(file_size,file_size)
else:
file_size_dl = 0
while True:
buffer = response.read(block_size)
if not buffer: break
file_size_dl += len(buffer)
out_file.write(buffer)
if progress_callback!=None: progress_callback(file_size_dl,file_size)
with open(dstfilepath,"wb") as out_file:
if python3:
with urllib.request.urlopen(srcurl) as response:
file_size = int(response.getheader("Content-Length"))
_download_helper(response,out_file,file_size)
else:
response = urllib2.urlopen(srcurl)
meta = response.info()
file_size = int(meta.getheaders("Content-Length")[0])
_download_helper(response,out_file,file_size)
import traceback
try:
download(
"https://geometrian.com/data/programming/projects/glLib/glLib%20Reloaded%200.5.9/0.5.9.zip",
"output.zip",
progress_callback_simple
)
except:
traceback.print_exc()
input()
Notes:
If one need to use the sp_executesql
with OUTPUT
variables:
EXEC sp_executesql @sql
,N'@p0 INT'
,N'@p1 INT OUTPUT'
,N'@p2 VARCHAR(12) OUTPUT'
,@p0
,@p1 OUTPUT
,@p2 OUTPUT;
\n didn't work for me. So I used <br></br>
HTML tag
<string name="message_register_success">
Sign up is complete. <br></br>
Enjoy a new shopping life at MageMobile!!
</string>
Java doesn't have goto
, because it makes the code unstructured and unclear to read. However, you can use break
and continue
as civilized form of goto without its problems.
ahead: {
System.out.println("Before break");
break ahead;
System.out.println("After Break"); // This won't execute
}
// After a line break ahead, the code flow starts from here, after the ahead block
System.out.println("After ahead");
Output:
Before Break
After ahead
before: {
System.out.println("Continue");
continue before;
}
This will result in an infinite loop as every time the line continue before
is executed, the code flow will start again from before
.
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
Here it is. Add this code to your web.config file:
<system.webServer>
<rewrite>
<rules>
<rule name="Root Hit Redirect" stopProcessing="true">
<match url="^$" />
<action type="Redirect" url="/menu_1/MainScreen.aspx" />
</rule>
</rules>
</rewrite>
</system.webServer>
It will do 301 Permanent Redirect (URL will be changed in browser). If you want to have such "redirect" to be invisible (rewrite, internal redirect), then use this rule (the only difference is that "Redirect" has been replaced by "Rewrite"):
<system.webServer>
<rewrite>
<rules>
<rule name="Root Hit Redirect" stopProcessing="true">
<match url="^$" />
<action type="Rewrite" url="/menu_1/MainScreen.aspx" />
</rule>
</rules>
</rewrite>
</system.webServer>
Maybe this will help... this was used in the full size jQuery calendar click event (http://arshaw.com/fullcalendar/)... but it can be used more generally to deal with fancybox being launched by jQuery.
eventClick: function(calEvent, jsEvent, view) {
jQuery("body").after('<a id="link_'+calEvent.url+'" style="display: hidden;" href="http://thisweekinblackness.com/wp-content/uploads/2009/01/steve-urkel.jpg">Steve</a>');
jQuery('#link_'+calEvent.url).fancybox();
jQuery('#link_'+calEvent.url).click();
jQuery('#link_'+calEvent.url).remove();
return false;
}
$(document).ready(function() {
$('#reset').click(function() {
$('#compose_form').find("input[type=text] , textarea ").each(function() {
$(this).val('');
});
});
});
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module.
It can be used to get the inverse cumulative distribution function (inv_cdf
- inverse of the cdf
), also known as the quantile function or the percent-point function for a given mean (mu
) and standard deviation (sigma
):
from statistics import NormalDist
NormalDist(mu=10, sigma=2).inv_cdf(0.95)
# 13.289707253902943
Which can be simplified for the standard normal distribution (mu = 0
and sigma = 1
):
NormalDist().inv_cdf(0.95)
# 1.6448536269514715
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file name>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
The usual method is to use the NEWID() function, which generates a unique GUID. So,
SELECT * FROM dbo.Foo ORDER BY NEWID();
Use document.write().
<html>_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
var number = 123;_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>_x000D_
the value for number is:_x000D_
<script type="text/javascript">_x000D_
document.write(number)_x000D_
</script>_x000D_
</h1>_x000D_
</body>_x000D_
</html>
_x000D_
This should solve your problem: FB Share button/dialog documentation Genereally speaking you can use either normal HTML code and style it with CSS, or you can use Javascript.
Here is an example:
<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fparse.com" target="_blank" rel="noopener">
<img class="YOUR_FB_CSS_STYLING_CLASS" src="img/YOUR_FB_ICON_IMAGE.png" width="22px" height="22px" alt="Share on Facebook">
</a>
Replace https%3A%2F%2Fparse.com, YOUR_FB_CSS_STYLING_CLASS and YOUR_FB_ICON_IMAGE.png with your own choices and you should be ok.
Note: For the sake of your users' security use the HTTPS link to FB, like in the a's href attribute.
Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below
public class DynamicArray {
static int []increaseSizeOfArray(int []arr){
int []brr=new int[(arr.length*2)];
for (int i = 0; i < arr.length; i++) {
brr[i]=arr[i];
}
return brr;
}
public static void main(String[] args) {
int []arr=new int[5];
for (int i = 0; i < 11; i++) {
if (i<arr.length) {
arr[i]=i+100;
}
else {
arr=increaseSizeOfArray(arr);
arr[i]=i+100;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println("arr="+arr[i]);
}
}
}
Source : How to make dynamic array
In my case, I tried unlocking the file with tf lock
but was told I couldn't because the stale workspace on an old computer that no longer existed was a local workspace. I then tried deleting the workspace with tf workspace /delete
, but deleting the workspace did not remove the lock (and then I couldn't try to unlock it again because I just got an error saying the workspace no longer existed).
I ended up tf destroy
ing the file and checking it in again, which was pretty silly and had the undesirable effect of removing\ it from previous changesets, but at least got us working again. It wasn't that big a deal in this case since the file had never been changed since being checked in.
Direct quote from MSDN: <xsd:import> Element, Remarks section
The difference between the include element and the import element is that import element allows references to schema components from schema documents with different target namespaces and the include element adds the schema components from other schema documents that have the same target namespace (or no specified target namespace) to the containing schema. In short, the import element allows you to use schema components from any schema; the include element allows you to add all the components of an included schema to the containing schema.
Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize()
allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize()
.
If you are familiar with json_encode()
and json_decode()
(and JSON in general), the concept is similar.
try this:
Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
I think I have a way where you may not get exactly get what you want, but you can integrate Morgan's logging with log4js -- in other words, all your logging activity can go to the same place. I hope this digest from an Express server is more or less self-explanatory:
var express = require("express");
var log4js = require("log4js");
var morgan = require("morgan");
...
var theAppLog = log4js.getLogger();
var theHTTPLog = morgan({
"format": "default",
"stream": {
write: function(str) { theAppLog.debug(str); }
}
});
....
var theServer = express();
theServer.use(theHTTPLog);
Now you can write whatever you want to theAppLog and Morgan will write what it wants to the same place, using the same appenders etc etc. Of course, you can call info() or whatever you like in the stream wrapper instead of debug() -- that just reflects the logging level you want to give to Morgan's req/res logging.
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
"Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible.
In IFrame:
parent.closeIFrame();
In parent:
function closeIFrame(){
$('#youriframeid').remove();
}
I added a mMap.setOnMarkerClickListener(this);
in the onMapReady(GoogleMap googleMap)
method. So every time you click a marker it displays the text name in the toast method.
public class DemoMapActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
double lat=0.34924212701428;
double lng=32.616554024713;
String venue = "Capital Shoppers City";
LatLng location = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(location).title(venue)).setTag(0);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(location);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
mMap.moveCamera(cameraUpdate);
mMap.animateCamera(zoom);
mMap.setOnMarkerClickListener(this);
}
@Override
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
Integer clickCount = (Integer) marker.getTag();
// Check if a click count was set, then display the click count.
if (clickCount != null) {
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" has been clicked ",
Toast.LENGTH_SHORT).show();
}
// Return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
}
You can check this link for reference Markers
I think that this code is going to help:
JS:
$('#foo').ready(function () {
$('#loadingMessage').css('display', 'none');
});
$('#foo').load(function () {
$('#loadingMessage').css('display', 'none');
});
HTML:
<iframe src="http://google.com/" id="foo"></iframe>
<div id="loadingMessage">Loading...</div>
CSS:
#loadingMessage {
width: 100%;
height: 100%;
z-index: 1000;
background: #ccc;
top: 0px;
left: 0px;
position: absolute;
}
I have tried all of the above solutions (which all bring valid points), but nothing was working for me.
Until I found that my MySQL table field mappings in C# was using an incorrect type: MySqlDbType.Blob . I changed it to MySqlDbType.Text and now I can write all the UTF8 symbols I want!
p.s. My MySQL table field is of the "LongText" type. However, when I autogenerated the field mappings using MyGeneration software, it automatically set the field type as MySqlDbType.Blob in C#.
Interestingly, I have been using the MySqlDbType.Blob type with UTF8 characters for many months with no trouble, until one day I tried writing a string with some specific characters in it.
Hope this helps someone who is struggling to find a reason for the error.
You can simply add another join like this:
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
However be aware that, because it is an INNER JOIN
, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN
which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
LEFT OUTER JOIN images
ON dashboard_messages.image_id = images.image_id
Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:
<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
alert(document.getElementById('test').search); //bar
alert(document.getElementById('test').hash); //quz
</script>
Or
<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>
Should you need this on a regular string variable and happen to have jQuery around, this should work:
var mylink = "foo.html?bar#quz";
if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
// do stuff
}
(but its maybe a bit overdone .. )