You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
happens also when you use a dependency without installing it. happen to me when i called MenuIcon from '@material-ui/icons/' when was missing in the project.
What we ended up doing is stopped using the class components and created Functional Components, using useEffect()
from the Hooks API for lifecycle methods. This allows you to still use makeStyles()
with Lifecycle Methods without adding the complication of making Higher-Order Components. Which is much simpler.
Example:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';
import { Container, makeStyles } from '@material-ui/core';
import LogoButtonCard from '../molecules/Cards/LogoButtonCard';
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
margin: theme.spacing(1)
},
highlight: {
backgroundColor: 'red',
}
}));
// Highlight is a bool
const Welcome = ({highlight}) => {
const [userName, setUserName] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(true);
const classes = useStyles();
useEffect(() => {
axios.get('example.com/api/username/12')
.then(res => setUserName(res.userName));
}, []);
if (!isAuthenticated()) {
return <Redirect to="/" />;
}
return (
<Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
<LogoButtonCard
buttonText="Enter"
headerText={isAuthenticated && `Welcome, ${userName}`}
buttonAction={login}
/>
</Container>
);
}
}
export default Welcome;
import React, { useState } from "react"
const inputTextValue = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: (e) => { setValue(e.target.value) }
};
};
export default () => {
const textValue = inputTextValue("");
return (<>
<input {...textValue} />
</>
);
}
/*"Solution I Tired Changed Name of Funtion in Captial "*/
import React, { useState } from "react"
const InputTextValue = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: (e) => { setValue(e.target.value) }
};
};
export default () => {
const textValue = InputTextValue("");
return (<>
<input {...textValue} />
</>
);
}
If above solutions dont work, try this and it works for me:
componentWillUnmount() {
// fix Warning: Can't perform a React state update on an unmounted component
this.setState = (state,callback)=>{
return;
};
}
I am using git+vscode+windows+vue, and after read the eslint document: https://eslint.org/docs/rules/linebreak-style
Finally fix it by:
add *.js text eol=lf
to .gitattributes
then run vue-cli-service lint --fix
If you prefer a useEffect
replacement approach:
const usePreviousEffect = (fn, inputs = []) => {
const previousInputsRef = useRef([...inputs])
useEffect(() => {
fn(previousInputsRef.current)
previousInputsRef.current = [...inputs]
}, inputs)
}
And use it like this:
usePreviousEffect(
([prevReceiveAmount, prevSendAmount]) => {
if (prevReceiveAmount !== receiveAmount) // side effect here
if (prevSendAmount !== sendAmount) // side effect here
},
[receiveAmount, sendAmount]
)
Note that the first time the effect executes, the previous values passed to your fn
will be the same as your initial input values. This would only matter to you if you wanted to do something when a value did not change.
This is just a warning and it will probably be fixed before 2019 with plugin updates so don't worry about it. I would recommend you to use compatible versions of your plugins and gradle.
You can check your plugin version and gradle version here for better experience and performance.
https://developer.android.com/studio/releases/gradle-plugin
Try using the stable versions for a smooth and warning/error free code.
Try this. I think this will help you.
override fun onBackPressed() {
when (mNavController.getCurrentDestination()!!.getId()) {
R.id.loginFragment -> {
onWarningAlertDialog(this, "Alert", "Do you want to close this application ?")
}
R.id.registerFragment -> {
super.onBackPressed()
}
}
}
private fun onWarningAlertDialog(mainActivity: MainActivity, s: String, s1: String) {
val dialogBuilder = AlertDialog.Builder(this)
dialogBuilder.setMessage(/*""*/s1)
.setCancelable(false)
.setPositiveButton("Proceed", DialogInterface.OnClickListener { dialog, id ->
finish()
})
.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, id ->
dialog.cancel()
})
// create dialog box
val alert = dialogBuilder.create()
// set title for alert dialog box
alert.setTitle("AlertDialogExample")
// show alert dialog
alert.show()
}
if you want to solve this problem without migrating to AndroidX (I don't recommend it)
this manifest merger issue is related to one of your dependency using androidX.
you need to decrease this dependency's release version. for my case :
I was using google or firebase
api 'com.google.android.gms:play-services-base:17.1.0'
I have to decrease it 15.0.1 to use in support library.
What actually was missing for me and what made it work then was downloading'Google Play services' and 'Google Repository'
Go to: Settings -> Android SDK -> SDK Tools -> check/install Google Play services + repository
Hope it helps.
Simple solution
Hit below commend only to fix this error
npm install --save-dev @angular-devkit/build-angular
It might be cause of a library, I faced it because of Glide.
It was
implementation 'com.github.bumptech.glide:glide:4.7.1'
So I added exclude group: "com.android.support"
And it becomes
implementation ('com.github.bumptech.glide:glide:4.7.1') {
exclude group: "com.android.support"
}
What worked for me was setting up the .prettierrc.json
config file. Put it to the root of your project with a sample config like this:
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 2,
"semi": true,
"arrowParens": "always"
}
After triggering the Format Document command, all works just as expected.
Side note: What comes as a bonus with this solution is that each team member gets the same formatting outputs thanks to the present config file.
In build:app
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.proyecto.marketdillo"
minSdkVersion 14
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0-rc02'
implementation 'com.android.support:design:28.0.0-rc02'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-firestore:17.1.5'
implementation 'com.android.support:multidex:1.0.3'
}
apply plugin: 'com.google.gms.google-services'
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.
well got this answer from another site and don't want to take any credit for this but this solution works like butter.
Go to File\Settings\Gradle. Deselect the "Offline work" box. Now you can connect and download any necessary or missing dependencies.
I was also facing similar issue by doing below changes, it worked for me
In app.modules.ts
import {HttpClientModule} from '@angular/common/http'
and in corresponding service class
import { HttpClient } from '@angular/common/http'
constructor should look like as below
constructor(private http: HttpClient, private xyz: xyzService) {}
In test file
import { HttpClientTestingModule } from '@angular/common/http/testing'
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
}));
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
When the version of Android Studio is 3.0.1, Gradle Version is 4.1 and Android PluginVersion is 3.0.0, it will encounter this problem. Then I downgrade Gradle Version is 3.3, Android Android is zero, there is no such problem.
I find out the reason of this problem for my project. I was added one dependency twice in build.gradle. One time by adding dependency and one time again by adding jar dependency:
compile 'org.achartengine:achartengine:1.2.0'
...
implementation files('../achartengine-1.2.0.jar')
after remove the first line problem solved.
On line 10 there's a space between s
and t
. It should be one word: stylesheet
.
In my case, I deleted src/registerServiceWorker file from create-react-app generated app. I added it and now it's all working.
Adding the below content in the main gradle has solved the problem for me:
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
flatDir {
dirs 'libs'
}
}
I had similar problem on windows, however sometimes eslint worked (in vscode) sometimes not. Later I realized that it works fine after a while. It was related to this issue: eslint server takes ~3-5 minutes until available
Setting enviroment variable NO_UPDATE_NOTIFIER=1
solved the problem
I had the same error, what solve my problem was. In my library instead of using compile or implementation i use "api". So in the end my dependencies:
dependencies {
api fileTree(dir: 'libs', include: ['*.jar'])
api files('libs/model.jar')
testApi 'junit:junit:4.12'
api 'com.android.support:percent:26.0.0-beta2'
api 'com.android.support:appcompat-v7:26.0.0-beta2'
api 'com.android.support:support-core-utils:26.0.0-beta2'
api 'com.squareup.retrofit2:retrofit:2.0.2'
api 'com.squareup.picasso:picasso:2.4.0'
api 'com.squareup.retrofit2:converter-gson:2.0.2'
api 'com.squareup.okhttp3:logging-interceptor:3.2.0'
api 'uk.co.chrisjenx:calligraphy:2.2.0'
api 'com.google.code.gson:gson:2.2.4'
api 'com.android.support:design:26.0.0-beta2'
api 'com.github.PhilJay:MPAndroidChart:v3.0.1'
}
You can find more info about "api", "implementation" in this link https://stackoverflow.com/a/44493379/3479489
Solution One: You can use new react HOOKS API. Currently in React v16.8.0
Hooks let you use more of React’s features without classes. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. Hooks solves all the problems addressed with Recompose.
A Note from the Author of recompose
(acdlite, Oct 25 2018):
Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today, we announced a proposal for Hooks. Hooks solves all the problems I attempted to address with Recompose three years ago, and more on top of that. I will be discontinuing active maintenance of this package (excluding perhaps bugfixes or patches for compatibility with future React releases), and recommending that people use Hooks instead. Your existing code with Recompose will still work, just don't expect any new features.
Solution Two:
If you are using react version that does not support hooks, no worries, use recompose
(A React utility belt for function components and higher-order components.) instead. You can use recompose
for attaching lifecycle hooks, state, handlers etc
to a function component.
Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).
// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33
function RenderlessComponent() {
return null;
}
export default lifecycle({
componentDidMount() {
const { checkIfAuthed } = this.props;
// Do they have an active session? ("Remember me")
checkIfAuthed();
},
componentWillReceiveProps(nextProps) {
const {
loadUser,
} = this.props;
// Various 'indicators'..
const becameAuthed = (!(this.props.auth) && nextProps.auth);
const isCurrentUser = (this.props.currentUser !== null);
if (becameAuthed) {
loadUser(nextProps.auth.uid);
}
const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
if (shouldSetCurrentUser) {
const currentUser = nextProps.users[nextProps.auth.uid];
if (currentUser) {
this.props.setCurrentUser({
'id': nextProps.auth.uid,
...currentUser,
});
}
}
}
})(RenderlessComponent);
Have you added the google maven endpoint?
Important: The support libraries are now available through Google's Maven repository. You do not need to download the support repository from the SDK Manager. For more information, see Support Library Setup.
Add the endpoint to your build.gradle file:
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
}
Which can be replaced by the shortcut google()
since Android Gradle v3:
allprojects {
repositories {
jcenter()
google()
}
}
If you already have any maven url inside repositories
, you can add the reference after them, i.e.:
allprojects {
repositories {
jcenter()
maven {
url 'https://jitpack.io'
}
maven {
url 'https://maven.google.com'
}
}
}
Try to remove multidex from default config and check the build error log. If that log is some relatable with INotification class. Use this in android{}
configurations {
all*.exclude group: 'com.android.support', module: 'support-v4'
}
This helps me.
I have met the similar problem.
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring project ':app'.
> Failed to notify project evaluation listener.
> org.gradle.api.tasks.compile.CompileOptions.setBootClasspath(Ljava/lang/String;)V
* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.0-milestone-1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 7s
Build step 'Invoke Gradle script' changed build result to FAILURE
Build step 'Invoke Gradle script' marked build as failure
Finished: FAILURE
The key is you need to get a way to solve this kind of problems,not to solve this problem.
According to the log above,the most important information is:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output. Run with --scan to get full insights.
Most of the building problems of Gradle will be solved because when you use the specific Gradle build command,you can get more detailed and useful information that are clear.
*clean project
./gradlew clean
*build project
./gradlew build
*build for debug package
./gradlew assembleDebug or ./gradlew aD
*build for release package
./gradlew assembleRelease or ./gradlew aR
*build for release package and install
./gradlew installRelease or ./gradlew iR Release
*build for debug package and install
./gradlew installDebug or ./gradlew iD Debug
*uninstall release package
./gradlew uninstallRelease or ./gradlew uR
*uninstall debug package
./gradlew uninstallDebug or ./gradlew uD
*all the above command + "--info" or "--debug" or "--scan" or "--stacktrace" can get more detail information.
And then I found the problem is related with the version of Gradle,when I have changed Gradle from 5.0 to 4.1,and then it's OK.
On Mac :
go to Android Studio > Preferences > Build, Execution, Deployment > Compiler
On Windows :
go to File > Settings > > Build, Execution, Deployment > Compiler
Now, in the Command-line Options field , add following three flags :
--stacktrace --info --scan
like shown below
Now , open the Build window from the bottom of Android studio
Then, there is a button on the left side of the Build window:
press this button , you will see detailed logs with exact code that is preventing the project from compiling
getting following error
It happens: Error:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:
_x000D_
The problem occurs because webpack-dev-server
2.4.4 adds a host check. You can disable it by adding this to your webpack config:
devServer: {
compress: true,
disableHostCheck: true, // That solved it
}
EDIT: Please note, this fix is insecure.
Please see the following answer for a secure solution: https://stackoverflow.com/a/43621275/5425585
@ts-expect-error
TS 3.9 introduces a new magic comment. @ts-expect-error
will:
@ts-ignore
if (false) {
// @ts-expect-error: Let's ignore a single compiler error like this unreachable code
console.log("hello"); // compiles
}
// If @ts-expect-error didn't suppress anything at all, we now get a nice warning
let flag = true;
// ...
if (flag) {
// @ts-expect-error
// ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
console.log("hello");
}
@ts-ignore
and @ts-expect-error
can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:
? Use any
type
// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;
// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;
? Augment JQueryStatic
interface
// ./global.d.ts
interface JQueryStatic {
summernote: any;
}
// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works
In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js
and use --allowJs
with checkJs: false
.
npm install font-awesome --save
add ~/ before path
@import "~/font-awesome/scss/font-awesome.scss";
I recently had this problem.
<Text style={styles.textRegister}> -------- Register With --------</Text>
with this result:
Make sure you are using default gradle wrapper in Open File > Settings > Build,Execution,Deployment > Build Tools > Gradle.
For anyone building an ionic app and trying to upload it. Make sure you added at least one platform to the app. Otherwise you will get this error.
Most of the times when I face this issue. I remove replace https
with http
. It solves the issue.
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null
or undefined
here, so don't complain about the possibility of it being null
or undefined
." Sometimes the type checker is unable to make that determination itself.
It is explained here:
A new
!
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operationx!
produces a value of the type ofx
withnull
andundefined
excluded. Similar to type assertions of the forms<T>x
andx as T
, the!
non-null assertion operator is simply removed in the emitted JavaScript code.
I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
To ignore some folder from eslint rules we could create the file .eslintignore
in root directory and add there the path to the folder we want omit (the same way as for .gitignore
).
Here is the example from the ESLint docs on Ignoring Files and Directories:
# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default
# Ignore built files except build/index.js
build/*
!build/index.js
Solution for me (Android Studio) :
1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure
2) and increase the level of SDK "Compile SDK Version".
Try the below steps:
npm uninstall webpack --save-dev
followed by
npm install [email protected] --save-dev
Then you should be able to gulp again. Fixed the issue for me.
Two suggestions:
std::deque
instead of std::vector
for better performance in your specific case and use the method std::deque::pop_front()
.&
in std::vector<ScanRule>& topPriorityRules;
I think this is an even simpler example
List<String> emptyList = new ArrayList<>();
Optional<String> opt2 = emptyList.stream().findFirst();
assertThrows(NoSuchElementException.class, () -> opt2.get());
Calling get()
on an optional containing an empty ArrayList
will throw a NoSuchElementException
. assertThrows
declares the expected exception and provides a lambda supplier (takes no arguments and returns a value).
Thanks to @prime for his answer which I hopefully elaborated on.
Add classpath com.google.gms:google-services:3.0.0
dependencies at project level build.gradle
Refer the sample block from project level build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
This is a bit late for those coming in, but check your proguard rules! I wasted a lot of time on this. Your proguard rules could be changing the names to important firebase files. This really only proves a problem in production and instant run :)
proguard-rules.pro
-keep class com.google.firebase.** { *; }
-keep class com.firebase.** { *; }
-keep class org.apache.** { *; }
-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }
-dontwarn org.apache.**
-dontwarn org.w3c.dom.**
So now assume the Customer wants to change his name in the webui - then there will be some controller action, where there will be the updated DTO with the old ID and the new name.
Normally, you have the following workflow:
P.S. This operation will inevitably issue 2 queries: select and update. Again, 2 queries, even if you wanna update a single field. However, if you utilize Hibernate's proprietary @DynamicUpdate annotation on top of entity class, it will help you not to include into update statement all the fields, but only those that actually changed.
P.S. If you do not wanna pay for first select statement and prefer to use Spring Data's @Modifying query, be prepared to lose L2C cache region related to modifiable entity; even worse situation with native update queries (see this thread) and also of course be prepared to write those queries manually, test them and support them in the future.
add plt.figure(figsize=(16,5))
before the sns.heatmap and play around with the figsize numbers till you get the desired size
...
plt.figure(figsize = (16,5))
ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)
I know this answer is ridiculous, but consider just disabling this rule until the bugs are worked out or you've upgraded your tooling:
/* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling
Or disable project-wide in your eslintrc:
"rules": {
"react/prop-types": "off"
}
Another way would be to catch the exeption:
def is_nat(npdatetime):
try:
npdatetime.strftime('%x')
return False
except:
return True
add and remove text input element dynamically any one can use this this will work Type of Contact Balance Fund Equity Fund Allocation Allocation % is required! Remove Add Contact
userForm: FormGroup;
public contactList: FormArray;
// returns all form groups under contacts
get contactFormGroup() {
return this.userForm.get('funds') as FormArray;
}
ngOnInit() {
this.submitUser();
}
constructor(public fb: FormBuilder,private router: Router,private ngZone: NgZone,private userApi: ApiService) { }
// contact formgroup
createContact(): FormGroup {
return this.fb.group({
fundName: ['', Validators.compose([Validators.required])], // i.e Email, Phone
allocation: [null, Validators.compose([Validators.required])]
});
}
// triggered to change validation of value field type
changedFieldType(index) {
let validators = null;
validators = Validators.compose([
Validators.required,
Validators.pattern(new RegExp('^\\+[0-9]?()[0-9](\\d[0-9]{9})$')) // pattern for validating international phone number
]);
this.getContactsFormGroup(index).controls['allocation'].setValidators(
validators
);
this.getContactsFormGroup(index).controls['allocation'].updateValueAndValidity();
}
// get the formgroup under contacts form array
getContactsFormGroup(index): FormGroup {
// this.contactList = this.form.get('contacts') as FormArray;
const formGroup = this.contactList.controls[index] as FormGroup;
return formGroup;
}
submitUser() {
this.userForm = this.fb.group({
first_name: ['', [Validators.required]],
last_name: [''],
email: ['', [Validators.required]],
company_name: ['', [Validators.required]],
license_start_date: ['', [Validators.required]],
license_end_date: ['', [Validators.required]],
gender: ['Male'],
funds: this.fb.array([this.createContact()])
})
this.contactList = this.userForm.get('funds') as FormArray;
}
addContact() {
this.contactList.push(this.createContact());
}
removeContact(index) {
this.contactList.removeAt(index);
}
Here is the only CSS solution to fix this. Use the below css.
.row-fluid {
display: table;
}
.row-fluid .span6 {
display: table-cell;
vertical-align: top;
}
.vc_single_image-wrapper {
position: relative;
}
.vc_single_image-wrapper .image-wrapper {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-size: cover;
background-repeat: no-repeat;
background-position: 50% 50%;
}
HTML from the OP:
<div class="vc_single_image-wrapper vc_box_border_grey">
<div class="image-wrapper" style="background-image: url(http://i0.wp.com/www.homedecor.nl/wp-content/uploads/2016/03/Gordijnen-Home-Decor-2.jpg?fit=952%2C480;"></div>
</div>
try this, it should work. also remove float from .row-fluid .span6
Another way is to open Visual Studio Code from a terminal with the virtualenv set and need to perform F1 Python: Select Interpreter
and select the required virtualenv.
I have been struggling with this problem for 2 days. And tried all options. Finally noticed that after updating my android studio, it was not showing me the compile errors like @v.d. wrote above. My problem was, In my build files, I was using compile(which should be replaced with implementation or api) and testcompile(which also replaced by testimplementation). Notice that I have changed in whole build files(android, app and others - in my case I also had folding-cell library)
for example instead of this
compile project(path: ':folding-cell')
write this
implementation project(path: ':folding-cell')
Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.
I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up
My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:
in resources/lang/en/validaton.php:
'uploaded' => 'The :attribute failed to upload.',
And this is the message displayed when the file is larger than the limit set by PHP.
I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.
However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.
So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.
Here is what works if the file to smaller than the PHP file size limit:
In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:
This is how I set a custom error message and maximum file size:
I have an input field <input type="file" name="upload">
. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
...
...
public function rules() {
return [
'upload' => 'required|file|max:8192',
];
}
public function messages()
{
return [
'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
];
}
}
Go to database, next to title there are 2 options:
Cloud Firestore, Realtime database
Select Realtime database and go to rules
Change rules to true.
The reason why this happen is that diff dependency use same lib of diff version.
So, there are 3 steps or (1 step) to solve this problem.
Add
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:2.0.1'
}
to your build.gradle
file in android {...}
Open terminal in android studio
run ./gradlew -q app:dependencies
command.
Click Clean Project
from menu bar of android studio in Build
list.
It will rebuild the project, and then
remove
code in 1st step.
Maybe you need just exec 2nd step. I can't rollback when error occurs. Have a try.
Feb 25th 2021:
For me, after over 8 hours of trials and errors, it was the re-ordering of the repositories
sources in the project-level build.gradle
file that solved the issue for me. So, instead of:
buildscript {
...
repositories {
google()
mavenCentral()
maven { url "https://plugins.gradle.org/m2/" }
}
...
}
I moved google()
to the bottom:
buildscript {
...
repositories {
mavenCentral()
maven { url "https://plugins.gradle.org/m2/" }
google()
}
...
}
Of course, be sure to update the gradle android plugin and the matching gradle-wrapper distribution versions too.
To return true or false depending on whether a checkbox is checked or not, I use this in JQuery
let checkState = $("#checkboxId").is(":checked") ? "true" : "false";
For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html
Then you should edit your mysqld.cnf
file, for instance :
vim /etc/mysql/mysql.conf.d/mysqld.cnf
Then, add in the [mysqld] part, the following :
plugin-load-add=validate_password.so
validate_password_policy=LOW
Basically, if you edit your default, it will looks like :
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW
Then, you can restart:
systemctl restart mysql
If you forget the plugin-load-add=validate_password.so
part, you will it an error at restart.
Enjoy !
You can't use float
inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle
.
So if you want to position child
element to right of parent
element you can use margin-left: auto
but now child
element will also push other div
to the right as you can see here Fiddle
.
What you can do now is change order of elements and set order: 2
on child
element so it doesn't affect second div
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
margin-left: auto;_x000D_
order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">Ignore parent?</div>_x000D_
<div>another child</div>_x000D_
</div>
_x000D_
open key.properties and check your path is correct. (replace from \ to /)
example:-
replace from "storeFile=D:\Projects\Flutter\Key\key.jks" to "storeFile=D:/Projects/Flutter/Key/key.jks"
Unexpected token errors in ESLint parsing occur due to incompatibility between your development environment and ESLint's current parsing capabilities with the ongoing changes with JavaScripts ES6~7.
Adding the "parserOptions" property to your .eslintrc is no longer enough for particular situations, such as using
static contextTypes = { ... } /* react */
in ES6 classes as ESLint is currently unable to parse it on its own. This particular situation will throw an error of:
error Parsing error: Unexpected token =
The solution is to have ESLint parsed by a compatible parser. babel-eslint is a package that saved me recently after reading this page and i decided to add this as an alternative solution for anyone coming later.
just add:
"parser": "babel-eslint"
to your .eslintrc
file and run npm install babel-eslint --save-dev
or yarn add -D babel-eslint
.
Please note that as the new Context API starting from React ^16.3
has some important changes, please refer to the official guide.
np.isnan
can be applied to NumPy arrays of native dtype (such as np.float64):
In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)
but raises TypeError when applied to object arrays:
In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Since you have Pandas, you could use pd.isnull
instead -- it can accept NumPy arrays of object or native dtypes:
In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)
In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)
Note that None
is also considered a null value in object arrays.
This worked for me.
wrap the cards inside
<div class="card-group"></div>
or
<div class="card-deck"></div>
The following hack works:
xmlns:tools="http://schemas.android.com/tools"
line in the
manifest tag tools:replace="android:icon,android:theme,android:allowBackup,label,name"
in the application tagStopping OpenSdk Java process (inner to Android Studio process) worked.
I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install
. When I changed to the directory that had my makefile it worked.
So possibly you aren't in the right directory.
Replace:
ActivityCompat.requestPermissions(this, new String[]{"Manifest.permission.READ_PHONE_STATE"}, 225);
with:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 225);
The actual string for that permission is not "Manifest.permission.READ_PHONE_STATE"
. Use the symbol Manifest.permission.READ_PHONE_STATE
.
This is short, yet efficient and proven approach:
location ~ (patternOne|patternTwo){ #rules etc. }
So one can easily have multiple patterns with simple pipe syntax pointing to the same location block / rules.
The simple solution is download and extract the following file which contains mips64el-linux-android-4.9 and mipsel-linux-android-4.9 folders,to your toolchains folder inside sdk "android-sdk\ndk-bundle\toolchains".
your model just have getter and setter in androidX. else not find your model in view and show this bug
public class User {
String name;
public String getName() {
return name;
}
public User(String name) {
this.name = name;
}
}
You can turn off specific rule for a file by using /*eslint [<rule: "off"], >]*/
/* eslint no-console: "off", no-mixed-operators: "off" */
Version: [email protected]
For fixing:
No matching client found for package name 'com.example.exampleapp:
You should get a valid google-service.json
file for your package from here
For fixing:
Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 8.3.0.:
You should move apply plugin: 'com.google.gms.google-services'
to the end of your app gradle.build
file. Something like this:
dependencies {
...
}
apply plugin: 'com.google.gms.google-services'
SOLVED
After banging my head on the wall for a couple days with this issue, it was looking like the problem had something to do with the content type negotiation between the client and server. I dug deeper into that using Fiddler to check the request details coming from the client app, here's a screenshot of the raw request as captured by fiddler:
What's obviously missing there is the Content-Type
header, even though I was setting it as seen in the code sample in my original post. I thought it was strange that the Content-Type
never came through even though I was setting it, so I had another look at my other (working) code calling a different Web API service, the only difference was that I happened to be setting the req.ContentType
property prior to writing to the request body in that case. I made that change to this new code and that did it, the Content-Type
was now showing up and I got the expected success response from the web service. The new code from my .NET client now looks like this:
req.Method = "POST"
req.ContentType = "application/json"
lstrPagingJSON = JsonSerializer(Of Paging)(lPaging)
bytData = Encoding.UTF8.GetBytes(lstrPagingJSON)
req.ContentLength = bytData.Length
reqStream = req.GetRequestStream()
reqStream.Write(bytData, 0, bytData.Length)
reqStream.Close()
'// Content-Type was being set here, causing the problem
'req.ContentType = "application/json"
That's all it was, the ContentType
property just needed to be set prior to writing to the request body
I believe this behavior is because once content is written to the body it is streamed to the service endpoint being called, any other attributes pertaining to the request need to be set prior to that. Please correct me if I'm wrong or if this needs more detail.
I had the same issue a few days ago and I found this thread Twitter Developer Forum that points to some incompatibility with versions of gradle/build-tools/crashalics.
My problem was slightly different from yours as I'm not using alpha-3
I'm using 1.5
. But on my update I also changed to the latest gradle distribution gradle-2.9-all.zip
.
So probably/maybe you can fix it by changing to the latest gradle version. But If it does not work, you'll really have to be patient and wait until build tools V2.0
is not in alpha anymore OR the Crashalitycs team, fix the incompatibility.
in my vue
project i fixed this problem like this :
vim package.json
...
"rules": {
"no-console": "off"
},
...
ps : package.json is a configfile in the vue project dir, finally the content shown like this:
{
"name": "metadata-front",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.18.0",
"vue": "^2.5.17",
"vue-router": "^3.0.2"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^3.0.4",
"@vue/cli-plugin-eslint": "^3.0.4",
"@vue/cli-service": "^3.0.4",
"babel-eslint": "^10.0.1",
"eslint": "^5.8.0",
"eslint-plugin-vue": "^5.0.0-0",
"vue-template-compiler": "^2.5.17"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"rules": {
"no-console": "off"
},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
If you want to set specific learning rates for intervals of epochs like 0 < a < b < c < ...
. Then you can define your learning rate as a conditional tensor, conditional on the global step, and feed this as normal to the optimiser.
You could achieve this with a bunch of nested tf.cond
statements, but its easier to build the tensor recursively:
def make_learning_rate_tensor(reduction_steps, learning_rates, global_step):
assert len(reduction_steps) + 1 == len(learning_rates)
if len(reduction_steps) == 1:
return tf.cond(
global_step < reduction_steps[0],
lambda: learning_rates[0],
lambda: learning_rates[1]
)
else:
return tf.cond(
global_step < reduction_steps[0],
lambda: learning_rates[0],
lambda: make_learning_rate_tensor(
reduction_steps[1:],
learning_rates[1:],
global_step,)
)
Then to use it you need to know how many training steps there are in a single epoch, so that we can use the global step to switch at the right time, and finally define the epochs and learning rates you want. So if I want the learning rates [0.1, 0.01, 0.001, 0.0001]
during the epoch intervals of [0, 19], [20, 59], [60, 99], [100, \infty]
respectively, I would do:
global_step = tf.train.get_or_create_global_step()
learning_rates = [0.1, 0.01, 0.001, 0.0001]
steps_per_epoch = 225
epochs_to_switch_at = [20, 60, 100]
epochs_to_switch_at = [x*steps_per_epoch for x in epochs_to_switch_at ]
learning_rate = make_learning_rate_tensor(epochs_to_switch_at , learning_rates, global_step)
My response is a little bit old but for my the only solution was adding multiDexEnabled option in defaultConfig like this:
android{
...
defaultConfig{
...
multiDexEnabled true
}
}
If this does not work for you try adding this piece of code:
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '26.1.0'
}
}
}
}
My error was related to a problem with different libraries versions and this made the trick.
I hope this can help somebody :)
Also please check your package name in Manifest and package name in google services json file. If both have package name differ from one another u will have this issue.
The problem is caused because the code you are running was created in an older API level, And your present SDK Manager doesn't support running them. So do try the following; 1.Install the SDK Manager that support API level 23. Go to >SDK Manager, >Android SDK , then select API 23 and install. 2.second alternative is to update your build.grade app module to change compileSdkVersion,compile,and other numbers to your currently supported API level.
Note:please ensure to check the API and Revision numbers and change them exactly. otherwise Your project won't synchronize
If all the above didn't work for you try removing cache from .gradle
global folder
rm -rf ~/.gradle/caches
react-native run-android
rm -rf ~/.gradle
react-native run-android
In my case, I added below code in dependencies of app level build.gradle
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
After that, I clean the project and rebuild.My problem solved.
AndroidStudio Menu:
Build/Clean Project
Update old dependencies
HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')
If you need sdk 23, add this to your gradle:
In dependencies add:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
and also add this
android {
useLibrary 'org.apache.http.legacy'
}
if you faced this problem you can completely resolve it by changing :
build.gradle(project: ...)
replace this
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Latest published version of the Support Library is 24.1.1, So you can use it like this,
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
Same as for other support components.
You can see the revisions here,
https://developer.android.com/topic/libraries/support-library/revisions.html
Add this in the WordPress' .htaccess file:
RewriteCond %{HTTP_HOST} ^yoursite.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.yoursite.com [NC]
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [L,R=301,NC]
Therefore the default WordPress' .htaccess file should look like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP_HOST} ^yoursite.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.yoursite.com [NC]
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [L,R=301,NC]
</IfModule>
You can also set the test env in your test file as follows:
/* eslint-env jest */
describe(() => {
/* ... */
})
I have a similar issue with a share Host. I was having 500 error. I just fixed by checking the Laravel version and PHP version. The error was because Laravel 5.6 doesn't run on PHP 7.0.x Once I know this I just reconfigure the project to Laravel 5.5 that is compatible with PHP 7.0.x now everything is right. Another reason I have issues sometimes is the FTP I get corrupted Files and have to upload the project more than once. Hope this help in the future I don't found so many information in this topic.
I have had a similar scenario in Laravel and solved it in the following way.
The password contains characters from at least three of the following five categories:
First, we need to create a regular expression and validate it.
Your regular expression would look like this:
^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$
I have tested and validated it on this site. Yet, perform your own in your own manner and adjust accordingly. This is only an example of regex, you can manipluated the way you want.
So your final Laravel code should be like this:
'password' => 'required|
min:6|
regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/|
confirmed',
Update As @NikK in the comment mentions, in Laravel 5.5 and newer the the password value should encapsulated in array Square brackets like
'password' => ['required',
'min:6',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/',
'confirmed']
I have not testing it on Laravel 5.5 so I am trusting @NikK hence I have moved to working with c#/.net these days and have no much time for Laravel.
Note:
Some online references
Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:
For some projects it's easier to set your target to es6
in your tsconfig.json
.
{
"compilerOptions": {
"target": "es6",
...
The fundamental way to think about this subject is as follows:
A URI is a resource identifier that uniquely identifies a specific instance of a resource TYPE. Like everything else in life, every object (which is an instance of some type), have set of attributes that are either time-invariant or temporal.
In the example above, a car is a very tangible object that has attributes like make, model and VIN - that never changes, and color, suspension etc. that may change over time. So if we encode the URI with attributes that may change over time (temporal), we may end up with multiple URIs for the same object:
GET /cars/honda/civic/coupe/{vin}/{color=red}
And years later, if the color of this very same car is changed to black:
GET /cars/honda/civic/coupe/{vin}/{color=black}
Note that the car instance itself (the object) has not changed - it's just the color that changed. Having multiple URIs pointing to the same object instance will force you to create multiple URI handlers - this is not an efficient design, and is of course not intuitive.
Therefore, the URI should only consist of parts that will never change and will continue to uniquely identify that resource throughout its lifetime. Everything that may change should be reserved for query parameters, as such:
GET /cars/honda/civic/coupe/{vin}?color={black}
Bottom line - think polymorphism.
You can easily enable debugging support using an option for the @EnableWebSecurity
annotation:
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
…
}
I was importing an Android application in Android Studio (Gradle version 2.10) from Eclipse. The drawable images are not supported, then manually remove those images and paste some PNG images.
And also update the Android drawable importer from the Android repository. Then clean and rebuild the application, and then it works.
I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:
Make sure ESLint is not run with the --no-inline-config
flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):
/* eslint-env browser */
This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.
There are plenty of environments, and you can declare more than one at the same time, for example, in-line:
/* eslint-env browser, node */
If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.
From their docs:
An environment defines global variables that are predefined. The available environments are:
browser
- browser global variables.node
- Node.js global variables and Node.js scoping.commonjs
- CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).shared-node-browser
- Globals common to both Node and Browser.[...]
Besides environments, you can make it ignore anything you want. If it warns you about using console.log()
but you don't want to be warned about it, just inline:
/* eslint-disable no-console */
You can see the list of all rules, including recommended rules to have for best coding practices.
In v1.43 is the ability to separately color the vertical rulers.
See issue Support multiple rulers with different colors - (in settings.json):
"editor.rulers": [
{
"column": 80,
"color": "#ff00FF"
},
100, // <- a ruler in the default color or as customized (with "editorRuler.foreground") at column 100
{
"column": 120,
"color": "#ff0000"
},
],
Use your file browser and copy-paste the IInAppBillingService.aidl into /app/src/main/aidl/com/android/vending/billing/
I had the same error after converting my project to Kotlin
. My problem was that my jre location was changed to an invalid path during the process (I wonder why this could happen... made me waste time). Fixed it by doing this:
File > Project Structure > SDK Location
Unchecked the Use embedded JDK
option, which was pointing to an old JDK installation, and selected the correct one:
/home/my_user/jdk1.8.0_101
After changing this, the error disappeared
Under Centos7 64 bit the issue is that some 32 bit libraries did not exist. To fix this I need to add:
yum install glibc.i686
yum install zlib.i686
yum install libstdc++.i686
Replace your class path with something ambiguous like this. Its a solution and it works but it may not be a good solution.
classpath 'com.android.tools.build:gradle:+'
The best way is replacing the + with the latest version of gradle
This solution work for me
Install Java JDK 8.
Then, go to Tools-> Options ->Tools for Apache Cordova-> Environment Variable Overrides and set the path to your JDK to "C:\Program Files\java\jdk1.8.0_121" to get Java 8 instead of Java 7.
for more info http://www.developersite.org/103-141954-android
Ok, I just faced this problem and tried all of the steps mentioned above but didn't help. So what I did, I checked what image extension it was before I renamed it to .png. In my case it was .jpeg. So I renamed it back to .jpeg and kept the same original file in drawable. And bingo, it just worked fine.
So the solution is, use the file without changing extension, be it .png or .jpeg, keep it the original way.
Thought to share if it helps anyone. Thanks.
It seems you have a jar file or a lib appearing multiple times.
So, remove the .jar file from the lib folder then:
Build
> Rebuild
Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.
public function scopeShowProductCount($query)
{
$query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
->groupBy('pid')
->orderBy('count_pid', 'desc');
}
This facade worked to get the same result in the controller:
$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();
The resulting dump for both queries was as follows:
#attributes: array:2 [
"pid" => "1271"
"count_pid" => 19
],
#attributes: array:2 [
"pid" => "1273"
"count_pid" => 12
],
#attributes: array:2 [
"pid" => "1275"
"count_pid" => 7
]
It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:
ObjectMapper mapper = new ObjectMapper();
String www = "www.sample.pl";
Weather weather = mapper.readValue(www, Weather.class);
But this will:
ObjectMapper mapper = new ObjectMapper();
URL www = new URL("http://www.oracle.com/");
Weather weather = mapper.readValue(www, Weather.class);
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source
(which would be x
in the sample above) is null.
Some time you may just need to add maven { url "https://jitpack.io" }
in your allprojects block in project level build.gradle file.
Example:
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
I am using in Laravel 5.6.28 next middleware:
namespace App\Http\Middleware;
use App\Models\Unit;
use Closure;
use Illuminate\Http\Request;
class HttpsProtocol
{
public function handle($request, Closure $next)
{
$request->setTrustedProxies([$request->getClientIp()], Request::HEADER_X_FORWARDED_ALL);
if (!$request->secure() && env('APP_ENV') === 'prod') {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Create new file called .htaccess
in root project folder and place the below code inside it :
<IfModule mod_rewrite.c>
#Session timeout
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]
RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
</IfModule>
Note: If you changed server.php
to index.php
you also should rename it in above code
For those who are using laravel 5 or above must use public modifier other wise it will throw an exception
Access level to App\yourModelName::$timestamps must be
public (as in class Illuminate\Database\Eloquent\Model)
public $timestamps = false;
With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.
Private Sub Open_multiple_sub_pages_from_main_page()
Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True
' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"
' Wait while IE loading...
While IE.Busy
DoEvents
Wend
Set objCollection = IE.Document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).Name = "txtUserName" Then
' Set text for search
objCollection(i).Value = "1234"
End If
If objCollection(i).Name = "txtPwd" Then
' Set text for search
objCollection(i).Value = "password"
End If
If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
Set objElement = objCollection(i)
End If
i = i + 1
Wend
objElement.Click ' click button to load page
' Wait while IE re-loading...
While IE.Busy
DoEvents
Wend
' Show IE
IE.Visible = True
Set Doc = IE.Document
Dim links, link
Dim j As Integer 'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n 'loop to go thru all "a" item so it loads next page
links(j).Click
While IE.Busy
DoEvents
Wend
'-------------Do stuff here: copy field value and paste in excel sheet. Will post another question for this------------------------
IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click 'save
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click 'close
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
j = j + 2
Wend
End Sub
The general end of line comment, // eslint-disable-line
, does not need anything after it: no need to look up a code to specify what you wish ES Lint to ignore.
If you need to have any syntax ignored for any reason other than a quick debugging, you have problems: why not update your delint config?
I enjoy // eslint-disable-line
to allow me to insert console
for a quick inspection of a service, without my development environment holding me back because of the breach of protocol. (I generally ban console
, and use a logging class - which sometimes builds upon console
.)
You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula
=$B2>$C2
by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down
Laravel min
and max
validation do not work properly with a numeric
rule validation. Instead of numeric, min and max
, Laravel provided a rule digits_between
.
$this->validate($request,[
'field_name'=>'digits_between:2,5',
]);
I had a similar issue, when I upgraded to the latest version of Android Studio 1.3.2. What seemed to work for me was removing the .gradle
folder from my project directory:
rm -rf ~/project/.gradle
As mentioned by jfriend00 you should not expose your server structure. You could copy your project dependency files to something like public/scripts
. You can do this very easily with dep-linker like this:
var DepLinker = require('dep-linker');
DepLinker.copyDependenciesTo('./public/scripts')
// Done
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
If you are migrating to 1.0.0 you need to change the following properties.
In the Project's build.gradle file you need to replace minifyEnabled.
Hence your new build type should be
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
Also make sure that gradle version is 1.0.0 like
classpath 'com.android.tools.build:gradle:1.0.0'
in the build.gradle file.
This should solve the problem.
Source: http://tools.android.com/tech-docs/new-build-system/migrating-to-1-0-0
$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);
if ($validator->fails()) { return $validator->errors(); }
To fix this problem . first you must add latestandroid-support-v7-appcompat from the \sdk\extras\android\support
That works for me and I will strongly recommend you to use Android Studio.
This Worked for me
Actually error is a array which contain error message and other values for elements we pass, you can console.log(error); and see. Inside if condition "error.appendTo($(element).parents('div').find($('.errorEmail')));" Is nothing but finding html element in code and passing the error message.
$("form[name='contactUs']").validate({
rules: {
message: 'required',
name: "required",
phone_number: {
required: true,
minlength: 10,
maxlength: 10,
number: false
},
email: {
required: true,
email: true
}
},
messages: {
name: "Please enter your name",
email: "Please enter a valid email address",
message: "Please enter your message",
phone_number: "Please enter a valid mobile number"
},
errorPlacement: function(error, element) {
$("#errorText").empty();
if(error[0].htmlFor == 'name')
{
error.appendTo($(element).parents('div').find($('.errorName')));
}
if(error[0].htmlFor == 'email')
{
error.appendTo($(element).parents('div').find($('.errorEmail')));
}
if(error[0].htmlFor == 'phone_number')
{
error.appendTo($(element).parents('div').find($('.errorMobile')));
}
if(error[0].htmlFor == 'message')
{
error.appendTo($(element).parents('div').find($('.errorMessage')));
}
}
});
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selector to apply the style to the elements children, not its grand children. For example like this:
JSFiddle - DEMO
.wrapper * {_x000D_
color: blue;_x000D_
margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
color:red;_x000D_
margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="myTestClass">Text 0_x000D_
<div>Text 1</div>_x000D_
<span>Text 1</span>_x000D_
<div>Text 1_x000D_
<p>Text 2</p>_x000D_
<div>Text 2</div>_x000D_
</div>_x000D_
<p>Text 1</p>_x000D_
</div>_x000D_
<div>Text 0</div>_x000D_
</div>
_x000D_
If you are not tweaking the curl command too much you can also go and call the curl command directly
import shlex
cmd = '''curl -X POST -d '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001'''
args = shlex.split(cmd)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:
$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl
I found a work around: Moved the folder to nginx configuration folder, in my case "/etc/nginx/my-web-app". And then changed the permissions to root user "sudo chown -R root:root "my-web-app".
For anyone having same issue with PHP 7, this is what I done to make nginx execute php files properly in CentOS 7, posted here so in case of anyone having same problem:
Follow step by step this document on Digital Ocean.
Open the /etc/nginx/conf.d/default.conf
(by default I don't have sites-enabled nor sites-available, you can edit accordingly).
Edit the location
parameter as below:
default.conf:
location ~ \.php$ {
try_files $uri =404;
#fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
#instruct nginx execute php7 files instead download them :D
fastcgi_pass unix:/var/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
Restart Nginx and PHP services sudo systemctl restart php-fpm
and sudo systemctl restart nginx
.
Last but most important, clear browser cache or running in incognito (Chrome)
or Private Browsing (Firefox)
etc...
Hope this helpful and happy coding
Just add use of origin in your if you use node.js as server...
like this
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
We Need response for origin
If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with
$(document).ajaxStop(function(){
alert("All AJAX requests completed");
});
https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.
For me, changing the ownership of /var/lib/mongodb and /tmp/mongodb-27017.sock to mongodb was the way to go.
Just do:
sudo chown -R mongodb:mongodb /var/lib/mongodb
and then:
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock
and then start or restart the mongodb server:
sudo systemctl start mongod
or
sudo systemctl restart mongod
and check the status
sudo systemctl status mongod
Root-gradle file:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:x.x.x'
}
}
allprojects {
repositories {
jcenter()
}
}
Gradle-wrapper.properties file:
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-x.x-all.zip
Check the minimum API level inside the build.gradle(module: app)[inside of the gradle scripts]. Thatt should be equal to or lower than the device you use
In laravel 6 the latest one can easily add in the "APP/user.php" model:
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'U';
And in schema one can add
$table->integer('created_at')->nullable();
$table->integer('updated_at')->nullable();
This works fine for me.
$(document).ready(function () {
$('#btn_move').click( function(){
var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var Val_date=$('#txt_date').val();
if(Val_date.match(dateformat)){
var seperator1 = Val_date.split('/');
var seperator2 = Val_date.split('-');
if (seperator1.length>1)
{
var splitdate = Val_date.split('/');
}
else if (seperator2.length>1)
{
var splitdate = Val_date.split('-');
}
var dd = parseInt(splitdate[0]);
var mm = parseInt(splitdate[1]);
var yy = parseInt(splitdate[2]);
var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];
if (mm==1 || mm>2)
{
if (dd>ListofDays[mm-1])
{
alert('Invalid date format!');
return false;
}
}
if (mm==2)
{
var lyear = false;
if ( (!(yy % 4) && yy % 100) || !(yy % 400))
{
lyear = true;
}
if ((lyear==false) && (dd>=29))
{
alert('Invalid date format!');
return false;
}
if ((lyear==true) && (dd>29))
{
alert('Invalid date format!');
return false;
}
}
}
else
{
alert("Invalid date format!");
return false;
}
});
});
Late but as a note: after upgrading Chrome to v/81, all check boxes & radio buttons turned blue. So here is a dead simple solution if you ain't okay with blue but with grayscale;
input[type='checkbox'], input[type='radio'] { filter: grayscale(1) }
See more on MDN:
https://developer.mozilla.org/en-US/docs/Web/CSS/filter
https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/grayscale
In my case, all modules were correctly set up (https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension is a good starter) & I had the redirection working for a base url, let's say /mysite/
but I got the errors for any child ULR, let's say /mysite/login/
http://reverse-proxy.dns.com/mysite/
was properly redirected to the remote servers while http://reverse-proxy.dns.com/mysite/login/
failed at the Apache2 reverse proxying with OP's error message.
The issue was the ending /
character in the proxypass directive "/mysite/". Working configuration for child URL is :
<Proxy balancer://mysite_cluster>
BalancerMember http://192.x.x.10:8080/mysite
BalancerMember http://192.x.x.11:8080/mysite
</Proxy>
<VirtualHost *:80>
[...]
ProxyRequests Off
ProxyPreserveHost On
ProxyPass "/mysite" "balancer://mysite_cluster"
ProxyPassReverse "/mysite" "balancer://mysite_cluster"
</VirtualHost>
Trailing /
truly are tricky.
You have to perform following steps to do this, which are as follows
Map your domain upto public folder of your project (i.e. /var/www/html/yourproject/public) (if using linux)
Go to your public folder edit your .htaccess
file there
AddHandler application/x-httpd-php72 .php
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Redirect non-http to https
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Remove index.php
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
</IfModule>
https
, it protect that.My answer is based on getting a 403 error although I had all of the Apache settings mentioned in the other answers correct.
It was a fresh Centos 7 server and it turned out that the issue was not the Apache settings but the fact that the PhpMyAdmin did not serve at all. The solution was to install php and add the php directive to apache.conf:
Don't forget to restart Apache server to take effect - systemctl restart httpd.service
I hope this helps. I first thought my issue was Apache directives, so I post my solution here.
Since you will want to ignore the record you are updating when performing an update, you will want to use ignore
as mentioned by some others. But I prefer to receive an instance of the User
rather then just an ID. This method will also allow you to do the same for other models
Controller
public function update(UserRequest $request, User $user)
{
$user->update($request->all());
return back();
}
UserRequest
public function rules()
{
return [
'email' => [
'required',
\Illuminate\Validation\Rule::unique('users')->ignoreModel($this->route('user')),
],
];
}
update: use ignoreModel
in stead of ignore
I would dump your query so you can take a look at the SQL that was actually executed and see how that differs from what you wrote.
You should be able to do that with the following code:
$queries = DB::getQueryLog();
$last_query = end($queries);
var_dump($last_query);
die();
Hopefully that should give you enough information to allow you to figure out what's gone wrong.
Like sgibb said it was an if problem, it had nothing to do with | or ||.
Here is another way to solve your problem:
for (i in 1:nrow(trip)) {
if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {
trip[i, 'mutType'] <- "G:C to T:A"
}
else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {
trip[i, 'mutType'] <- "G:C to C:G"
}
else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {
trip[i, 'mutType'] <- "G:C to A:T"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {
trip[i, 'mutType'] <- "A:T to T:A"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {
trip[i, 'mutType'] <- "A:T to G:C"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {
trip[i, 'mutType'] <- "A:T to C:G"
}
}
With the latest version of phpmyadmin 5.0.2+ at least
Check that the actual installation was completed correctly,
Mine had been copied over into a sub folder on a linux machine rather that being at the
/usr/share/phpmyadmin/
You've mixed tabs and spaces. __init__
is actually defined nested inside another method, so your class doesn't have its own __init__
method, and it inherits object.__init__
instead. Open your code in Notepad instead of whatever editor you're using, and you'll see your code as Python's tab-handling rules see it.
This is why you should never mix tabs and spaces. Stick to one or the other. Spaces are recommended.
This is common error, make sure that your file.war is built correctly. Just open .war file and check that your WebApplicationInitializer is there.
Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when
and verify
.
Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T>
and expose a method matches(T)
that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.
/* Mockito */ verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));
Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T
where Hamcrest matcher methods return Matcher objects (of type Matcher<T>
).
Mockito matchers are invoked through static methods such as eq
, any
, gt
, and startsWith
on org.mockito.Matchers
and org.mockito.AdditionalMatchers
. There are also adapters, which have changed across Mockito versions:
Matchers
featured some calls (such as intThat
or argThat
) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T>
extended org.hamcrest.Matcher<T>
, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.Matchers
calls phrased as intThat
or argThat
wrap ArgumentMatcher<T>
objects that no longer implement org.hamcrest.Matcher<T>
but are used in similar ways. Hamcrest adapters such as argThat
and intThat
are still available, but have moved to MockitoHamcrest
instead.Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:
/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));
In the above statement: foo.setPowerLevel
is a method that accepts an int
. is(greaterThan(9000))
returns a Matcher<Integer>
, which wouldn't work as a setPowerLevel
argument. The Mockito matcher intThat
wraps that Hamcrest-style Matcher and returns an int
so it can appear as an argument; Mockito matchers like gt(9000)
would wrap that entire expression into a single call, as in the first line of example code.
when(foo.quux(3, 5)).thenReturn(true);
When not using argument matchers, Mockito records your argument values and compares them with their equals
methods.
when(foo.quux(eq(3), eq(5))).thenReturn(true); // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different
When you call a matcher like any
or gt
(greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture()
it stores a matcher that saves its argument instead for later inspection.
Matchers return dummy values such as zero, empty collections, or null
. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt()
or any(Integer.class)
or an empty List<String>
for anyListOf(String.class)
. Because of type erasure, though, Mockito lacks type information to return any value but null
for any()
or argThat(...)
, which can cause a NullPointerException if trying to "auto-unbox" a null
primitive value.
Matchers like eq
and gt
take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.
Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt())
or thenReturn(any(Foo.class))
in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.
Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.
Most matcher calls only add to this stack, with an exception for matchers like and
, or
, and not
. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:
when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6] [5] [1] [4] [2] [3]
This will:
anyInt()
to the stack.gt(10)
to the stack.lt(20)
to the stack.gt(10)
and lt(20)
and add and(gt(10), lt(20))
.foo.quux(0, 0)
, which (unless otherwise stubbed) returns the default value false
. Internally Mockito marks quux(int, int)
as the most recent call.when(false)
, which discards its argument and prepares to stub method quux(int, int)
identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any()
matcher for its first argument and and(gt(10), lt(20))
for its second argument and clears the stack.This demonstrates a few rules:
Mockito can't tell the difference between quux(anyInt(), 0)
and quux(0, anyInt())
. They both look like a call to quux(0, 0)
with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.
Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.
int between10And20 = and(gt(10), lt(20));
/* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
// Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
/* OK */ when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
// The helper method calls the matcher methods in the right order.
The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when
or verify
, but Mockito can't check that automatically.
You can check manually with Mockito.validateMockitoUsage()
.
In a call to when
, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values).
doReturn
and doAnswer
(etc) do not invoke the actual method and are often a useful alternative.
If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq
matcher), Mockito would check the stack length against that call instead, and likely fail.
If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final
method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.
InvalidUseOfMatchersException:
Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when
or verify
call. Matchers should never be used as stubbed return values or fields/variables.
Check that you're not calling a mock as a part of providing a matcher argument.
Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.
NullPointerException with primitive arguments: (Integer) any()
returns null while any(Integer.class)
returns 0; this can cause a NullPointerException
if you're expecting an int
instead of an Integer. In any case, prefer anyInt()
, which will return zero and also skip the auto-boxing step.
NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz)
will actually call foo.bar(null)
, which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any())
skips the stubbed behavior.
Use MockitoJUnitRunner, or explicitly call validateMockitoUsage
in your tearDown
or @After
method (which the runner would do for you automatically). This will help determine whether you've misused matchers.
For debugging purposes, add calls to validateMockitoUsage
in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.
You're getting into looping most likely due to these rules:
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
Just comment it out and try again in a new browser.
I also faced the same problem and the problem was that the libraries were missing in some of the following files.
settings.gradle, app/build.gradle, package.json, MainApplication.java
Suppose the library is react-native-vector-icons then it should be mentioned in following files;
compile project(':react-native-vector-icons')
include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
Import the dependency: import com.oblador.vectoricons.VectorIconsPackage;
and then add: new VectorIconsPackage() in getPackages() method.
You are better off running the command in the console to get a better idea on what is wrong with the settings. In my case, when I ran gradlew check
it actually tells me which referenced project was missing.
* What went wrong:
Could not determine the dependencies of task ':test'.
Could not resolve all task dependencies for configuration ':testRuntimeClasspath'.
Could not resolve project :lib-blah.
Required by:
project :
> Unable to find a matching configuration of project :lib-blah: None of the consumable configurations have attributes.
The annoying thing was that, it would not show any meaningful error message during the import failure. And if I commented out all the project references, sure it let me import it, but then once I uncomment it out, it would only print that ambiguous message and not tell you what is wrong.
For those who use Tomcat with Bitronix, this will fix the problem:
The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.
In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:
(if you already used them, make sure your references are correct):
e.g.
-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59"
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties"
Now, restart your server and check the log.
The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:
HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))
Format..., select formatting, OK, OK.
where I have filled yellow the cells that are triggering the red fill result.
Append the id
of the instance currently being updated to the validator.
Pass the id
of your instance to ignore the unique validator.
In the validator, use a parameter to detect if you are updating or creating the resource.
If updating, force the unique rule to ignore a given id:
//rules
'email' => 'unique:users,email_address,' . $userId,
If creating, proceed as usual:
//rules
'email' => 'unique:users,email_address',
Try this:
myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))
giving:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
or this:
myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))
giving:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.
Above used this input:
myfile <-
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L,
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
Update 1 Since originally posted dplyr has changed %.%
to %>%
so have modified answer accordingly.
Update 2 dplyr now has case_when
which provides another solution:
myfile %>%
mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1,
V2 == 4 & V3 != 1 ~ 2,
TRUE ~ 0))
A .tex file should be a LaTeX source file.
If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.
Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.
Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.
You can also check out this question and answer for how to do it: How to compile a LaTeX document?
Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.
To understand circular dependencies, you need to remember that Python is essentially a scripting language. Execution of statements outside methods occurs at compile time. Import statements are executed just like method calls, and to understand them you should think about them like method calls.
When you do an import, what happens depends on whether the file you are importing already exists in the module table. If it does, Python uses whatever is currently in the symbol table. If not, Python begins reading the module file, compiling/executing/importing whatever it finds there. Symbols referenced at compile time are found or not, depending on whether they have been seen, or are yet to be seen by the compiler.
Imagine you have two source files:
File X.py
def X1:
return "x1"
from Y import Y2
def X2:
return "x2"
File Y.py
def Y1:
return "y1"
from X import X1
def Y2:
return "y2"
Now suppose you compile file X.py. The compiler begins by defining the method X1, and then hits the import statement in X.py. This causes the compiler to pause compilation of X.py and begin compiling Y.py. Shortly thereafter the compiler hits the import statement in Y.py. Since X.py is already in the module table, Python uses the existing incomplete X.py symbol table to satisfy any references requested. Any symbols appearing before the import statement in X.py are now in the symbol table, but any symbols after are not. Since X1 now appears before the import statement, it is successfully imported. Python then resumes compiling Y.py. In doing so it defines Y2 and finishes compiling Y.py. It then resumes compilation of X.py, and finds Y2 in the Y.py symbol table. Compilation eventually completes w/o error.
Something very different happens if you attempt to compile Y.py from the command line. While compiling Y.py, the compiler hits the import statement before it defines Y2. Then it starts compiling X.py. Soon it hits the import statement in X.py that requires Y2. But Y2 is undefined, so the compile fails.
Please note that if you modify X.py to import Y1, the compile will always succeed, no matter which file you compile. However if you modify file Y.py to import symbol X2, neither file will compile.
Any time when module X, or any module imported by X might import the current module, do NOT use:
from X import Y
Any time you think there may be a circular import you should also avoid compile time references to variables in other modules. Consider the innocent looking code:
import X
z = X.Y
Suppose module X imports this module before this module imports X. Further suppose Y is defined in X after the import statement. Then Y will not be defined when this module is imported, and you will get a compile error. If this module imports Y first, you can get away with it. But when one of your co-workers innocently changes the order of definitions in a third module, the code will break.
In some cases you can resolve circular dependencies by moving an import statement down below symbol definitions needed by other modules. In the examples above, definitions before the import statement never fail. Definitions after the import statement sometimes fail, depending on the order of compilation. You can even put import statements at the end of a file, so long as none of the imported symbols are needed at compile time.
Note that moving import statements down in a module obscures what you are doing. Compensate for this with a comment at the top of your module something like the following:
#import X (actual import moved down to avoid circular dependency)
In general this is a bad practice, but sometimes it is difficult to avoid.
About your command line:
root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
You are already authenticated as root
so sudo
is redundant there.
You are missing the -j
or --jump
just before the ACCEPT
parameter (just tought that was a typo and you are inserting it correctly).
About yout question:
If you are inserting the iptables
rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.
If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:
check your vmachine network settings and:
if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.
if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.
if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.
Hope this helps.
I have faced the same question recently. What I understand is, if the branch you are checking in has a file which you modified and it happens to be also modified and committed by that branch. Then git will stop you from switching to the branch to keep your change safe before you commit or stash.
check if tun/tap enabled:
cat /dev/net/tun
if ok will see something :
cat: /dev/net/tun: File descriptor in bad state
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
Example:
iptables -A INPUT -j LOG --log-prefix "INPUT:DROP:" --log-level 6
iptables -A INPUT -j DROP
Log Exampe:
Feb 19 14:18:06 servername kernel: INPUT:DROP:IN=eth1 OUT= MAC=aa:bb:cc:dd:ee:ff:11:22:33:44:55:66:77:88 SRC=x.x.x.x DST=x.x.x.x LEN=48 TOS=0x00 PREC=0x00 TTL=117 ID=x PROTO=TCP SPT=x DPT=x WINDOW=x RES=0x00 SYN URGP=0
Other options:
LOG
Turn on kernel logging of matching packets. When this option
is set for a rule, the Linux kernel will print some
information on all matching packets
(like most IP header fields) via the kernel log (where it can
be read with dmesg or syslogd(8)). This is a "non-terminating
target", i.e. rule traversal
continues at the next rule. So if you want to LOG the packets
you refuse, use two separate rules with the same matching
criteria, first using target LOG
then DROP (or REJECT).
--log-level level
Level of logging (numeric or see syslog.conf(5)).
--log-prefix prefix
Prefix log messages with the specified prefix; up to 29
letters long, and useful for distinguishing messages in
the logs.
--log-tcp-sequence
Log TCP sequence numbers. This is a security risk if the
log is readable by users.
--log-tcp-options
Log options from the TCP packet header.
--log-ip-options
Log options from the IP packet header.
--log-uid
Log the userid of the process which generated the packet.
This happened to me when using ng-include, and the included page had controllers defined. Apparently that's not supported.
If using VueJS, import all the js dependencies for jQuery extensions first, then import $ second...
import "../assets/js/jquery-2.2.3.min.js"
import "../assets/js/jquery-ui-1.12.1.min.js"
import "../assets/js/jquery.validate.min.js"
import $ from "jquery";
You then need to use jquery from a javascript function called from a custom wrapper defined globally in the VueJS prototype method.
This safeguards use of jQuery and jQuery UI from fighting with VueJS.
Vue.prototype.$fValidateTag = function( sTag, rRules )
{
return ValidateTag( sTag, rRules );
};
function ValidateTag( sTag, rRules )
{
Var rTagT = $( sTag );
return rParentTag.validate( sTag, rRules );
}
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
Found my solution thanks to Error with .htaccess and mod_rewrite
For Apache 2.4 and in all *.conf files (e.g. httpd-vhosts.conf, http.conf, httpd-autoindex.conf ..etc) use
Require all granted
instead of
Order allow,deny
Allow from all
The Order and Allow directives are deprecated in Apache 2.4.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]
## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]
<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.
Simply remove the .value
from your code.
Set envFrmwrkPath = ActiveSheet.Range("D6").Value
instead of this, use:
Set envFrmwrkPath = ActiveSheet.Range("D6")
The font may exist with different names, and not at all on some systems, so you need to use different variations and fallback to get the closest possible look on all systems:
font-family: "Comic Sans MS", "Comic Sans", cursive;
Be careful what you use this font for, though. Many consider it as ugly and overused, so it should not be use for something that should look professional.
You can use MATCH
for instance.
Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.
In the entry box, put:
=MATCH(A2, 'Sheet2'!A:A, 0)
Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.
MATCH
takes the value A2
from your data table, looks into 'Sheet2'!A:A
and if there's an exact match (that's why there's a 0
at the end), then it'll return the row number.
Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.
EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:
=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))
In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild
and pointing ndkBuild
path argument at an Android.mk
or change ndkBuild
to cmake
and point the path argument at a CMakeLists.txt
build script.
android {
compileSdkVersion 19
buildToolsVersion "25.0.2"
defaultConfig {
minSdkVersion 19
targetSdkVersion 19
ndk {
abiFilters 'armeabi', 'armeabi-v7a', 'x86'
}
externalNativeBuild {
cmake {
cppFlags '-std=c++11'
arguments '-DANDROID_TOOLCHAIN=clang',
'-DANDROID_PLATFORM=android-19',
'-DANDROID_STL=gnustl_static',
'-DANDROID_ARM_NEON=TRUE',
'-DANDROID_CPP_FEATURES=exceptions rtti'
}
}
}
externalNativeBuild {
cmake {
path 'src/main/jni/CMakeLists.txt'
}
//ndkBuild {
// path 'src/main/jni/Android.mk'
//}
}
}
For much more detail check Google's page on adding native code.
After this is setup correctly you can ./gradlew installDebug
and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.
The other answers do point out the correct way to prevent the automatic creation of Android.mk
files, but they fail to go the extra step of integrating better with Android Studio. I have added the ability to actually clean and build from source without needing to go to the command-line. Your local.properties
file will need to have ndk.dir=/path/to/ndk
apply plugin: 'com.android.application'
android {
compileSdkVersion 14
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.example.application"
minSdkVersion 14
targetSdkVersion 14
ndk {
moduleName "YourModuleName"
}
}
sourceSets.main {
jni.srcDirs = [] // This prevents the auto generation of Android.mk
jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
}
task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
def ndkDir = android.ndkDirectory
commandLine "$ndkDir/ndk-build",
'-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
'-j', Runtime.runtime.availableProcessors(),
'all',
'NDK_DEBUG=1'
}
task cleanNative(type: Exec, description: 'Clean JNI object files') {
def ndkDir = android.ndkDirectory
commandLine "$ndkDir/ndk-build",
'-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
'clean'
}
clean.dependsOn 'cleanNative'
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn buildNative
}
}
dependencies {
compile 'com.android.support:support-v4:20.0.0'
}
The src/main/jni
directory assumes a standard layout of the project. It should be the relative from this build.gradle
file location to the jni
directory.
Also check this Stack Overflow answer.
It is really important that your gradle version and general setup are correct. If you have an older project I highly recommend creating a new one with the latest Android Studio and see what Google considers the standard project. Also, use gradlew
. This protects the developer from a gradle version mismatch. Finally, the gradle plugin must be configured correctly.
And you ask what is the latest version of the gradle plugin? Check the tools page and edit the version accordingly.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
// Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain.
task wrapper(type: Wrapper) {
gradleVersion = '2.2'
}
// Look Google doesn't use Maven Central, they use jcenter now.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
Make sure gradle wrapper
generates the gradlew
file and gradle/wrapper
subdirectory. This is a big gotcha.
This has come up a number of times, but android.ndkDirectory
is the correct way to get the folder after 1.1. Migrating Gradle Projects to version 1.0.0. If you're using an experimental or ancient version of the plugin your mileage may vary.
I solved this by stopping mysql several times.
$ mysql.server stop
Shutting down MySQL
.. ERROR! The server quit without updating PID file (/usr/local/var/mysql/xxx.local.pid).
$ mysql.server stop
Shutting down MySQL
.. SUCCESS!
$ mysql.server stop
ERROR! MySQL server PID file could not be found! (note: this is good)
$ mysql.server start
All good from here. I suspect mysql had been started more than once.
I solved the problem by installing the google play services package in sdk manager.
After it, create a new application & in the build.gradle add this
compile 'com.google.android.gms:play-services:4.3.+'
Like this
dependencies {
compile 'com.android.support:appcompat-v7:+'
compile 'com.google.android.gms:play-services:4.3.+'
}
I created a little javascript tool to style elements on screen size without using media queries or recompiling bootstrap css:
https://github.com/Heras/Responsive-Breakpoints
Just add class responsive-breakpoints
to any element, and it will automagically add xs sm md lg xl
classes to those elements.
You need to:
Go to cloud.google.com
Go to my Console
Choose your Project
Choose Networking > VPC network
Choose "Firewalls rules"
Choose "Create Firewall Rule"
To apply the rule to select VM instances, select Targets > "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like. Then, make sure the instances have the network tag applied.
To allow incoming TCP connections to port 9090, in "Protocols and Ports" enter tcp:9090
Click Create
I hope this helps you.
Update Please refer to docs to customize your rules.
In your example 'nan'
is a string so instead of using isnan()
just check for the string
like this:
cleanedList = [x for x in countries if x != 'nan']
You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.
The Basic Auth / Session ID can be stolen via:
By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.
The new (more secure) flow would be:
Updated 30.07.15:
JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).
I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).
Updated 17.07.16:
JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.
Simply use the .rules('add')
method immediately after creating the element...
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
// create the new input element
$('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
// declare the rule on this newly created input field
$('#FileUpload' + filenumber).rules('add', {
required: true, // <- with this you would not need 'required' attribute on input
accept: "image/jpeg, image/pjpeg"
});
filenumber++; // increment counter for next time
return false;
});
You'll still need to use .validate()
to initialize the plugin within a DOM ready handler.
You'll still need to declare rules for your static elements using .validate()
. Whatever input elements that are part of the form when the page loads... declare their rules within .validate()
.
You don't need to use .each()
, when you're only targeting ONE element with the jQuery selector attached to .rules()
.
You don't need the required
attribute on your input element when you're declaring the required
rule using .validate()
or .rules('add')
. For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required"
.
Working DEMO: http://jsfiddle.net/8dAU8/5/
<table cellpadding="0" cellspacing="0" width="100%" style="border: 1px;" rules="none">_x000D_
<tbody>_x000D_
<tr>_x000D_
<th style="width: 96px;">Column 1</th>_x000D_
<th style="width: 96px;">Column 2</th>_x000D_
<th style="width: 96px;">Column 3</th>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td style="border-left: thin solid; border-top: thin solid; border-bottom: thin solid;"> </td>_x000D_
<td style="border-top: thin solid; border-bottom: thin solid;"> </td>_x000D_
<td style="border-top: thin solid; border-bottom: thin solid; border-right: thin solid;"> </td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
There are times that using OPTION(RECOMPILE)
makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:
EXEC sp_updatestats
And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.
Adding OPTION(RECOMPILE)
rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy
but maybe we are just using different terms for the same thing.
When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.
In summary - I don't see any reason that OPTION(RECOMPILE)
would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.
And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.
Here is the code - The code is in asp.net core 2.0 but should work in above versions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;
namespace UnityAssets.Website.Services
{
public class EmailSender : IEmailSender
{
public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
{
var email = new MimeMessage();
email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
email.Subject = subject;
var body = new BodyBuilder
{
HtmlBody = htmlMessage
};
email.Body = body.ToMessageBody();
using (var client = new SmtpClient())
{
//provider specific settings
await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);
await client.SendAsync(email).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
}
}
Bootstrap has 3 lines of CSS, within your bootstrap.css generated file that control the placeholder text color:
.form-control::-moz-placeholder {
color: #999999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999999;
}
.form-control::-webkit-input-placeholder {
color: #999999;
}
Now if you add this to your own CSS file it won't override bootstrap's because it is less specific. So assmuning your form inside a then add that to your CSS:
form .form-control::-moz-placeholder {
color: #fff;
opacity: 1;
}
form .form-control:-ms-input-placeholder {
color: #fff;
}
form .form-control::-webkit-input-placeholder {
color: #fff;
}
Voila that will override bootstrap's CSS.
in my case just removing background-image
from nav-bar
item solved the problem
.navbar-default .navbar-nav > .active > a:focus {
.
.
.
background-image: none;
}
Using !important
is not a good option, as you will most likely want to override your own styles in the future. That leaves us with CSS priorities.
Basically, every selector has its own numerical 'weight':
Among two selector styles browser will always choose the one with more weight. Order of your stylesheets only matters when priorities are even - that's why it is not easy to override Bootstrap.
Your option is to inspect Bootstrap sources, find out how exactly some specific style is defined, and copy that selector so your element has equal priority. But we kinda loose all Bootstrap sweetness in the process.
The easiest way to overcome this is to assign additional arbitrary ID to one of the root elements on your page, like this: <body id="bootstrap-overrides">
This way, you can just prefix any CSS selector with your ID, instantly adding 100 points of weight to the element, and overriding Bootstrap definitions:
/* Example selector defined in Bootstrap */
.jumbotron h1 { /* 10+1=11 priority scores */
line-height: 1;
color: inherit;
}
/* Your initial take at styling */
h1 { /* 1 priority score, not enough to override Bootstrap jumbotron definition */
line-height: 1;
color: inherit;
}
/* New way of prioritization */
#bootstrap-overrides h1 { /* 100+1=101 priority score, yay! */
line-height: 1;
color: inherit;
}
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
I hit this problem when I tried to run a Laravel 5.8 app on my server, uploading from local development using Vagrant Homestead. After a while I figured out that the dev subdomain on the live server I was running was somehow set to PHP 5.6.
cPanel > MultiPHP Manager > Set to PHP 7.2
fixed this for me. Hope this might help someone.
This works for me:
android {
packagingOptions {
exclude 'LICENSE.txt'
}
}
I have also got stuck into this and believe me disabling SELinux is not a good idea.
Please just use below and you are good,
sudo restorecon -R /var/www/mysite
Enjoy..
Padding is a way to add kind of a margin inside the Div.
Just Use
div { padding-left: 20px; }
And to mantain the size, you would have to -20px from the original width of the Div.
The server directive has to be in the http directive. It should not be outside of it.
Incase if you need detailed information, refer this.
This code works. I have a date input field that has been set to read only which forces the user to select from the calendar.
for a start date:
var updateInput = "var input = document.getElementById('startDateInput');" +
"input.value = '18-Jan-2016';" +
"angular.element(input).scope().$apply(function(s) { s.$parent..searchForm[input.name].$setViewValue(input.value);})";
browser.executeScript(updateInput);
for an end date:
var updateInput = "var input = document.getElementById('endDateInput');" +
"input.value = '22-Jan-2016';" +
"angular.element(input).scope().$apply(function(s) { s.$parent.searchForm[input.name].$setViewValue(input.value);})";
browser.executeScript(updateInput);
There is a new DecisionTreeClassifier
method, decision_path
, in the 0.18.0 release. The developers provide an extensive (well-documented) walkthrough.
The first section of code in the walkthrough that prints the tree structure seems to be OK. However, I modified the code in the second section to interrogate one sample. My changes denoted with # <--
Edit The changes marked by # <--
in the code below have since been updated in walkthrough link after the errors were pointed out in pull requests #8653 and #10951. It's much easier to follow along now.
sample_id = 0
node_index = node_indicator.indices[node_indicator.indptr[sample_id]:
node_indicator.indptr[sample_id + 1]]
print('Rules used to predict sample %s: ' % sample_id)
for node_id in node_index:
if leave_id[sample_id] == node_id: # <-- changed != to ==
#continue # <-- comment out
print("leaf node {} reached, no decision here".format(leave_id[sample_id])) # <--
else: # < -- added else to iterate through decision nodes
if (X_test[sample_id, feature[node_id]] <= threshold[node_id]):
threshold_sign = "<="
else:
threshold_sign = ">"
print("decision id node %s : (X[%s, %s] (= %s) %s %s)"
% (node_id,
sample_id,
feature[node_id],
X_test[sample_id, feature[node_id]], # <-- changed i to sample_id
threshold_sign,
threshold[node_id]))
Rules used to predict sample 0:
decision id node 0 : (X[0, 3] (= 2.4) > 0.800000011921)
decision id node 2 : (X[0, 2] (= 5.1) > 4.94999980927)
leaf node 4 reached, no decision here
Change the sample_id
to see the decision paths for other samples. I haven't asked the developers about these changes, just seemed more intuitive when working through the example.
You can install IPA using Xcode
This will install application on your device.
I change upload method with images[]
according to @Denmark.
private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return $images;
}
I want to add something.
Actually, Task.Delay
is a timer based wait mechanism. If you look at the source you would find a reference to a Timer
class which is responsible for the delay. On the other hand Thread.Sleep
actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay()
if you want something(continuation) happen after some delay.
I know this is not a coding answer but it is what the OP wanted and what I have spent half the day trying to achieve - print from a web page with page numbers.
Yes, it is two steps instead of one but I haven't been able to find any CSS option despite several hours of searching. Real shame all the browsers removed the functionality that used to allow it.
function validatePhone(txtPhone) {
var a = document.getElementById(txtPhone).value;
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
}
For the Scripting.Dictionary type, you can either use late binding (as already pointed out ) with:
Dim Dict as Object
Set Dict = CreateObject("Scripting.Dictionary")
Which works, but you don't get the code auto completion. Or you use early binding, but you need to make sure that VBA can find the Scripting.Dictionary type by adding the reference to the Microsoft Scripting Library via VBA-->Tools-->References--> "Microsoft Scripting Runtime". Then you can use:
Dim Dict as Scripting.Dictionary
Set Dict = New Scripting.Dictionary
... and auto completion will work.
Create a .gitignore file, so to do that, you just create any blank .txt file.
Then you have to change its name writing the following line on the cmd (where git.txt
is the name of the file you've just created):
rename git.txt .gitignore
Then you can open the file and write all the untracked files you want to ignore for good. For example, mine looks like this:
```
OS junk files
[Tt]humbs.db
*.DS_Store
#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
*.pyc
*.xml
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad
#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*
#Project files
[Bb]uild/
#Subversion files
.svn
# Office Temp Files
~$*
There's a whole collection of useful .gitignore files by GitHub
Once you have this, you need to add it to your git repository just like any other file, only it has to be in the root of the repository.
Then in your terminal you have to write the following line:
git config --global core.excludesfile ~/.gitignore_global
From oficial doc:
You can also create a global .gitignore file, which is a list of rules for ignoring files in every Git repository on your computer. For example, you might create the file at ~/.gitignore_global and add some rules to it.
Open Terminal. Run the following command in your terminal: git config --global core.excludesfile ~/.gitignore_global
If the respository already exists then you have to run these commands:
git rm -r --cached .
git add .
git commit -m ".gitignore is now working"
If the step 2 doesn´t work then you should write the hole route of the files that you would like to add.
you can use unlink in the folder where you have created your symlink
None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome:
<iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe>
I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage.
When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik.
var str = "IAMA JavaScript Developer";
var a=str.split(''), b = a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift())
}
a.shift();
alert(a.join(''));
Okay, this maybe an old post... but was first result in google and decided to make your own mix on this as..
FIRSTLY I WILL USE FOCUS
The reason for this is that it works nicely for the example i'm showing, if someone wants a mouse down type event then use active
THE HTML CODE:
<button class="mdT mdI1" ></button>
<button class="mdT mdI2" ></button>
<button class="mdT mdI3" ></button>
<button class="mdT mdI4" ></button>
THE CSS CODE:
/* Change Button Size/Border/BG Color And Align To Middle */
.mdT {
width:96px;
height:96px;
border:0px;
outline:0;
vertical-align:middle;
background-color:#AAAAAA;
}
.mdT:focus {
width:256px;
height:256px;
}
/* Change Images Depending On Focus */
.mdI1 { background-image:url('http://placehold.it/96x96/AAAAAA&text=img1'); }
.mdI1:focus { background-image:url('http://placehold.it/256x256/555555&text=Image+1'); }
.mdI2 { background-image:url('http://placehold.it/96x96/AAAAAA&text=img2'); }
.mdI2:focus { background-image:url('http://placehold.it/256x256/555555&text=Image+2'); }
.mdI3 { background-image:url('http://placehold.it/96x96/AAAAAA&text=img3'); }
.mdI3:focus { background-image:url('http://placehold.it/256x256/555555&text=Image+3'); }
.mdI4 { background-image:url('http://placehold.it/96x96/AAAAAA&text=img4'); }
.mdI4:focus { background-image:url('http://placehold.it/256x256/555555&text=Image+4'); }
JS FIDDLE LINK: http://jsfiddle.net/00wwkjux/
So why am i posting this in an old thread, well because the examples here vary and i thought to provide one back to the community which is a working example.
As already answered by the thread creator, they only want the effect to last during the click event. Now while this is not exact for that need, its close. active will animate while the mouse is down and any changes that you need to have last longer need to be done with javascript.
This is the most common issue faced by Windows users for running Docker Containers. IMO this is the "million dollar question on Docker"; @"Rocco Smit" has rightly pointed out "inbound traffic for it was disabled by default on my host machine's firewall"; in my case, my McAfee Anti Virus software. I added additional ports to be allowed for inbound traffic from other computers on the same Wifi LAN in the Firewall Settings of McAfee; then it was magic. I had struggled for more than a week browsing all over internet, SO, Docker documentations, Tutorials after Tutorials related to the Networking of Docker, and the many illustrations of "not supported on Windows" for "macvlan", "ipvlan", "user defined bridge" and even this same SO thread couple of times. I even started browsing google with "anybody using Docker in Production?", (yes I know Linux is more popular for Prod workloads compared to Windows servers) as I was not able to access (from my mobile in the same Home wifi) an nginx app deployed in Docker Container on Windows. After all, what good it is, if you cannot access the application (deployed on a Docker Container) from other computers / devices in the same LAN at-least; Ultimately in my case, the issue was just with a firewall blocking inbound traffic;
Use Jenkins.
Jenkins is the recent fork by the core developers of Hudson. To understand why, you need to know the history of the project. It was originally open source and supported by Sun. Like much of what Sun did, it was fairly open, but there was a bit of benign neglect. The source, trackers, website, etc. were hosted by Sun on their relatively closed java.net platform.
Then Oracle bought Sun. For various reasons Oracle has not been shy about leveraging what it perceives as its assets. Those include some control over the logistic platform of Hudson, and particularly control over the Hudson name. Many users and contributors weren't comfortable with that and decided to leave.
So it comes down to what Hudson vs Jenkins offers. Both Oracle's Hudson and Jenkins have the code. Hudson has Oracle and Sonatype's corporate support and the brand. Jenkins has most of the core developers, the community, and (so far) much more actual work.
Read that post I linked up top, then read the rest of these in chronological order. For balance you can read the Hudson/Oracle take on it. It's pretty clear to me who is playing defensive and who has real intentions for the project.
You have to merge your files first. Do a git status
to see what are the files that need to be merged (means you need to resolve the conflicts first). Once this is done, do git add file_merged
and do your pull
again.
You're trying to use a dict
as a key to another dict
or in a set
. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:
>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:
>>> key = frozenset(dict_key.items())
Now you may use key
as a key in a dict
or set
:
>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}
Of course you need to repeat the exercise whenever you want to look up something using a dict:
>>> some_dict[dict_key] # Doesn't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())] # Works
True
If the dict
you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:
def freeze(d):
if isinstance(d, dict):
return frozenset((key, freeze(value)) for key, value in d.items())
elif isinstance(d, list):
return tuple(freeze(value) for value in d)
return d
mytimer.h:
#ifndef MYTIMER_H
#define MYTIMER_H
#include <QTimer>
class MyTimer : public QObject
{
Q_OBJECT
public:
MyTimer();
QTimer *timer;
public slots:
void MyTimerSlot();
};
#endif // MYTIME
mytimer.cpp:
#include "mytimer.h"
#include <QDebug>
MyTimer::MyTimer()
{
// create a timer
timer = new QTimer(this);
// setup signal and slot
connect(timer, SIGNAL(timeout()),
this, SLOT(MyTimerSlot()));
// msec
timer->start(1000);
}
void MyTimer::MyTimerSlot()
{
qDebug() << "Timer...";
}
main.cpp:
#include <QCoreApplication>
#include "mytimer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Create MyTimer instance
// QTimer object will be created in the MyTimer constructor
MyTimer timer;
return a.exec();
}
If we run the code:
Timer...
Timer...
Timer...
Timer...
Timer...
...
You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to
and following the instructions there.
If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.
(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)
While above approaches do not address the case for Mac OS X because Mac Os X does not support -readable
switch this is how you can avoid 'Permission denied' errors in your output. This might help someone.
find / -type f -name "your_pattern" 2>/dev/null
.
If you're using some other command with find
, for example, to find the size of files of certain pattern in a directory 2>/dev/null
would still work as shown below.
find . -type f -name "your_pattern" -exec du -ch {} + 2>/dev/null | grep total$
.
This will return the total size of the files of a given pattern. Note the 2>/dev/null
at the end of find command.
As input and output streams are just start and end point, the solution is to temporary store data in byte array. So you must create intermediate ByteArrayOutputStream
, from which you create byte[]
that is used as input for new ByteArrayInputStream
.
public void doTwoThingsWithStream(InputStream inStream, OutputStream outStream){
//create temporary bayte array output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doFirstThing(inStream, baos);
//create input stream from baos
InputStream isFromFirstData = new ByteArrayInputStream(baos.toByteArray());
doSecondThing(isFromFirstData, outStream);
}
Hope it helps.
HTML:
<div ng-repeat="scannedDevice in ScanResult">
<!--GridStarts-->
<div >
<img ng-src={{'./assets/img/PlaceHolder/Test.png'}}
<!--Pass Param-->
ng-click="connectDevice(scannedDevice.id)"
altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}"
onerror="this.src = $(this).attr('altSrc')">
</div>
</div>
Java Script:
//Global Variables
var ANGULAR_APP = angular.module('TestApp',[]);
ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {
//Variables
$scope.ScanResult = [];
//Pass Parameter
$scope.connectDevice = function(deviceID) {
alert("Connecting : "+deviceID );
};
}]);
I'd go with @sandeep's display: table-cell
answer if you don't care about IE7.
Otherwise, here's an alternative, with one downside: the "right" div
has to come first in the HTML.
See: http://jsfiddle.net/thirtydot/qLTMf/
and exactly the same, but with the "right div" removed: http://jsfiddle.net/thirtydot/qLTMf/1/
#parent {
overflow: hidden;
border: 1px solid red
}
.right {
float: right;
width: 100px;
height: 100px;
background: #888;
}
.left {
overflow: hidden;
height: 100px;
background: #ccc
}
<div id="parent">
<div class="right">right</div>
<div class="left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam semper porta sem, at ultrices ante interdum at. Donec condimentum euismod consequat. Ut viverra lorem pretium nisi malesuada a vehicula urna aliquet. Proin at ante nec neque commodo bibendum. Cras bibendum egestas lacus, nec ullamcorper augue varius eget.</div>
</div>
Late contribution but just came across something similar in Python datetime and pandas give different timestamps for the same date.
If you have timezone-aware datetime in pandas
, technically, tz_localize(None)
changes the POSIX timestamp (that is used internally) as if the local time from the timestamp was UTC. Local in this context means local in the specified timezone. Ex:
import pandas as pd
t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="US/Central")
# DatetimeIndex(['2013-05-18 12:00:00-05:00', '2013-05-18 13:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H')
t_loc = t.tz_localize(None)
# DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')
# offset in seconds according to timezone:
(t_loc.values-t.values)//1e9
# array([-18000, -18000], dtype='timedelta64[ns]')
Note that this will leave you with strange things during DST transitions, e.g.
t = pd.date_range(start="2020-03-08 01:00:00", periods=2, freq='H', tz="US/Central")
(t.values[1]-t.values[0])//1e9
# numpy.timedelta64(3600,'ns')
t_loc = t.tz_localize(None)
(t_loc.values[1]-t_loc.values[0])//1e9
# numpy.timedelta64(7200,'ns')
In contrast, tz_convert(None)
does not modify the internal timestamp, it just removes the tzinfo
.
t_utc = t.tz_convert(None)
(t_utc.values-t.values)//1e9
# array([0, 0], dtype='timedelta64[ns]')
My bottom line would be: stick with timezone-aware datetime if you can or only use t.tz_convert(None)
which doesn't modify the underlying POSIX timestamp. Just keep in mind that you're practically working with UTC then.
(Python 3.8.2 x64 on Windows 10, pandas
v1.0.5.)
Localstorage is designed to be accessible by javascript, so it doesn't provide any XSS protection. As mentioned in other answers, there is a bunch of possible ways to do an XSS attack, from which localstorage is not protected by default.
However, cookies have security flags which protect from XSS and CSRF attacks. HttpOnly flag prevents client side javascript from accessing the cookie, Secure flag only allows the browser to transfer the cookie through ssl, and SameSite flag ensures that the cookie is sent only to the origin. Although I just checked and SameSite is currently supported only in Opera and Chrome, so to protect from CSRF it's better to use other strategies. For example, sending an encrypted token in another cookie with some public user data.
So cookies are a more secure choice for storing authentication data.
When you are working with JSON data in Android, you would use JSONArray
to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects).
For example: [{"name":"item 1"},{"name": "item2} ]
On the other hand, you would use JSONObject
when dealing with JSON that begins with curly braces. A JSON object is typically used to contain key/value pairs related to one item.
For example: {"name": "item1", "description":"a JSON object"}
Of course, JSON arrays and objects may be nested inside one another. One common example of this is an API which returns a JSON object containing some metadata alongside an array of the items matching your query:
{"startIndex": 0, "data": [{"name":"item 1"},{"name": "item2"} ]}
In [95]: import scipy
In [96]: scipy.__version__
Out[96]: '0.12.0'
In [104]: scipy.version.*version?
scipy.version.full_version
scipy.version.short_version
scipy.version.version
In [105]: scipy.version.full_version
Out[105]: '0.12.0'
In [106]: scipy.version.git_revision
Out[106]: 'cdd6b32233bbecc3e8cbc82531905b74f3ea66eb'
In [107]: scipy.version.release
Out[107]: True
In [108]: scipy.version.short_version
Out[108]: '0.12.0'
In [109]: scipy.version.version
Out[109]: '0.12.0'
See SciPy doveloper documentation for reference.
Please try to remove the preceeding spaces before EOF
:-
/var/mail -s "$SUBJECT" "$EMAIL" <<-EOF
Using <tab>
instead of <spaces>
for ident AND using <<-EOF works fine.
The "-"
removes the <tabs>
, not <spaces>
, but at least this works.
My solution if you work with the Trunk/
and Release/
workflow:
Right click on Trunk/
which you will be creating your Branch from:
Select Branch/Tag:
Type in location of your new branch, commit message, and any externals (if your repository has them):
Note, you can use {{.}}
to render the current context item.
{{#avatar}}{{.}}{{/avatar}}
{{^avatar}}missing{{/avatar}}
When I ran into this issue of wanting a less generic DropdownStringButton, I just created it:
dropdown_string_button.dart
import 'package:flutter/material.dart';
// Subclass of DropdownButton based on String only values.
// Yes, I know Flutter discourages subclassing, but this seems to be
// a reasonable exception where a commonly used specialization can be
// made more easily usable.
//
// Usage:
// DropdownStringButton(items: ['A', 'B', 'C'], value: 'A', onChanged: (string) {})
//
class DropdownStringButton extends DropdownButton<String> {
DropdownStringButton({
Key key, @required List<String> items, value, hint, disabledHint,
@required onChanged, elevation = 8, style, iconSize = 24.0, isDense = false,
isExpanded = false, }) :
assert(items == null || value == null || items.where((String item) => item == value).length == 1),
super(
key: key,
items: items.map((String item) {
return DropdownMenuItem<String>(child: Text(item), value: item);
}).toList(),
value: value, hint: hint, disabledHint: disabledHint, onChanged: onChanged,
elevation: elevation, style: style, iconSize: iconSize, isDense: isDense,
isExpanded: isExpanded,
);
}
I got it done by only encoding the output using utf-8. Here is the code example
new_tweets = api.GetUserTimeline(screen_name = user,count=200)
result = new_tweets[0]
try: text = result.text
except: text = ''
with open(file_name, 'a', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(text)
i.e: do not encode when collecting data from api, encode the output (print or write) only.
You can convert to a Double[]
by calling frameList.toArray(new Double[frameList.size()])
, but you'll need to iterate the list/array to convert to double[]
Given the general support of .innerHTML
these days, the only effective difference now is that .html()
will execute code in any <script>
tags if there are any in the html you give it. .innerHTML
, under HTML5, will not.
From the jQuery docs:
By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example,
<img onload="">
). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
Note: both .innerHTML
and .html()
can execute js other ways (e.g the onerror
attribute).
That should be simple. Try this:
var idList = new int[1, 2, 3, 4, 5];
var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e));
For me, plain old .contents()
appeared to work to return the text nodes, just have to be careful with your selectors so that you know they will be text nodes.
For example, this wrapped all the text content of the TDs in my table with pre
tags and had no problems.
jQuery("#resultTable td").content().wrap("<pre/>")
For t-SQL I use the following query for varchar columns (shows the collation and is_null properties):
SELECT
s.name
, o.name as table_name
, c.name as column_name
, t.name as type
, c.max_length
, c.collation_name
, c.is_nullable
FROM
sys.columns c
INNER JOIN sys.objects o ON (o.object_id = c.object_id)
INNER JOIN sys.schemas s ON (s.schema_id = o.schema_id)
INNER JOIN sys.types t ON (t.user_type_id = c.user_type_id)
WHERE
s.name = 'dbo'
AND t.name IN ('varchar') -- , 'char', 'nvarchar', 'nchar')
ORDER BY
o.name, c.name
The only difference I see is that getJSON performs a GET request instead of a POST.
Apart from the previous use cases, you can also use Docker Compose to create directories in case you want to make new dummy folders on docker-compose up
:
volumes:
- .:/ftp/
- /ftp/node_modules
- /ftp/files
if you wanna keep OOP form without turning any error off, you can also:
class A
{
public function foo() {
;
}
}
class B extends A
{
/*instead of :
public function foo($a, $b, $c) {*/
public function foo() {
list($a, $b, $c) = func_get_args();
// ...
}
}
If you only need to modify the page num you can replace it:
var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);
I had no problem making EditTextPreference read-only, by using:
editTextPref.setSelectable(false);
This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html
private static final List<String> keyList;
static {
keyList = new ArrayList<String>();
keyList.add("field1");
keyList.add("field2");
keyList.add("field3");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
initSummary(getPreferenceScreen().getPreference(i));
}
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
//editTextPref.setEnabled(false); // this can be used to 'gray out' as well
editTextPref.setSelectable(false);
if (keyList.contains(p.getKey())) {
p.setSummary(editTextPref.getText());
}
}
}
You said you are attempting to get the text from a div and store it on local storage.
Please Note: Text and Html are different. In the question you mentioned text. html()
will return Html content like <a>example</a>
. if you want to get Text content then you have to use text()
instead of html()
then the result will be example
instead of <a>example<a>
. Anyway, I am using your terminology let it be Text.
Step 1: get the text from div.
what you did is not get the text from div but set the text to a div.
$('#test').html("Test");
is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object]
.
To get the text you have to write like this
$('#test').html();
This will return a string not an object so the result will be Test
in your case.
Step 2: set it to local storage.
Your approach is correct and you can write it as
localStorage.key=value
But the preferred approach is
localStorage.setItem(key,value);
to set
localStorage.getItem(key);
to get.
key and value must be strings.
so in your context code will become
$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);
But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;
If you are facing any other problems please update your question accordingly.
Try this:
-- http://lua-users.org/wiki/FileInputOutput
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
Here is a short and sweet answer with an example.
table{_x000D_
width: 100%;_x000D_
}_x000D_
table td, table th {_x000D_
border: 1px solid #000;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<body>_x000D_
<table>_x000D_
<tr>_x000D_
<th class="text-left">Text align left.</th>_x000D_
<th class="text-center">Text align center.</th>_x000D_
<th class="text-right">Text align right.</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="text-left">Text align left.</td>_x000D_
<td class="text-center">Text align center.</td>_x000D_
<td class="text-right">Text align right.</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>
_x000D_
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
$objPHPExcel->getActiveSheet()->getStyle("A1:".$objPHPExcel->getActiveSheet()->getHighestDataColumn()."1")->getFont()->setBold(true);
I found this to be a working solution, you can replace the two instances of 1
with the row number. The HighestDataColumn
function returns for example C or Z, it gives you the last/highest column that's in the sheet containing any data. There is also getHighestColumn()
, that one would include cells that are empty but have styling or are part of other functionality.
Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.
In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:
import matplotlib.pyplot as plt
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()
By default, Homebrew installs packages to your /usr/local. Macport commands require sudo to install and upgrade (similar to apt-get in Ubuntu).
For more detail:
This site suggests using Hombrew: http://deephill.com/macports-vs-homebrew/
whereas this site lists the advantages of using Macports: http://arstechnica.com/civis/viewtopic.php?f=19&t=1207907
I also switched from Ubuntu recently, and I enjoy using homebrew (it's simple and easy to use!), but if you feel attached to using sudo, Macports might be the better way to go!
There is no full proof way.
But here is some strategy that can be employed to hide source code using "window.history.pushState()" and adding oncontextmenu="return false"
in body tag as attribute
like <body oncontextmenu="return false">
to disable right click too along with modifying view-source content using "history.pushState()".
Detail here - http://freelancer.usercv.com/blog/28/hide-website-source-code-in-view-source-using-stupid-one-line-chinese-hack-code
Fixed mine like this:
yum install elfutils-default-yama-scope-0.168-8.el7.noarch --disablerepo=epel
yum install nss-pem -disablerepo=epel
yum reinstall ca-certificates --disablerepo=epel
yum clean all
rm -rf /var/cache/yum
yum update`
for anyone encountering this later this may also help. I encountered this exact issue trying to use adb from a user command prompt and the answers above did not help, but the problem went away with an "adb kill-server" when running in an administrator command prompt.
Check this key for 32 bits and 64 bits Windows machines.
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
and this for Windows 64 bits with 32 Bits JRE.
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
This will work for the oracle-sun JRE.
The string is basically bounded from the place where it is pointed to (char *ptrChar;
), to the null character (\0
).
The char *ptrChar;
actually points to the beginning of the string (char array), and thus that is the pointer to that string,
so when you do like ptrChar[x]
for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).
32-bit
%windir%\Microsoft.NET\Framework\[version]\config\machine.config
64-bit
%windir%\Microsoft.NET\Framework64\[version]\config\machine.config
[version]
should be equal to v1.0.3705
, v1.1.4322
, v2.0.50727
or v4.0.30319
.
v3.0
and v3.5
just contain additional assemblies to v2.0.50727
so there should be no config\machine.config
. v4.5.x
and v4.6.x
are stored inside v4.0.30319
.
private Color FromHex(string hex)
{
if (hex.StartsWith("#"))
hex = hex.Substring(1);
if (hex.Length != 6) throw new Exception("Color not valid");
return Color.FromArgb(
int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
}
Check the Registry for the existence of HKLM\SOFTWARE\Wow6432Node - If it's there, the system is 64-bit - 32-bit, otherwise.
You mean you want to show a javascript alert when a button is clicked on a PHP generated page?
echo('<button type="button" onclick="alert(\'Alrt Text!\');">My Button</button>');
Would do that
all the major javascript libraries like jscript, prototype, YUI have support for loading script files. For example, in YUI, after loading the core you can do the following to load the calendar control
var loader = new YAHOO.util.YUILoader({
require: ['calendar'], // what components?
base: '../../build/',//where do they live?
//filter: "DEBUG", //use debug versions (or apply some
//some other filter?
//loadOptional: true, //load all optional dependencies?
//onSuccess is the function that YUI Loader
//should call when all components are successfully loaded.
onSuccess: function() {
//Once the YUI Calendar Control and dependencies are on
//the page, we'll verify that our target container is
//available in the DOM and then instantiate a default
//calendar into it:
YAHOO.util.Event.onAvailable("calendar_container", function() {
var myCal = new YAHOO.widget.Calendar("mycal_id", "calendar_container");
myCal.render();
})
},
// should a failure occur, the onFailure function will be executed
onFailure: function(o) {
alert("error: " + YAHOO.lang.dump(o));
}
});
// Calculate the dependency and insert the required scripts and css resources
// into the document
loader.insert();
BigDecimal decPrec = (BigDecimal)yo.get("Avg");
decPrec = decPrec.setScale(5, RoundingMode.CEILING);
String value= String.valueOf(decPrec);
This way you can set specific precision of a BigDecimal
.
The value of decPrec was 1.5726903423607562595809913132345426
which is rounded off to 1.57267
.
If you want to unit test code then you need to isolate your code you want to test (in this case your service) from external resources (e.g. databases). You could probably do this with some sort of in-memory EF provider, however a much more common way is to abstract away your EF implementation e.g. with some sort of repository pattern. Without this isolation any tests you write will be integration tests, not unit tests.
As for testing EF code - I write automated integration tests for my repositories that write various rows to the database during their initialization, and then call my repository implementations to make sure that they behave as expected (e.g. making sure that results are filtered correctly, or that they are sorted in the correct order).
These are integration tests not unit tests, as the tests rely on having a database connection present, and that the target database already has the latest up-to-date schema installed.
Another way
@Html.TextAreaFor(model => model.Comments[0].Comment)
And in your css do this
textarea
{
font-family: inherit;
width: 650px;
height: 65px;
}
That DataType dealie allows carriage returns in the data, not everybody likes those.
Create a new Java project in Eclipse. This will create a src folder (to contain your source files).
Also create a lib folder (the name isn't that important, but it follows standard conventions).
Copy the ./com/*
folders into the /src
folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).
Copy any dependencies (jar
files that your project itself depends on) into /lib
(note that this should NOT include the TGGL jar
- thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!)
Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app)
Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents.
The content of the /src
folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). If you have dependencies (which you don't in your current project, but I'll include this here for completeness), the compile will fail initially because you are missing the dependency jar files
from the project classpath.
Finally, open the /lib
folder in Eclipse, right click
on each required jar file
and choose Build Path->Add
to build path.
That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it.
The problem is from regional Options . The decimal separator in win 7 for european countries is coma . You have to open Control Panel -> Regional and Language Options -> Aditional Settings -> Decimal Separator : click to enter a dot (.) and to List Separator enter a coma (,) . This is !
I had the same issue when updating a record. Inside the save() i was prepping the rawdata taken from the form to match the database format (doing a lot of mapping of enums values, etc), and this intermittently cancels the put request. i resolved it by taking out the data prepping from the save() and creating a dedicated dataPrep() method out of it. I turned this dataPrep into async and await all the memory intensive data conversion. I then return the prepped data to the save() method that i could use in the http put client. I made sure i await on dataPrep() before calling the put method:
await dataToUpdate = await dataPrep(); http.put(apiUrl, dataToUpdate);
This solved the intermittent cancelling of request.
Textdistance:
TextDistance – python library for comparing distance between two or more sequences by many algorithms. It has Textdistance
Example1:
import textdistance
textdistance.hamming('test', 'text')
Output:
1
Example2:
import textdistance
textdistance.hamming.normalized_similarity('test', 'text')
Output:
0.75
Thanks and Cheers!!!
you could also grep the line out and then cut it like for instance:
grep 'text' filename | cut -c 1-5
In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.
Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:
Database.php
class Database {
private static $connection;
private static $current_query;
...
public static function query($sql) {
if (!self::$connection){
self::open_connection();
}
self::$current_query = $sql;
$result = mysql_query($sql,self::$connection);
if (!$result){
self::close_connection();
// throw custom error
// The query failed for some reason. here is query :: self::$current_query
$error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
$error->handleError();
}
return $result;
}
....
public static function find_by_sql($sql){
if (!is_string($sql))
return false;
$result_set = self::query($sql);
$obj_arr = array();
while ($row = self::fetch_array($result_set))
{
$obj_arr[] = self::instantiate($row);
}
return $obj_arr;
}
}
Table object classL
class DomainPeer extends Database {
public static function getDomainInfoList() {
$sql = 'SELECT ';
$sql .='d.`id`,';
$sql .='d.`name`,';
$sql .='d.`shortName`,';
$sql .='d.`created_at`,';
$sql .='d.`updated_at`,';
$sql .='count(q.id) as queries ';
$sql .='FROM `domains` d ';
$sql .='LEFT JOIN queries q on q.domainId = d.id ';
$sql .='GROUP BY d.id';
return self::find_by_sql($sql);
}
....
}
I hope this example helps you create a good structure.
For Eclipse (Helios) the following procedure works - I've tried it:
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.
use a static defaultProps like:
export default class AddAddressComponent extends Component {
static defaultProps = {
provinceList: [],
cityList: []
}
render() {
let {provinceList,cityList} = this.props
if(cityList === undefined || provinceList === undefined){
console.log('undefined props')
}
...
}
AddAddressComponent.contextTypes = {
router: React.PropTypes.object.isRequired
}
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
}
AddAddressComponent.propTypes = {
userInfo: React.PropTypes.object,
cityList: PropTypes.array.isRequired,
provinceList: PropTypes.array.isRequired,
}
Taken from: https://github.com/facebook/react-native/issues/1772
If you wish to check the types, see how to use PropTypes in treyhakanson's or Ilan Hasanov's answer, or review the many answers in the above link.
In addition to Optimize Imports
and Auto Import
, which were pointed out by @dave-newton and @ryan-stewart in earlier answers, go to:
File menu > Settings > Code Style > Java > Imports
File menu > Settings > Editor > Code Style > Java > Imports
(thanks to @mathias-bader for the hint!)
There you can fine tune the grouping and order or imports, "Class count to use import with '*'
", etc.
Note:
since IDEA 13 you can configure the project default settings from the IDEA "start page": Configure > Project defaults > Settings > ...
. Then every new project will have those default settings:
The size of an array is static in C++. You cannot dynamically resize it. That's what std::vector
is for:
std::vector<int> v; // size of the vector starts at 0
v.push_back(10); // v now has 1 element
v.push_back(20); // v now has 2 elements
v.push_back(30); // v now has 3 elements
v.pop_back(); // removes the 30 and resizes v to 2
v.resize(v.size() - 1); // resizes v to 1
Using Random function to generate number and iterating them on al
using for loop
ArrayList<Integer> al=new ArrayList<Integer>(5);
for (int i=0;i<=4;i++){
Random rand=new Random();
al.add(i,rand.nextInt(100));
System.out.println(al);
}
System.out.println(al.size());
I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.
For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.
Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.
http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html
git --work-tree=/tmp/files_without_dot_git clone --depth=1 \
https://git.yourgit.your.com/myawesomerepo.git \
/tmp/deleteme_contents_of_dot_git
Both the directories in /tmp are created on the fly. No need to pre-create these.
This is what I did, and it works for me.
step 1: add this in the build.grade(module: app)
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
step 2: sync the project and done.
When I coded C++ for a living I consted everything I possibly could. Using const is a great way to help the compiler help you. For instance, const-ing your method return values can save you from typos such as:
foo() = 42
when you meant:
foo() == 42
If foo() is defined to return a non-const reference:
int& foo() { /* ... */ }
The compiler will happily let you assign a value to the anonymous temporary returned by the function call. Making it const:
const int& foo() { /* ... */ }
Eliminates this possibility.
In my case all the dependencies were already there. Please update NPM in that case as it might have been crashed. It solved my problem.
npm install -g npm
To renew the development profile before it expired, I finally found a way that works for me. I boldfaced the steps I had been missing before.
Go to the Apple provisioning portal, select "Provisioning". You'll get a list "Development Provisioning Profiles" where you'll see your soon to expire profile with the label "Managed by XCode". Click the "New Profile" button on top, select the type of profile you want and create it. Wait half a minute, refresh the home screen and when it shows the new profile as "Active", switch back to XCode, go to the Organizer, select "Provisioning profiles" under "Library" in left top column. Click "Refresh" at the bottom, log in (if it asks) and the new profile appears in the list after a short while.
Now, crucially, connect your device and drag your new profile to the "Provisioning Profiles" row under the connected device in the left column.
Finally, you can clean up the old profiles from your device if you feel like it.
Note: interestingly, it seems that simply marking and deleting your provisioning profile on the iOS Provisioning Portal site causes a new fresh Team Provisioning Profile to be created. So maybe that is all that is needed. I will try that next time to see if that is enough, if so you don't need to create a profile as I described above.
You can disable caching globally using $.ajaxSetup()
, for example:
$.ajaxSetup({ cache: false });
This appends a timestamp to the querystring when making the request. To turn cache off for a particular $.ajax()
call, set cache: false
on it locally, like this:
$.ajax({
cache: false,
//other options...
});
Add the function:
function scrollToForm() {
document.querySelector('#form').scrollIntoView({behavior: 'smooth'});
}
Trigger the function:
<a href="javascript: scrollToForm();">Jump to form</a>
For int64_t
type:
#include <inttypes.h>
int64_t t;
printf("%" PRId64 "\n", t);
for uint64_t
type:
#include <inttypes.h>
uint64_t t;
printf("%" PRIu64 "\n", t);
you can also use PRIx64
to print in hexadecimal.
cppreference.com has a full listing of available macros for all types including intptr_t
(PRIxPTR
). There are separate macros for scanf, like SCNd64
.
A typical definition of PRIu16 would be "hu"
, so implicit string-constant concatenation happens at compile time.
For your code to be fully portable, you must use PRId32
and so on for printing int32_t
, and "%d"
or similar for printing int
.
You can make a div that contains both the form & the button, then make the div float to the right by setting float: right;
.
You can call the super class's constructor like this
class A(object):
def __init__(self, number):
print "parent", number
class B(A):
def __init__(self):
super(B, self).__init__(5)
b = B()
NOTE:
This will work only when the parent class inherits object
You can't compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day).
You can check if now is before or after today's 8am:
>>> import datetime
>>> now = datetime.datetime.now()
>>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
>>> now < today8am
True
>>> now == today8am
False
>>> now > today8am
False
The issue is that the original axiosTest()
function isn't returning the promise. Here's an extended explanation for clarity:
function axiosTest() {
// create a promise for the axios request
const promise = axios.get(url)
// using .then, create a new promise which extracts the data
const dataPromise = promise.then((response) => response.data)
// return it
return dataPromise
}
// now we can use that data from the outside!
axiosTest()
.then(data => {
response.json({ message: 'Request received!', data })
})
.catch(err => console.log(err))
The function can be written more succinctly:
function axiosTest() {
return axios.get(url).then(response => response.data)
}
Or with async/await:
async function axiosTest() {
const response = await axios.get(url)
return response.data
}
Here is another possibility, again with Java 8 Streams:
void intArrayToListOfIntegers(int[] arr, List<Integer> list) {
IntStream.range(0, arr.length).forEach(i -> list.add(arr[i]));
}
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
I think COALESCE
function partially similar to the isnull
, but try it.
Why don't you go for null handling functions through application programs, it is better alternative.
May be you are missing Third party library
to like actionBarSherlock, slidingMenu, achartengine
Add it into lib
folder and Add to Build Path
..
Its work for me.
Try this
Get-ChildItem | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }
In your code,
$build-Config
is not a valid variable name. $.FullName
should be $_.FullName
$
should be $_.Name
My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity
, call finish()
. When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.
using System.Windows.Forms;
public class message
{
static void Main()
{
MessageBox.Show("Hello World!");
}
}
If you're fine with using the std c library:
#include <sys/stat.h>
off_t fsize(char *file) {
struct stat filestat;
if (stat(file, &filestat) == 0) {
return filestat.st_size;
}
return 0;
}
UPDATE yourtable
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern')
WHERE 1
The accepted answer definitely works, but somehow miss an important point.
The OP is asking for a dictionary sorted by it's keys
this is just not really possible and not what OrderedDict
is doing.
OrderedDict is maintaining the content of the dictionary in insertion order. First item inserted, second item inserted, etc.
>>> d = OrderedDict()
>>> d['foo'] = 1
>>> d['bar'] = 2
>>> d
OrderedDict([('foo', 1), ('bar', 2)])
>>> d = OrderedDict()
>>> d['bar'] = 2
>>> d['foo'] = 1
>>> d
OrderedDict([('bar', 2), ('foo', 1)])
Hencefore I won't really be able to sort the dictionary inplace, but merely to create a new dictionary where insertion order match key order. This is explicit in the accepted answer where the new dictionary is b.
This may be important if you are keeping access to dictionaries through containers. This is also important if you itend to change the dictionary later by adding or removing items: they won't be inserted in key order but at the end of dictionary.
>>> d = OrderedDict({'foo': 5, 'bar': 8})
>>> d
OrderedDict([('foo', 5), ('bar', 8)])
>>> d['alpha'] = 2
>>> d
OrderedDict([('foo', 5), ('bar', 8), ('alpha', 2)])
Now, what does mean having a dictionary sorted by it's keys ? That makes no difference when accessing elements by keys, this only matter when you are iterating over items. Making that a property of the dictionary itself seems like overkill. In many cases it's enough to sort keys() when iterating.
That means that it's equivalent to do:
>>> d = {'foo': 5, 'bar': 8}
>>> for k,v in d.iteritems(): print k, v
on an hypothetical sorted by key dictionary or:
>>> d = {'foo': 5, 'bar': 8}
>>> for k, v in iter((k, d[k]) for k in sorted(d.keys())): print k, v
Of course it is not hard to wrap that behavior in an object by overloading iterators and maintaining a sorted keys list. But it is likely overkill.
References are not pointers.
8.3.2/1:
A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]
1.9/4:
Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer)
As Johannes says in a deleted answer, there's some doubt whether "dereferencing a null pointer" should be categorically stated to be undefined behavior. But this isn't one of the cases that raise doubts, since a null pointer certainly does not point to a "valid object or function", and there is no desire within the standards committee to introduce null references.
Much has changed since this question was asked. Visual Studio 2013 with update 4 and Visual Studio 2015 now have integrated tools for Apache Cordova and you can run them on a Visual Studio emulator for Android.
Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Of course, you can run the program as java Hello
and you will see the message; however, the command will also fail with a message stating:
Exception in thread "main" java.lang.NoSuchMethodError: main
[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0)
immediately after printing the message.
As of JDK6 onward, you no longer see the message from the static
initializer block; details here.
Try the solution from Reportlab.
Download it and install it as usual with python setup.py install
You will also need to install the following modules: xhtml2pdf, html5lib, pypdf with easy_install.
Here is an usage example:
First define this function:
import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
Then you can use it like this:
def myview(request):
#Retrieve data or whatever you need
return render_to_pdf(
'mytemplate.html',
{
'pagesize':'A4',
'mylist': results,
}
)
The template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Title</title>
<style type="text/css">
@page {
size: {{ pagesize }};
margin: 1cm;
@frame footer {
-pdf-frame-content: footerContent;
bottom: 0cm;
margin-left: 9cm;
margin-right: 9cm;
height: 1cm;
}
}
</style>
</head>
<body>
<div>
{% for item in mylist %}
RENDER MY CONTENT
{% endfor %}
</div>
<div id="footerContent">
{%block page_foot%}
Page <pdf:pagenumber>
{%endblock%}
</div>
</body>
</html>
Hope it helps.
First of all, check out my post on retained Fragments. It might help.
Now to answer your questions:
Does the fragment also retain its
viewstate, or will this be recreated on configuration change - what exactly is "retained"?
Yes, the Fragment
's state will be retained across the configuration change. Specifically, "retained" means that the fragment will not be destroyed on configuration changes. That is, the Fragment
will be retained even if the configuration change causes the underlying Activity
to be destroyed.
Will the fragment be destroyed when the user leaves the activity?
Just like Activity
s, Fragment
s may be destroyed by the system when memory resources are low. Whether you have your fragments retain their instance state across configuration changes will have no effect on whether or not the system will destroy the Fragment
s once you leave the Activity
. If you leave the Activity
(i.e. by pressing the home button), the Fragment
s may or may not be destroyed. If you leave the Activity
by pressing the back button (thus, calling finish()
and effectively destroying the Activity
), all of the Activity
s attached Fragment
s will also be destroyed.
Why doesn't it work with fragments on the back stack?
There are probably multiple reasons why it's not supported, but the most obvious reason to me is that the Activity
holds a reference to the FragmentManager
, and the FragmentManager
manages the backstack. That is, no matter if you choose to retain your Fragment
s or not, the Activity
(and thus the FragmentManager
's backstack) will be destroyed on a configuration change. Another reason why it might not work is because things might get tricky if both retained fragments and non-retained fragments were allowed to exist on the same backstack.
Which are the use cases where it makes sense to use this method?
Retained fragments can be quite useful for propagating state information — especially thread management — across activity instances. For example, a fragment can serve as a host for an instance of Thread
or AsyncTask
, managing its operation. See my blog post on this topic for more information.
In general, I would treat it similarly to using onConfigurationChanged
with an Activity
... don't use it as a bandaid just because you are too lazy to implement/handle an orientation change correctly. Only use it when you need to.
You can do that, or you can use the readfile
function, which outputs it for you:
header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();
Edit: Derp, fixed obvious glaring typo.
usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats
plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)
Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.
require(plyr)
require(dostats)
files <- list.files(pattern = ".csv")
for (i in seq_along(files)) {
assign(paste("Df", i, sep = "."), read.csv(files[i]))
assign(paste(paste("Df", i, sep = ""), "summary", sep = "."),
ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))
}
Here is the output
R> Df1.summary
.id sum min mean median max
1 A 34 4 5.6667 5.5 8
2 B 22 1 3.6667 3.0 9
R> Df2.summary
.id sum min mean median max
1 A 21 1 3.5000 3.5 6
2 B 16 1 2.6667 2.5 5
Try this:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';
};
</script>
Here is a working jsFiddle
You do not embed the images in the bundle. They are called through the browser. So its;
var imgSrc = './image/image1.jpg';
return <img src={imgSrc} />
In theory, maven does not allow to use a property to set a parent version.
In your case, maven can simply not figure out that the 0.0.1-SNAPSHOT version of your parent pom is the one that is currently in your project, and so it tries to find it in your local repo. It probably finds one since it is a snapshot, but it is an old version that probably not contains your Dependency Management section.
There is a workaround though :
Simply change the parent section in the child pom with this :
<parent>
<groupId>com.sw.system4</groupId>
<artifactId>system4-parent</artifactId>
<version>${system4.version}</version>
<relativePath>../pom.xml</relativePath> <!-- this must match your parent pom location -->
</parent>
Maybe it's better to use links
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
How to create a link to a directory
Hint: If you need not to see the link in your home you can start it with a dot . ; then it will be hidden by default then you can access it like
cd ~/.myHiddelLongDirLink
To give an example to what Alex said, if you're using Magento, for example, .phtml files are only to be found in the /design area as template files, and contain both HTML and PHP lines. Meanwhile the PHP files are pure code and don't have any lines of HTML in them.
Store it either in a cookie (if it's acceptable for your situation), or in a session variable.
session_start();
if ( !isset( $_SESSION["origURL"] ) )
$_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];
It means that the callback function you passed to this.dataStore.data.find
should return a boolean and have 3 parameters, two of which can be optional:
However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:
this.dataStore.data.find((element, index, obj) => {
// ...
return true; // or false
});
or:
this.dataStore.data.find(element => {
// ...
return true; // or false
});
Reason why it's this way: the function you pass to the find
method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find
method can determine which value to find.
In practice, this means that the predicate is called for each item in data
, and the first item in data
for which your predicate returns true
is the value returned by find
.
My solution:
int mkrdir(const char *path, int index, int permission)
{
char bf[NAME_MAX];
if(*path == '/')
index++;
char *p = strchr(path + index, '/');
int len;
if(p) {
len = MIN(p-path, sizeof(bf)-1);
strncpy(bf, path, len);
bf[len]=0;
} else {
len = MIN(strlen(path)+1, sizeof(bf)-1);
strncpy(bf, path, len);
bf[len]=0;
}
if(access(bf, 0)!=0) {
mkdir(bf, permission);
if(access(bf, 0)!=0) {
return -1;
}
}
if(p) {
return mkrdir(path, p-path+1, permission);
}
return 0;
}
Function FileExists(fullFileName As String) As Boolean
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
how to convert JTextField to string and string to JTextField in java
If you mean how to get and set String from jTextField then you can use following methods:
String str = jTextField.getText() // get string from jtextfield
and
jTextField.setText(str) // set string to jtextfield
//or
new JTextField(str) // set string to jtextfield
You should check JavaDoc for JTextField
You can simply use below method
/**
* Replace all the occerencess of $find by $replace in $originalString
* @param {originalString} input - Raw string.
* @param {find} input - Target key word or regex that need to be replaced.
* @param {replace} input - Replacement key word
* @return {String} Output string
*/
function replaceAll(originalString, find, replace) {
return originalString.replace(new RegExp(find, 'g'), replace);
};
Try the code below. e.preventDefault() was added. This removes the default event action for the form.
$(document).ready(function () {
$("form").submit(function (e) {
$.ajax({
url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
data: { id: '@Model.ClientId' },
success: function (data) {
showMsg(data, e);
},
cache: false
});
e.preventDefault();
});
});
Also, you mentioned you wanted the form to not submit under the premise of validation, but I see no code validation here?
Here is an example of some added validation
$(document).ready(function () {
$("form").submit(function (e) {
/* put your form field(s) you want to validate here, this checks if your input field of choice is blank */
if(!$('#inputID').val()){
e.preventDefault(); // This will prevent the form submission
} else{
// In the event all validations pass. THEN process AJAX request.
$.ajax({
url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
data: { id: '@Model.ClientId' },
success: function (data) {
showMsg(data, e);
},
cache: false
});
}
});
});
[Edit]
If you are doing this to trim the beginning of a log file, you can avoid loading the entire file by doing something like this:
// count the number of lines in the file
int count = 0;
using (var sr = new StreamReader("file.txt"))
{
while (sr.ReadLine() != null)
count++;
}
// skip first (LOG_MAX - count) lines
count = LOG_MAX - count;
using (var sr = new StreamReader("file.txt"))
using (var sw = new StreamWriter("output.txt"))
{
// skip several lines
while (count > 0 && sr.ReadLine() != null)
count--;
// continue copying
string line = "";
while ((line = sr.ReadLine()) != null)
sw.WriteLine(line);
}
First of all, since File.ReadAllLines
loads the entire file into a string array (string[]
), copying to a list is redundant.
Second, you must understand that a List
is implemented using a dynamic array under the hood. This means that CLR will need to allocate and copy several arrays until it can accommodate the entire file. Since the file is already on disk, you might consider trading speed for memory and working on disk data directly, or processing it in smaller chunks.
If you need to load it entirely in memory, at least try to leave in an array:
string[] lines = File.ReadAllLines("file.txt");
If it really needs to be a List
, load lines one by one:
List<string> lines = new List<string>();
using (var sr = new StreamReader("file.txt"))
{
while (sr.Peek() >= 0)
lines.Add(sr.ReadLine());
}
Note: List<T>
has a constructor which accepts a capacity parameter. If you know the number of lines in advance, you can prevent multiple allocations by preallocating the array in advance:
List<string> lines = new List<string>(NUMBER_OF_LINES);
Even better, avoid storing the entire file in memory and process it "on the fly":
using (var sr = new StreamReader("file.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// process the file line by line
}
}
You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.
Here's the version like the ggplot2 one I gave only in base R. I copied some from @nullglob.
generate the data
carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)
You don't need to put it into a data frame like with ggplot2. The drawback of this method is that you have to write out a lot more of the details of the plot. The advantage is that you have control over more details of the plot.
## calculate the density - don't plot yet
densCarrot <- density(carrots)
densCuke <- density(cukes)
## calculate the range of the graph
xlim <- range(densCuke$x,densCarrot$x)
ylim <- range(0,densCuke$y, densCarrot$y)
#pick the colours
carrotCol <- rgb(1,0,0,0.2)
cukeCol <- rgb(0,0,1,0.2)
## plot the carrots and set up most of the plot parameters
plot(densCarrot, xlim = xlim, ylim = ylim, xlab = 'Lengths',
main = 'Distribution of carrots and cucumbers',
panel.first = grid())
#put our density plots in
polygon(densCarrot, density = -1, col = carrotCol)
polygon(densCuke, density = -1, col = cukeCol)
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
fill = c(carrotCol, cukeCol), bty = 'n',
border = NA)
Mine is using macros instead of searches - combining a macro with visual mode is sometimes more efficient.
This is very classic case: If you end up having to check for any data provided by the http instance then consider moving that code under the BeginRequest
event.
void Application_BeginRequest(Object source, EventArgs e)
This is the right place to check for http headers, query string and etc...
Application_Start
is for the settings that apply for the application entire run time, such as routing, filters, logging and so on.
Please, don't apply any workarounds such as static .ctor or switching to the Classic mode unless there's no way to move the code from the Start
to BeginRequest
. that should be doable for the vast majority of your cases.
i Did it, just follow this tutorial. helps a lot
Is a copy from javadb (because is down)
http://informatictips.blogspot.pt/2013/09/using-message-handler-to-alter-soap.html
or
http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client
I solve this problem with the line below:
cordova plugin add cordova-android-support-gradle-release --save
After that the compile was succesful.
DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 },
u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]}
def convert(data):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, collections.Mapping):
return dict(map(convert, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(convert, data))
else:
return data
print DATA
print convert(DATA)
# Prints:
# {u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])], u'foo': frozenset([u'Gah!']), u'bar': {u'baz': 97}, u'spam': u'eggs'}
# {'bar': {'baz': 97}, 'foo': frozenset(['Gah!']), 'list': ['list', (True, 'Maybe'), set(['and', 'a', 'set', 1])], 'spam': 'eggs'}
Assumptions:
data.encode('utf-8')
rather than str(data)
if you need an explicit encoding).If you need to support other container types, hopefully it's obvious how to follow the pattern and add cases for them.
I was facing the same problem where increasing max size in php.ini
has no effect on wordpress and tried many solutions like -:
functions.php
.htaccess
file.The one that worked for me is adding max size in .htaccess
file.
It wasn't working with neither with php.ini
file nor with functions.php
file.
I just did add this code in .htaccess
file and its done
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300
NOTE: I did add above code in <IfModule>
tag.
If php.ini
file is not doing anything in changing size then try other 2 files for it and one of them will surely work for you.
READ THIS ARTICLE TO KNOW ABOUT ALL FILES IN WHICH YOU CAN INCREASE MAX SIZE
To add to the accepted answer, I had a similar issue and solved it using a similar approach with the contrived example below. In this case I needed to log some parameters on componentWillUnmount
and as described in the original question I didn't want it to log every time the params changed.
const componentWillUnmount = useRef(false)
// This is componentWillUnmount
useEffect(() => {
return () => {
componentWillUnmount.current = true
}
}, [])
useEffect(() => {
return () => {
// This line only evaluates to true after the componentWillUnmount happens
if (componentWillUnmount.current) {
console.log(params)
}
}
}, [params]) // This dependency guarantees that when the componentWillUnmount fires it will log the latest params
You can do it using only the shell, no need for tr
or sed
$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
From the fine manual.
You must own the table to use ALTER TABLE.
Or be a database superuser.
ERROR: must be owner of relation contact
PostgreSQL error messages are usually spot on. This one is spot on.
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
Simply follow the below steps specific to mac:
go to:
/Users/{username}/Library/Android/sdk/emulator
./emulator -list-avds
./emulator @avdName
NewsViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tbl_View deselectRowAtIndexPath:indexPath animated:YES];
News *newsObj = [newstitleArr objectAtIndex:indexPath.row];
NewsDetailViewController *newsDetailView = [[NewsDetailViewController alloc] initWithNibName:@"NewsDetailViewController" bundle:nil];
newsDetailView.newsHeadlineStr = newsObj.newsHeadline;
[self.navigationController pushViewController:newsDetailView animated:YES];
}
NewsDetailViewController.h
@interface NewsDetailViewController : UIViewController
@property(nonatomic,retain) NSString *newsHeadlineStr;
@end
NewsDetailViewController.m
@synthesize newsHeadlineStr;
I just use:
$('body').animate({ 'scrollTop': '-=-'+<yourValueScroll>+'px' }, 2000);
_x000D_
Adding to @ud_an
It is not a good practice to create different folders for layouts. Create your layout such that it works fine with all the screen sizes. To achieve this, play with the layout attributes. You only need to have different images for hdpi, mdpi and ldpi types. The rest will be managed by android OS.
It's easy,this is my solution using objects!
My POJO
public class Person implements Serializable{
private String name;
private int age;
//get & set
}
Method Notification
Person person = new Person();
person.setName("david hackro");
person.setAge(10);
Intent notificationIntent = new Intent(this, Person.class);
notificationIntent.putExtra("person",person);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.notification_icon)
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.ColorTipografiaAdeudos))
.setPriority(2)
.setLargeIcon(bm)
.setTicker(fotomulta.getTitle())
.setContentText(fotomulta.getMessage())
.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT))
.setWhen(System.currentTimeMillis())
.setContentTitle(fotomulta.getTicketText())
.setDefaults(Notification.DEFAULT_ALL);
New Activity
private Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_push);
person = (Person) getIntent().getSerializableExtra("person");
}
Good Luck!!
git diff > patchfile
and
patch -p1 < patchfile
work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile
if you need handle file adds, deletes and renames.
EDIT December 2015
Latest versions of patch
command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).
So provided one uses current/latest version of patch
there is no need to use git
to be able to apply its diff as a patch.
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
My question is when should a use a double and when should I use a decimal type?
decimal
for when you work with values in the range of 10^(+/-28) and where you have expectations about the behaviour based on base 10 representations - basically money.
double
for when you need relative accuracy (i.e. losing precision in the trailing digits on large values is not a problem) across wildly different magnitudes - double
covers more than 10^(+/-300). Scientific calculations are the best example here.
which type is suitable for money computations?
decimal, decimal, decimal
Accept no substitutes.
The most important factor is that double
, being implemented as a binary fraction, cannot accurately represent many decimal
fractions (like 0.1) at all and its overall number of digits is smaller since it is 64-bit wide vs. 128-bit for decimal
. Finally, financial applications often have to follow specific rounding modes (sometimes mandated by law). decimal
supports these; double
does not.
The URL should be a string:
import urllib
link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)
myfile = f.readline()
print myfile
If your request doesn't specify an Origin
header, S3 won't include the CORS headers in the response. This really threw me because I kept trying to curl the files to test the CORS but curl doesn't include Origin
.
Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.
function changeCss(className, classValue) {
var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length == 0) {
var cssMainContainer = $('<style id="css-modifier-container"></style>');
cssMainContainer.appendTo($('head'));
}
cssMainContainer.append(className + " {" + classValue + "}\n");
}
For those scripting tmux, there is a command called rename-window
so e.g.
tmux rename-window -t <window> <newname>
The .size()
function is available in Jquery and many other libraries.
The .length
property works only when the index is an integer.
The length
property will work with this type of array:
var nums = new Array();
nums[0] = 1;
nums[1] = 2;
print(nums.length); // displays 2
The length
property won't work with this type of array:
var pbook = new Array();
pbook["David"] = 1;
pbook["Jennifer"] = 2;
print(pbook.length); // displays 0
So in your case you should be using the .length
property.
In ASP.NET MVC 3 you can simply add your list to ViewData...
var options = new List<SelectListItem>();
options.Add(new SelectListItem { Value = "1", Text = "1" });
options.Add(new SelectListItem { Value = "2", Text = "2" });
options.Add(new SelectListItem { Value = "3", Text = "3", Selected = true });
ViewData["options"] = options;
...and then reference it by name in your razor view...
@Html.DropDownList("options")
You don't have to manually "use" the list in the DropDownList call. Doing it this way correctly set the selected value for me too.
Disclaimer:
This is the method Google themselves use in at least one sample:
var markers = [];
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
Check Google sample for complete code example:
https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
Not sure if Access supports it, but in most engines (including SQL Server
) this is called a correlated subquery and works fine:
SELECT TypesAndBread.Type, TypesAndBread.TBName,
(
SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
FROM Sandwiches
WHERE (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
) As SandwichCount
FROM TypesAndBread
This can be made more efficient by indexing Type
and Bread
and distributing the subqueries over the UNION
:
SELECT [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
)
FROM [Sandwiches Types]
UNION ALL
SELECT [Breads].[Bread] As TBName, "Bread" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Bread = [Breads].[Bread]
)
FROM [Breads]
Press ESC to first go into command mode
. Then Press Shift+D.
If you dig into NSInteger's implementation:
#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
Simply, the NSInteger typedef does a step for you: if the architecture is 32-bit, it uses int
, if it is 64-bit, it uses long
. Using NSInteger, you don't need to worry about the architecture that the program is running on.
echo $this->bb;
The variable is inherited and is not private, so it is a part of the current object.
Here is additional information in response to your request for more information about using parent::
:
Use parent::
when you want add extra functionality to a method from the parent class. For example, imagine an Airplane
class:
class Airplane {
private $pilot;
public function __construct( $pilot ) {
$this->pilot = $pilot;
}
}
Now suppose we want to create a new type of Airplane that also has a navigator. You can extend the __construct() method to add the new functionality, but still make use of the functionality offered by the parent:
class Bomber extends Airplane {
private $navigator;
public function __construct( $pilot, $navigator ) {
$this->navigator = $navigator;
parent::__construct( $pilot ); // Assigns $pilot to $this->pilot
}
}
In this way, you can follow the DRY principle of development but still provide all of the functionality you desire.
The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):
>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True
Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.
Using the DB2 commands (no SQL) there is the possibility of executing
db2 LIST TABLES FOR ALL
This shows all the tables in all the schemas in the database.
select distinct title, (
select count(title)
from kmovies as sub
where sub.title=kmovies.title) as cnt
from kmovies
group by title
order by cnt desc
You want the file module. To create a directory, you need to specify the option state=directory
:
- name: Creates directory
file:
path: /src/www
state: directory
You can see other options at https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html
Range("$A$1").Value = "'01/01/13 00:00"
will do it.
Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.
for MacOS, make sure you know where the GO install
export GOPATH=/usr/local/go
PATH=$PATH:$GOPATH/bin
Since the question was asking how to do this with JS I'm providing a vanilla JS implementation.
var element = document.querySelector(".your-element-class-goes-here");
// it's a good idea to check whether the element exists
if (element != null && element != undefined) {
element.disabled = "disabled";
}
_x000D_
You can prevent tables from expanding beyond their parent div by using table-layout:fixed
.
The CSS below will make your tables expand to the width of the div surrounding it.
table
{
table-layout:fixed;
width:100%;
}
I found this trick here.
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
To match either / or end of content, use (/|\z)
This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).
To put that with an updated version of what you had:
/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)
Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+?
) rather than matching anything and everything ( .*
)
In Python3
pip list
Empty venv is
Package Version
---------- -------
pip 19.2.3
setuptools 41.2.0
To start a new environment
python3 -m venv your_foldername_here
Activate
cd your_foldername_here
source bin/activate
Deactivate
deactivate
You can also stand in the folder and give the virtual environment a name/folder (python3 -m venv name_of_venv).
Venv is a subset of virtualenv that is shipped with Python after 3.3.
You can use either of the two statements below:
numpy.mean(df['col_name'])
# or
df['col_name'].mean()
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
I came up with this simple and elegant solution. It assumes that the activity is responsible for creating the Fragments, and the Adapter just serves them.
This is the adapter's code (nothing weird here, except for the fact that mFragments
is a list of fragments maintained by the Activity)
class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public CharSequence getPageTitle(int position) {
TabFragment fragment = (TabFragment)mFragments.get(position);
return fragment.getTitle();
}
}
The whole problem of this thread is getting a reference of the "old" fragments, so I use this code in the Activity's onCreate.
if (savedInstanceState!=null) {
if (getSupportFragmentManager().getFragments()!=null) {
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
mFragments.add(fragment);
}
}
}
Of course you can further fine tune this code if needed, for example making sure the fragments are instances of a particular class.
I have done with below single git command:
git clone [url] -b [branch-name] --single-branch
When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.
To enforce the desired gem version you take the help of bundle exec
command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.
I have also written a post about it which also shows how we can avoid using it using bin stubs.
The most simple and the correct way is to use Record type Record<string, string>
const myVar : Record<string, string> = {
key1: 'val1',
key2: 'val2',
}
<!-- HTML -->
<a href="#google"></a>
<div id="google"></div>
/*CSS*/
html { scroll-behavior: smooth; }
Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.
You've an number of options, depending on how you want to play it:
isNaN(val)
Returns true if val is not a number, false if it is. In your case, this is probably what you need.
isFinite(val)
Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity
/^\d+$/.test(val)
Returns true if val, when cast to a String, has only digits (probably not what you need).
I got this issue after running the google-cloud-sdk
install script, which adds command-completion to the shell via an entry in .zshrc
.
Following Homebrew's instructions for configuring completions in zsh was helpful.
Additionally, if you receive “zsh compinit: insecure directories” warnings when attempting to load these completions, you may need to run this:
chmod -R go-w "$(brew --prefix)/share"
function check (list){
var foundRepeatingValue = false;
var newList = [];
for(i=0;i<list.length;i++){
var thisValue = list[i];
if(i>0){
if(newList.indexOf(thisValue)>-1){
foundRepeatingValue = true;
console.log("getting repeated");
return true;
}
} newList.push(thisValue);
} return false;
}
var list1 = ["dse","dfg","dse"];
check(list1);
Output:
getting repeated
true
label = new JLabel("A label");
label.setFont(new Font("Serif", Font.PLAIN, 14));
taken from How to Use HTML in Swing Components
For large text, the full text index is much faster. But you can full text index varchar(max)
as well.
Just Add these 2 permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your app's AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.networkusage"
...>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
...>
...
</application>
</manifest>
Happy Coding:)
I'm using the objectMapper. Every Rest Service is mostly working with json, and in one of your configs you have already configured an object mapper.
Code is written in Kotlin, hopefully it will be ok.
@Bean
fun objectMapper(): ObjectMapper {
val objectMapper = ObjectMapper()
objectMapper.registerModule(JodaModule())
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
return objectMapper
}
class UnauthorizedAuthenticationEntryPoint : BasicAuthenticationEntryPoint() {
@Autowired
lateinit var objectMapper: ObjectMapper
@Throws(IOException::class, ServletException::class)
override fun commence(request: HttpServletRequest, response: HttpServletResponse, authException: AuthenticationException) {
response.addHeader("Content-Type", "application/json")
response.status = HttpServletResponse.SC_UNAUTHORIZED
val responseError = ResponseError(
message = "${authException.message}",
)
objectMapper.writeValue(response.writer, responseError)
}}
After commenting @Marcin answer, I have more carefully checked one of my students code where I found the same weird behavior, even after only 2 epochs ! (So @Marcin's explanation was not very likely in my case).
And I found that the answer is actually very simple: the accuracy computed with the Keras method evaluate
is just plain wrong when using binary_crossentropy with more than 2 labels. You can check that by recomputing the accuracy yourself (first call the Keras method "predict" and then compute the number of correct answers returned by predict): you get the true accuracy, which is much lower than the Keras "evaluate" one.
Change detection is not triggered when you change a property of an object (including nested object). One solution would be to reassign a new object reference using 'lodash' clone() function.
import * as _ from 'lodash';
this.foo = _.clone(this.foo);
For .Net 4 use:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
Although this question is quite old, and the accepted response is valid, I find it a bit unconfortable because the content of the HTTP response (HTML, XML, JSON, binary or whatever) becomes mixed with the headers.
I've found a different alternative. CURL provides an option (CURLOPT_HEADERFUNCTION
) to set a callback that will be called for each response header line. The function will receive the curl object and a string with the header line.
You can use a code like this (adapted from TML response):
$cookies = Array();
$ch = curl_init('http://www.google.com/');
// Ask for the callback.
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$result = curl_exec($ch);
var_dump($cookies);
function curlResponseHeaderCallback($ch, $headerLine) {
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
$cookies[] = $cookie;
return strlen($headerLine); // Needed by curl
}
This solution has the drawback of using a global variable, but I guess this is not an issue for short scripts. And you can always use static methods and attributes if curl is being wrapped into a class.
you have a package.json file that shows the main configuration of your project, and a lockfile that contains the full details of your project configuration such as the urls that holds each of the package or libraries used in your project at the root folder of the project......
npm is the default package manager for Node.js....
All you need to do is call $ npm install
from the terminal in the root directory where you have the package.json and lock file ...since you are not adding any particular package to be install ..... it will go through the lock file and download one after the other, the required packages from their urls written in the lock file if it isnt present in the project enviroment .....
you make sure you edit your package.json file .... to give an entry point to your app..... "name":"app.js"
where app.js is the main script .. or index.js depending on the project naming convention...
then you can run..$ Node app.js
or $ npm start
if your package.json scripts has a start field config as such "scripts": { "start": "Node index.js", "test": "test" }
..... which is indirectly still calling your $ Node app.js
The problem is you haven't declared your interface state replace any with your suitable variable type of the 'value'
interface AppProps {
//code related to your props goes here
}
interface AppState {
value: any
}
class App extends React.Component<AppProps, AppState> {
// ...
}
Best way:
var s = 'String';
var a = [1,2,3];
var o = {key: 'val'};
(s.constructor === String) && console.log('its a string');
(a.constructor === Array) && console.log('its an array');
(o.constructor === Object) && console.log('its an object');
(o.constructor === Number || s.constructor === Boolean) && console.log('this won\'t run');
Each of these has been constructed by its appropriate class function, like "new Object()" etc.
Also, Duck-Typing: "If it looks like a duck, walks like a duck, and smells like a duck - it must be an Array" Meaning, check its properties.
Hope this helps.
Remember, you can always use combinations of approaches too. Here's an example of using an inline map of actions with typeof:
var type = { 'number': Math.sqrt.bind(Math), ... }[ typeof datum ];
Here's a more 'real world' example of using inline-maps:
function is(datum) {
var isnt = !{ null: true, undefined: true, '': true, false: false, 0: false }[ datum ];
return !isnt;
}
console.log( is(0), is(false), is(undefined), ... ); // >> true true false
This function would use [ custom ] "type-casting" -- rather, "type-/-value-mapping" -- to figure out if a variable actually "exists". Now you can split that nasty hair between null
& 0
!
Many times you don't even care about its type. Another way to circumvent typing is combining Duck-Type sets:
this.id = "998"; // use a number or a string-equivalent
function get(id) {
if (!id || !id.toString) return;
if (id.toString() === this.id.toString()) http( id || +this.id );
// if (+id === +this.id) ...;
}
Both Number.prototype
and String.prototype
have a .toString() method
. You just made sure that the string-equivalent of the number was the same, and then you made sure that you passed it into the http
function as a Number
. In other words, we didn't even care what its type was.
Hope that gives you more to work with :)
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
I know this isn't what's asked but I benefited from this method, when trying to set a variable within a "loop". Uses an array. Alternative implementation option.
SETLOCAL ENABLEDELAYEDEXPANSION
...
set Services[0]=SERVICE1
set Services[1]=SERVICE2
set Services[2]=SERVICE3
set "i=0"
:ServicesLoop
if defined Services[%i%] (
set SERVICE=!Services[%i%]!
echo CurrentService: !SERVICE!
set /a "i+=1"
GOTO :ServicesLoop
)
Try this before anything else - 'clear your cache'. I had the same issue. I was instructed to clear my cache. It worked.
I needed to sort cells with references, and really needed to avoid pasting Values to work with.. The "Pivot Table" did the trick.
Just be sure to right click on Pivot table and hit "refresh" each time you change some generic data (used in your tables).
Hope it will help. Andrei
If anybody is looking for a swift version:
1) Create a custom class for your data
class customData: NSObject, NSCoding {
let name : String
let url : String
let desc : String
init(tuple : (String,String,String)){
self.name = tuple.0
self.url = tuple.1
self.desc = tuple.2
}
func getName() -> String {
return name
}
func getURL() -> String{
return url
}
func getDescription() -> String {
return desc
}
func getTuple() -> (String,String,String) {
return (self.name,self.url,self.desc)
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObjectForKey("name") as! String
self.url = aDecoder.decodeObjectForKey("url") as! String
self.desc = aDecoder.decodeObjectForKey("desc") as! String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.name, forKey: "name")
aCoder.encodeObject(self.url, forKey: "url")
aCoder.encodeObject(self.desc, forKey: "desc")
}
}
2) To save data use following function:
func saveData()
{
let data = NSKeyedArchiver.archivedDataWithRootObject(custom)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(data, forKey:"customArray" )
}
3) To retrieve:
if let data = NSUserDefaults.standardUserDefaults().objectForKey("customArray") as? NSData
{
custom = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [customData]
}
Note: Here I am saving and retrieving an array of the custom class objects.
The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream
. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I would end it with NULL
. Why? Because you can't do either of these:
array[index] == '\0'
array[index] == "\0"
The first one is comparing a char *
to a char
, which is not what you want. You would have to do this:
array[index][0] == '\0'
The second one doesn't even work. You're comparing a char *
to a char *
, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use ==
to compare two strings, you have to use the strcmp()
function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:
array[index] == NULL
Works just fine and conveys your point.
Another option is to use the built in settype function:
<?php
$foo = "5bar"; // string
$bar = true; // boolean
settype($foo, "integer"); // $foo is now 5 (integer)
settype($bar, "string"); // $bar is now "1" (string)
?>
This actually performs a conversion on the variable unlike typecasting and allows you to have a general way of converting to multiple types.
You can always encrypt data on the client side. Please note that not all of the data have to be encrypted because it has a performance issue.
set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"
>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye
:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp
Set values using set commands before above lines.
I believe this helps you.
Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html
You can try
WebElement navigationPageButton = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();
I believe the command line switch you are looking for to pass to curl is -I
.
Example usage:
$ curl -I http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:05 GMT
Server: Apache
Location: http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287/
Content-Type: text/html; charset=iso-8859-1
Additionally, if you encounter a response HTTP status code of 301, you might like to also pass a -L
argument switch to tell curl
to follow URL redirects, and, in this case, print the headers of all pages (including the URL redirects), illustrated below:
$ curl -I -L http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Location: http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287/
Content-Type: text/html; charset=iso-8859-1
HTTP/1.1 302 Found
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Set-Cookie: UID=b8c37e33defde51cf91e1e03e51657da
Location: noaccess.php
Content-Type: text/html
HTTP/1.1 200 OK
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Content-Type: text/html
Here is an option that's easier to extend than yours, but no, there is none built into the library itself.
private static List<string> suffixes = new List<string> { " B", " KB", " MB", " GB", " TB", " PB" };
public static string Foo(int number)
{
for (int i = 0; i < suffixes.Count; i++)
{
int temp = number / (int)Math.Pow(1024, i + 1);
if (temp == 0)
return (number / (int)Math.Pow(1024, i)) + suffixes[i];
}
return number.ToString();
}
You could use Number.toLocaleString()
:
var number = 1557564534;_x000D_
document.body.innerHTML = number.toLocaleString();_x000D_
// 1,557,564,534
_x000D_
Not sure if this is the answer you were looking for, but it worked for me. After spinning my wheels in Windows Firewall, I went back into SQL Server Configuration Manager, checked SQL Server Network Configuration, in the protocols for the instance I was working with look at TCP/IP. By default it seems mine was set to disabled, which allowed for instance connections on the local machine but not using SSMS on another machine. Enabling TCP/IP did the trick for me.
views.py
from django.contrib import messages
def view_name(request):
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks'/)
else:
messages.error(request, "Error")
return render(request, 'page.html', {'form':form_class()})
If you want to show the errors of the form other than that not valid just put {{form.as_p}} like what I did below
page.html
<html>
<head>
<script>
{% if messages %}
{% for message in messages %}
alert('{{message}}')
{% endfor %}
{% endif %}
</script>
</head>
<body>
{{form.as_p}}
</body>
</html>
assertEquals(Object, Object)
from JUnit4/JUnit 5 or assertThat(actual, is(expected));
from Hamcrest proposed in the other answers will work only as both equals()
and toString()
are overrided for the classes (and deeply) of the compared objects.
It matters because the equality test in the assertion relies on equals()
and the test failure message relies on toString()
of the compared objects.
For built-in classes such as String
, Integer
and so for ... no problem as these override both equals()
and toString()
. So it is perfectly valid to assert List<String>
or List<Integer>
with assertEquals(Object,Object)
.
And about this matter : you have to override equals()
in a class because it makes sense in terms of object equality, not only to make assertions easier in a test with JUnit.
To make assertions easier you have other ways.
As a good practice I favor assertion/matcher libraries.
Here is a AssertJ solution.
org.assertj.core.api.ListAssert.containsExactly()
is what you need : it verifies that the actual group contains exactly the given values and nothing else, in order as stated in the javadoc.
Suppose a Foo
class where you add elements and where you can get that.
A unit test of Foo
that asserts that the two lists have the same content could look like :
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
@Test
void add() throws Exception {
Foo foo = new Foo();
foo.add("One", "Two", "Three");
Assertions.assertThat(foo.getElements())
.containsExactly("One", "Two", "Three");
}
A AssertJ good point is that declaring a List
as expected is needless : it makes the assertion straighter and the code more readable :
Assertions.assertThat(foo.getElements())
.containsExactly("One", "Two", "Three");
But Assertion/matcher libraries are a must because these will really further.
Suppose now that Foo
doesn't store String
s but Bar
s instances.
That is a very common need.
With AssertJ the assertion is still simple to write. Better you can assert that the list content are equal even if the class of the elements doesn't override equals()/hashCode()
while JUnit way requires that :
import org.assertj.core.api.Assertions;
import static org.assertj.core.groups.Tuple.tuple;
import org.junit.jupiter.api.Test;
@Test
void add() throws Exception {
Foo foo = new Foo();
foo.add(new Bar(1, "One"), new Bar(2, "Two"), new Bar(3, "Three"));
Assertions.assertThat(foo.getElements())
.extracting(Bar::getId, Bar::getName)
.containsExactly(tuple(1, "One"),
tuple(2, "Two"),
tuple(3, "Three"));
}
I would do it like this
function startWith($haystack,$needle){
if(substr($haystack,0, strlen($needle))===$needle)
return true;
}
function endWith($haystack,$needle){
if(substr($haystack, -strlen($needle))===$needle)
return true;
}
I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.
String.prototype.trimEllip = function (length) {
return this.length > length ? this.substring(0, length) + "..." : this;
}
And use it like:
var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)
(question) Don't you get that info in
select * from pg_user;
or using the view pg_stat_activity:
select * from pg_stat_activity;
Added:
the view says:
One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.
can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...
something like that.
Proxies may send a HTTP_X_FORWARDED_FOR
header but even that is optional.
Also keep in mind that visitors may share IP addresses; University networks, large companies and third-world/low-budget ISPs tend to share IPs over many users.
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
Please do not do that, it is very annoying.
The right menu is there for a reason, and it should be left there. Many browser extensions add entries to the right click menu and the user should be able to use it in any page he visits.
Moreover you can use all of the functionality of the right click menu in other ways (keyboard shortcuts, browser menu etc etc etc) so blocking the right click menu has the only effect of annoying the user.
PS: If really you cannot resist the urge to block it at least do not put a popup saying "no right click allowed".
Yes, if they return a subtype. Here's an example:
package com.sandbox;
public class Sandbox {
private static class Parent {
public ParentReturnType run() {
return new ParentReturnType();
}
}
private static class ParentReturnType {
}
private static class Child extends Parent {
@Override
public ChildReturnType run() {
return new ChildReturnType();
}
}
private static class ChildReturnType extends ParentReturnType {
}
}
This code compiles and runs.
If your application uses async stuff and you're fiddling with Mouse's cursor, you probably want to do it only in main UI thread. You can use app's Dispatcher thread for that:
Application.Current.Dispatcher.Invoke(() =>
{
// The check is required to prevent cursor flickering
if (Mouse.OverrideCursor != cursor)
Mouse.OverrideCursor = cursor;
});
An intent filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive.
When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object.
AndroidManifest.xml
<activity android:name=".HelloWorld"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http" android:host="androidium.org"/>
</intent-filter>
</activity>
Launch HelloWorld
Intent intent = new Intent (Intent.ACTION_VIEW, Uri.parse("http://androidium.org"));
startActivity(intent);