Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
I understand the issue with arm64 and Xcode 12 and I was able to resolve build issues by excluding the arm64 architecture for iPhone Simulator or by setting ONLY_ACTIVE_ARCH for Release scheme. However I still have problems to push my framework using pod repo push.
I found out that setting s.pod_target_xcconfig in my podspec does not apply this setting to dependencies defined in the same podspec. I can see it in the dummy App project that Cocoapods is generating during the validation. Cocoapods validation is running release scheme for simulator and this is failing when one or more dependencies doesn't exclude arm64 or is not set to build active architecture only.
A solution could be to force Cocoapods to add post install script while validating the project or let it build Debug scheme, because the Debug scheme is only building active architecture.
I ended up using Xcode 11 to release my pod to pass the validation. You can download Xcode 11 from developer.apple.com, copy it to Applications folder as Xcode11.app and switch using sudo xcode-select --switch /Applications/Xcode11.app/Contents/Developer
. Don't forget to switch back when done.
import { MatDialogModule } from '@angular/material/dialog';
import { MatTableModule } from '@angular/material/table';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
If you getting this error saying signing-config.json (Access denied) means just exit the android studio and just go to the desktop home and click on the android studio icon and give Run as Administrator, this will sort out the problem (or) you can delete the signing-config.json and re-run the program :)
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
ls /bin/python*
Identify the highest version of python listed.
If the highest version is something like python2.7
then install python2-pip
If its something like python3.8
then install python3-pip
Example for python3.8:
sudo apt-get install python3-pip
Dec 25th, 2019 :
Whoever facing issue regarding Image not showing in Flutter , let me give you simple checkpoints :
First point is very important
I got the same message when I tried to install pip install django-imagekit. So I ran pip install wheel (I had python 2.7) and then I reran pip install django-imagekit and it worked. Thanks
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
For me even thou the distribution certificate and provisioning profile was available for Xcode, selecting Automatic manage signing during the distribute process made it fail. I did the following. As mentioned before I created a new distribution certificate and provisioning profile and then during distribute process manually selected the certificate and provisioning profile and Voilaaaa. Also made sure I am on the latest version 10.1.
First run your IDE or CMD as Administrator and run the following:
pip install pipwin
pipwin install pyaudio
You should declare your method first in void initState()
, so when the first time pages has been loaded, it will init your method first, hope it can help
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
An alternative way to put images in your app (for me it just worked that way):
1 - Create an assets/images folder
2 - Add your image to the new folder
3 - Register the assets folder in pubspec.yaml
4 - Use this code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var assetsImage = new AssetImage('assets/images/mountain.jpg'); //<- Creates an object that fetches an image.
var image = new Image(image: assetsImage, fit: BoxFit.cover); //<- Creates a widget that displays an image.
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Climb your mountain!"),
backgroundColor: Colors.amber[600], //<- background color to combine with the picture :-)
),
body: Container(child: image), //<- place where the image appears
),
);
}
}
You could use
https://github.com/slightfoot/flutter_after_layout
which executes a function only one time after the layout is completed. Or just look at its implementation and add it to your code :-)
Which is basically
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => yourFunction(context));
}
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"
}
It is located on the Android Studio
folder itself, on where you installed it.
I followed below steps to install mcrypt for PHP7.2 using PECL.
apt-get install php-pecl
apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1
You should add "extension=mcrypt.so" to php.ini
Please comment below if you need any assistance. :-)
IMPORTANT !
According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.
People's answer here about having the key from the computer is generated are accurate. But if things are still failing, try restarting Xcode after installing a cert
I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.
Add:
"resolveJsonModule": true,
To tsconfig.json
Import like:
import * as nameOfJson from 'path/to/file.json';
Stop ng test
, start again.
Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports
Clearing the Cache of your React Native Project:
npm < 6.0 and RN < 0.50:
watchman watch-del-all && rm -rf $TMPDIR/react-* &&
rm -rf node_modules/ && npm cache clean && npm install &&
npm start -- --reset-cache
npm >= 6.0 and RN >= 0.50:
watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* &&
rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules/ && npm cache clean --force &&
npm install && npm start -- --reset-cache
Generally it is a versioning issue. Node.js v8 cannot compile with angular-cli 6.0 or later. angularcli v6 and above will work for lastest node versions. Please make sure if your node version is v8, then you need to install angular-cli upto 1.7.4. enter ng -v command in cmd and check the cli and node versions.
The other way to tackle it is to use this code snippet:
JSON.parse(JSON.stringify(response)).data
This feels so wrong but it works
Call the 2-arg constructor: For compatibility with Android O, call support-v4 NotificationCompat.Builder(Context context, String channelId)
. When running on Android N or earlier, the channelId
will be ignored. When running on Android O, also create a NotificationChannel
with the same channelId
.
Out of date sample code: The sample code on several JavaDoc pages such as Notification.Builder calling new Notification.Builder(mContext)
is out of date.
Deprecated constructors: Notification.Builder(Context context)
and v4 NotificationCompat.Builder(Context context)
are deprecated in favor of Notification[Compat].Builder(Context context, String channelId)
. (See Notification.Builder(android.content.Context) and v4 NotificationCompat.Builder(Context context).)
Deprecated class: The entire class v7 NotificationCompat.Builder
is deprecated. (See v7 NotificationCompat.Builder.) Previously, v7 NotificationCompat.Builder
was needed to support NotificationCompat.MediaStyle
. In Android O, there's a v4 NotificationCompat.MediaStyle
in the media-compat library's android.support.v4.media
package. Use that one if you need MediaStyle
.
API 14+: In Support Library from 26.0.0 and higher, the support-v4 and support-v7 packages both support a minimum API level of 14. The v# names are historical.
<link rel="stylesheet" href="{{ URL::asset('css/styles.css') }}">
It will search for the file in your project public
folder
React.MouseEvent works for me:
private onClick = (e: React.MouseEvent<HTMLInputElement>) => {
let button = e.target as HTMLInputElement;
}
Only few steps. We can download or generate PDF from our HTML page or we can generate PDF of specific div from a HTML page.
Steps : HTML -> Image (PNG or JPEG) -> PDF
Please Follow the below steps,
Step 1 :-
npm install --save html-to-image
npm install jspdf --save
Step 2 :-
/* ES6 */
import * as htmlToImage from 'html-to-image';
import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';
/* ES5 */
var htmlToImage = require('html-to-image');
-------------------------
import { jsPDF } from "jspdf";
Step 3 :-
****** With out PDF properties given below ******
htmlToImage.toPng(document.getElementById('myPage'), { quality: 0.95 })
.then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'my-image-name.jpeg';
const pdf = new jsPDF();
pdf.addImage(dataUrl, 'PNG', 0, 0);
pdf.save("download.pdf");
});
****** With PDF properties given below ******
htmlToImage.toPng(document.getElementById('myPage'), { quality: 0.95 })
.then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'my-image-name.jpeg';
const pdf = new jsPDF();
const imgProps= pdf.getImageProperties(dataUrl);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(dataUrl, 'PNG', 0, 0,pdfWidth, pdfHeight);
pdf.save("download.pdf");
});
I think this is helpful. Please try
Pycrypto has vulnerabilities assigned the CVE-2013-7459 number, and the repo hasn't accept PRs since June 23, 2014.
Pycryptodome is a drop-in replacement for the PyCrypto library, which exposes almost the same API as the old PyCrypto, see Compatibility with PyCrypto.
If you haven't install pycrypto yet, you can use pip install pycryptodome
to install pycryptodome in which you won't get Microsoft Visual C++ 14.0 issue.
I ran into the same issue. I had created another component with the same name under a different folder. so in my app module I had to import both components but with a trick
import {DuplicateComponent as AdminDuplicateComponent} from '/the/path/to/the/component';
Then in declarations I could add AdminDuplicateComponent instead.
Just thought that I would leave that there for future reference.
After a lot of time and getting help from a friend who knows a lot more than me about android: app/build.gradle
android {
compileSdkVersion 27
// org.gradle.caching = true
defaultConfig {
applicationId "com.cryptoviewer"
minSdkVersion 16
targetSdkVersion 23
versionCode 196
versionName "16.83"
// ndk {
// abiFilters "armeabi-v7a", "x86"
// }
}
and dependencies
dependencies {
implementation project(':react-native-camera')
//...
implementation "com.android.support:appcompat-v7:26.1.0" // <= YOU CARE ABOUT THIS
implementation "com.facebook.react:react-native:+" // From node_modules
}
in build.gradle
allprojects {
//...
configurations.all {
resolutionStrategy.force "com.android.support:support-v4:26.1.0"
}
in gradle.properties
android.useDeprecatedNdk=true
android.enableAapt2=false
org.gradle.jvmargs=-Xmx4608M
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.keshav.retroft2arrayinsidearrayexamplekeshav"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
compile 'com.android.support:appcompat-v7:26.0.1'
compile 'com.android.support:recyclerview-v7:26.0.1'
compile 'com.android.support:cardview-v7:26.0.1'
Here is an Enum
factory that avoids realm issues by using a namespace and Symbol.for
:
const Enum = (n, ...v) => Object.freeze(v.reduce((o, v) => (o[v] = Symbol.for(`${n}.${v}`), o), {}));
const COLOR = Enum("ACME.Color", "Blue", "Red");
console.log(COLOR.Red.toString());
console.log(COLOR.Red === Symbol.for("ACME.Color.Red"));
_x000D_
Got same problem with project porting from VS2013 to VS2017,
Fix: change "Properties->General->Windows SDK Version" to 10
I know this is an old question but according what @mikejones1477 said, modern front end libraries and frameworks escape the text giving you protection against XSS. The reason why cookies are not a secure method using credentials is that cookies doesn't prevent CSRF when localStorage does (also remember that cookies are accessible by javascript too, so XSS isn't the big problem here), this answer resume why.
The reason storing an authentication token in local storage and manually adding it to each request protects against CSRF is that key word: manual. Since the browser is not automatically sending that auth token, if I visit evil.com and it manages to send a POST http://example.com/delete-my-account, it will not be able to send my authn token, so the request is ignored.
Of course httpOnly is the holy grail but you can't access from reactjs or any js framework beside you still have CSRF vulnerability. My recommendation would be localstorage or if you want to use cookies make sure implemeting some solution to your CSRF problem like django does.
Regarding with the CDN's make sure you're not using some weird CDN, for example CDN like google or bootstrap provide, are maintained by the community and doesn't contain malicious code, if you are not sure, you're free to review.
I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.
As I didn't want to break anything, I did this to be able to use newer versions of Python3 than Python v3.4 :
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in auto mode
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
update-alternatives: using /usr/bin/python3.7 to provide /usr/local/bin/python3 (python3) in auto mode
$ update-alternatives --list python3
/usr/bin/python3.6
/usr/bin/python3.7
$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/local/bin/python3).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.7 2 auto mode
1 /usr/bin/python3.6 1 manual mode
2 /usr/bin/python3.7 2 manual mode
Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in manual mode
$ ls -l /usr/local/bin/python3 /etc/alternatives/python3
lrwxrwxrwx 1 root root 18 2019-05-03 02:59:03 /etc/alternatives/python3 -> /usr/bin/python3.6*
lrwxrwxrwx 1 root root 25 2019-05-03 02:58:53 /usr/local/bin/python3 -> /etc/alternatives/python3*
Add the @Component in your controller class. May this work
Unity 5.6.1 / 2017.1 fixes the Android SDK Tools 25.3.1+ compatibility issue. This is noted in Unity bug tracker under issue 888859 and their 5.6.1 release notes.
I don't think that IDE is relevant here. After all you're running a Maven and Maven doesn't have a source that will allow to compile the diamond operators. So, I think you should configure maven-compiler-plugin itself.
You can read about this here. But in general try to add the following properties:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
and see whether it compiles now in Maven only.
From Dockerfile reference:
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.The
ENV
instruction sets the environment variable<key>
to the value<value>
.
The environment variables set usingENV
will persist when a container is run from the resulting image.
So if you need build-time customization, ARG
is your best choice.
If you need run-time customization (to run the same image with different settings), ENV
is well-suited.
If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable
Given the number of combinations involved, using ENV
to set those features at runtime is best here.
But you can combine both by:
ARG
ARG
as an ENV
That is, with a Dockerfile including:
ARG var
ENV var=${var}
You can then either build an image with a specific var
value at build-time (docker build --build-arg var=xxx
), or run a container with a specific runtime value (docker run -e var=yyy
)
I found that using the recommended table-responsive class in a wrapper still causes responsive tables to (surprisingly) shrink horizontally:
<div class="table-responsive-lg">
<table class="table">
...
</table>
</div>
The solution for me was to create the following media breakpoints and classes to prevent it:
.table-xs {
width:544px;
}
.table-sm {
width: 576px;
}
.table-md {
width: 768px;
}
.table-lg {
width: 992px;
}
.table-xl {
width: 1200px;
}
/* Small devices (landscape phones, 544px and up) */
@media (min-width: 576px) {
.table-sm {
width: 100%;
}
}
/* Medium devices (tablets, 768px and up) The navbar toggle appears at this breakpoint */
@media (min-width: 768px) {
.table-sm {
width: 100%;
}
.table-md {
width: 100%;
}
}
/* Large devices (desktops, 992px and up) */
@media (min-width: 992px) {
.table-sm {
width: 100%;
}
.table-md {
width: 100%;
}
.table-lg {
width: 100%;
}
}
/* Extra large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) {
.table-sm {
width: 100%;
}
.table-md {
width: 100%;
}
.table-lg {
width: 100%;
}
.table-xl {
width: 100%;
}
}
Then I can add the appropriate class to my table element. For example:
<div class="table-responsive-lg">
<table class="table table-lg">
...
</table>
</div>
Here the wrapper sets the width to 100% for large and greater per Bootstrap. With the table-lg class applied to the table element, the table width is set also set to 100% for large and greater, but set to 992px for medium and smaller. The classes table-xs, table-sm, table-md, and table-xl work the same way.
I receive this error in any new module I create with create-react-native-module. None of the posted solutions worked for me.
What worked for me was first making sure to run yarn
in the newly created module folder in order to create node_modules/
(this step is probably obvious). Then, in XCode, select Product -> Scheme -> React instead of the default selection of MyModuleName.
StringValues
is an array of strings. You can get your string value by providing an index, e.g. HttpContext.Request.Query["page"][0]
.
(Taken from my comment)
pip
won't handle system level dependencies. You'll have to apt-get install libfreetype6-dev
before continuing. (It even says so right in your output. Try skimming over it for such errors next time, usually build outputs are very detailed)
You can run build
for a specific service by running docker-compose up --build <service name>
where the service name must match how did you call it in your docker-compose file.
Example
Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application
in docker-compose file.
You can then simply run docker-compose up --build application
Extra parameters
In case you want to add extra parameters to your command such as -d
for running in the background, the parameter must be before the service name:
docker-compose up --build -d application
Please use Spring Tool Suite (Eclipse-based development environment that is customized for developing Spring applications).
Create a Spring Starter Project, it will create the directory structure for you with the spring boot maven dependencies.
I have the following Nginx virtual host(static content) for local development work to disable all browser caching:
upstream testCom
{
server localhost:1338;
}
server
{
listen 80;
server_name <your ip or domain>;
location / {
# proxy_cache datacache;
proxy_cache_key $scheme$host$request_method$request_uri;
proxy_cache_valid 200 60m;
proxy_cache_min_uses 1;
proxy_cache_use_stale updating;
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_ignore_headers Set-Cookie;
userid on;
userid_name __uid;
userid_domain <your ip or domain>;
userid_path /;
userid_expires max;
userid_p3p 'policyref="/w3c/p3p.xml", CP="CUR ADM OUR NOR STA NID"';
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
proxy_pass http://testCom;
}
}
I have resolved the issue by below steps:
Just include this in the package.json in devDependencies section
"angular-cli": "1.0.0-beta.25.5"
Not compulsory to install it if you have another vresion of cli installed globally.
I got this issue when I worked with angular2 & 4 at a time with different project. So angular4 - need angular-cli@latest and angular2 need angular-cli the above version.
Open SVG using any text editor and remove width
and height
attributes from the root node.
Before
<svg width="12px" height="20px" viewBox="0 0 12 20" ...
After
<svg viewBox="0 0 12 20" ...
Now the image will always fill all the available space and will scale using CSS width
and height
. It will not stretch though so it will only grow to available space.
Tagging of the image isn't supported inside the Dockerfile. This needs to be done in your build command. As a workaround, you can do the build with a docker-compose.yml that identifies the target image name and then run a docker-compose build
. A sample docker-compose.yml would look like
version: '2'
services:
man:
build: .
image: dude/man:v2
That said, there's a push against doing the build with compose since that doesn't work with swarm mode deploys. So you're back to running the command as you've given in your question:
docker build -t dude/man:v2 .
Personally, I tend to build with a small shell script in my folder (build.sh) which passes any args and includes the name of the image there to save typing. And for production, the build is handled by a ci/cd server that has the image name inside the pipeline script.
If you are using debug configuration for maven, use the command
clean install
And skip all the tests.
This is an old question asked two years prior to my answer, I am going to post what worked for me anyways.
In my working directory I have two files: Dockerfile & provision.sh
Dockerfile:
FROM centos:6.8
# put the script in the /root directory of the container
COPY provision.sh /root
# execute the script inside the container
RUN /root/provision.sh
EXPOSE 80
# Default command
CMD ["/bin/bash"]
provision.sh:
#!/usr/bin/env bash
yum upgrade
I was able to make the file in the docker container executable by setting the file outside the container as executable chmod 700 provision.sh
then running docker build .
.
If you are a python
user -
Create a requirements.txt
file preferably using pip freeze > requirements.txt
.
Add, commit and try pushing it again.
If this doesn't work try deleting .git
(beware this might remove the associated git history) and follow the above steps again.
Worked for me.
the problem is in flow annotation in handleClick, i removed this and works fine thanks @alik
I had a similar problem, and after spending so much time and lots of searching about this issue the only trick worked for me:
Android SDK Tool
(update it to latest version)Android SDK Platform-tools
(update it to latest version)Android SDK Build-tools
(update it to latest version)Android Support Repository
under Extra
folder (update it to latest version)Android API
as the installed Android SDK Build-tools
& Android SDK Platform-tools
version as shown in the Configure Required SDKs
figure above.Note: Local Maven repository for Support Libraries which is listed as the SDK requirement in the official docs of React-native is now named as Android Support Repository in the SDK Manager .
If your device is listed, but shown as "OFFLINE", yet no popup to accept USB debugging has occured on the phone: Disconnect/reconnect USB cable, and the popup may show.
Probably this is a common cause, it's mentioned by others, but not in simplest terms.
Change following:
<bindingRedirect oldVersion="0.0.0.0-4.1.1.2" newVersion="4.1.1.2" />
with the following:
<bindingRedirect oldVersion="0.0.0.0-4.1.1.2" newVersion="4.0.0.0" />
in web.config
I navigate to:
/usr/lib/android-sdk/licenses
and I typed in terminal:
echo -e "\n8933bad161af4178b1185d1a37fbf41ea5269c55" > $ANDROID_SDK/licenses/android-sdk-license"
With root permission. And it works for me now.
Hey this is pretty simple to solve this error.Just follow this steps:
First uninstall any existing installation:
pip uninstall scikit-image
or, on conda-based systems:
conda uninstall scikit-image
Now, clone scikit-image on your local computer, and install:
git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .
To update the installation:
git pull # Grab latest source
pip install -e . # Reinstall
For other os and manual process please check this Link.
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
This worked for me:
yarn add --force [email protected]
or yarn add --force node-sass
run npm install jquery --save
then on your root component, place this
global.jQuery = require('../node_modules/jquery/dist/jquery.js');
var $ = global.jQuery;
Do not forget to export it to enable you to use it with other components
export default {
name: 'App',
components: {$}
}
According to official docs:
This may help if you want the HTTP headers that the server responded with. All header names are lower cased and can be accessed using the bracket notation. Example: response.headers['content-type']
will give something like: headers: {},
According to other answers I am adding the parallel stages scenario:
pipeline {
agent any
stages {
stage('some parallel stage') {
parallel {
stage('parallel stage 1') {
when {
expression { ENV == "something" }
}
steps {
echo 'something'
}
}
stage('parallel stage 2') {
steps {
echo 'something'
}
}
}
}
}
}
your manifest application name should contain application class name. Like
<application
android:name="your package name.MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:theme="@style/AppTheme">
In VS2019, the project property page, TypeScript Build tab has a setting (dropdown) for "Module System". When I changed that from "ES2015" to CommonJS, then VS2019 IDE stopped complaining that it could find neither axios nor redux-thunk (TS2307).
tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"baseUrl": "src",
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"lib": [
"es6",
"dom",
"es2015.promise"
],
"module": "esnext",
"moduleResolution": "node",
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"outDir": "build/dist",
"rootDir": "src",
"sourceMap": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es5",
"skipLibCheck": true,
"strict": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"exclude": [
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts",
"node_modules",
"obj",
"**/*.spec.ts"
],
"include": [
"src",
"src/**/*.ts",
"@types/**/*.d.ts",
"node_modules/axios",
"node_modules/redux-thunk"
]
}
Just lock and unlock the android solved my issue then
adb reverse tcp:8081 tcp:8081
I got this error when I was trying to create a virtualenv
with command virtualenv myVirtualEnv
. I just added a sudo
before the command; it solved everything.
You are using the wrong build.gradle
file.
In your top-level file you can't define an android
block.
Just move this part inside the module/build.gradle
file.
android {
compileSdkVersion 17
buildToolsVersion '23.0.0'
}
dependencies {
compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'
If you just want to install PHP no matter what version it is, try PHP7
sudo apt-get install php7.0 php7.0-mcrypt
In android/app/build.gradle
android {
compileSdkVersion 23
buildToolsVersion '23.0.0'
defaultConfig {
applicationId "com.dkm.example"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
multiDexEnabled true
it works for me
>= RC.6
Support resetting forms and maintain a submitted
state.
console.log(this.form.submitted);
this.form.reset()
or
this.form = new FormGroup()...;
importat update
To set the Form controls to a state when the form is created, like validators, some additional measurements are necessary
In the view part of the form (html) add an *ngIf
to show or hide the form
<form *ngIf="showForm"
In the component side of the form (*.ts) do this
showForm:boolean = true;
onSubmit(value:any):void {
this.showForm = false;
setTimeout(() => {
this.reset()
this.showForm = true;
});
}
Here is a more detailed example:
export class CreateParkingComponent implements OnInit {
createParkingForm: FormGroup ;
showForm = true ;
constructor(
private formBuilder: FormBuilder,
private parkingService: ParkingService,
private snackBar: MatSnackBar) {
this.prepareForm() ;
}
prepareForm() {
this.createParkingForm = this.formBuilder.group({
'name': ['', Validators.compose([Validators.required, Validators.minLength(5)])],
'company': ['', Validators.minLength(5)],
'city': ['', Validators.required],
'address': ['', Validators.compose([Validators.required, Validators.minLength(10)])],
'latitude': [''],
'longitude': [''],
'phone': ['', Validators.compose([Validators.required, Validators.minLength(7)])],
'pictureUrl': [''],
// process the 3 input values of the maxCapacity'
'pricingText': ['', Validators.compose([Validators.required, Validators.minLength(10)])],
'ceilingType': ['', Validators.required],
});
}
ngOnInit() {
}
resetForm(form: FormGroup) {
this.prepareForm();
}
createParkingSubmit() {
// Hide the form while the submit is done
this.showForm = false ;
// In this case call the backend and react to the success or fail answer
this.parkingService.create(p).subscribe(
response => {
console.log(response);
this.snackBar.open('Parqueadero creado', 'X', {duration: 3000});
setTimeout(() => {
//reset the form and show it again
this.prepareForm();
this.showForm = true;
});
}
, error => {
console.log(error);
this.showForm = true ;
this.snackBar.open('ERROR: al crear Parqueadero:' + error.message);
}
);
}
}
original <= RC.5 Just move the code that creates the form to a method and call it again after you handled submit:
@Component({
selector: 'form-component',
template: `
<form (ngSubmit)="onSubmit($event)" [ngFormModel]="form">
<input type="test" ngControl="name">
<input type="test" ngControl="email">
<input type="test" ngControl="username">
<button type="submit">submit</button>
</form>
<div>name: {{name.value}}</div>
<div>email: {{email.value}}</div>
<div>username: {{username.value}}</div>
`
})
class FormComponent {
name:Control;
username:Control;
email:Control;
form:ControlGroup;
constructor(private builder:FormBuilder) {
this.createForm();
}
createForm() {
this.name = new Control('', Validators.required);
this.email = new Control('', Validators.required);
this.username = new Control('', Validators.required);
this.form = this.builder.group({
name: this.name,
email: this.email,
username: this.username
});
}
onSubmit(value:any):void {
// code that happens when form is submitted
// then reset the form
this.reset();
}
reset() {
this.createForm();
}
}
While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt
and python-pip
.
Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
php5-mcrypt \
python-pip
However, according to this answer you should think about installing the python3-pip
package instead of the python-pip
package when using Python 3.x.
Furthermore, to make the php5-mcrypt
package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository
command missing in the Ubuntu Docker image so I installed the package software-properties-common
at first to make the command available.
Splitting up the statements and putting apt-get update
and apt-get install
into one RUN
command is also recommended here.
Oh and by the way, you actually don't need the -y
flag at apt-get update
because there is nothing that has to be confirmed automatically.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
apache2 \
curl \
git \
libapache2-mod-php5 \
php5 \
php5-mcrypt \
php5-mysql \
python3.4 \
python3-pip
Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.
The normal layout for a maven multi module project is:
parent
+-- pom.xml
+-- module
+-- pom.xml
Check that you use this layout.
Additionally:
the relativePath
looks strange. Instead of '..'
<relativePath>..</relativePath>
try '../' instead:
<relativePath>../</relativePath>
You can also remove relativePath
if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.
The module path may be wrong. In the parent you define the module as:
<module>junitcategorizer.cutdetection</module>
You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection
is not the name of the folder than change it accordingly.
Hope that helps..
EDIT have a look at the other post, I answered there.
While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile()
when it is deployed as JAR as I faced the same issue.
This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.
Below is the code snippet for the same -
ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);
You don't need hibernate-entitymanager-xxx.jar
, because of you use a Hibernate session approach (not JPA
). You need to close the SessionFactory
too and rollback a transaction on errors. But, the problem, of course, is not with those.
This is returned by a database
#
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "sa"
#
Looks like you've provided an incorrect username or (and) password.
In Linux
First of all set ANDROID_HOME in .bashrc file
Run command
sudo gedit ~/.bashrc
set andoid sdk path where you have installed
export ANDROID_HOME=/opt/android-sdk-linux
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
to reload file run command
source ~/.bashrc
Now check installed platform, run command
ionic platform
Output
Installed platforms:
android 6.0.0
Available platforms:
amazon-fireos ~3.6.3 (deprecated)
blackberry10 ~3.8.0
browser ~4.1.0
firefoxos ~3.6.3
ubuntu ~4.3.4
webos ~3.7.0
if android already installed then need to remove and install again
ionic platform rm android
ionic platform add android
If not installed already please add android platform
ionic platform add android
Please make sure you have added android platform without sudo command
if you still getting error in adding android platfrom like following
Error: EACCES: permission denied, open '/home/ubuntu/.cordova/lib/npm_cache/cordova-android/6.0.0/package/package.json'
Please go to /home/ubuntu/ and remove .cordova folder from there
cd /home/ubuntu/
sudo rm -r .cordova
Now run following command again
ionic platform add android
after adding platform successfully you will be able to build andoid in ionic.
Thanks
Editing the path of the keystore file solved my problem.
I got the same problem, and my solution looks like this:
// *./module1/module1.ts*
export module Module1 {
export class Module1{
greating(){ return 'hey from Module1'}
}
}
// *./module2/module2.ts*
import {Module1} from './../module1/module1';
export module Module2{
export class Module2{
greating(){
let m1 = new Module1.Module1()
return 'hey from Module2 + and from loaded Model1: '+ m1.greating();
}
}
}
Now we can use it on the server side:
// *./server.ts*
/// <reference path="./typings/node/node.d.ts"/>
import {Module2} from './module2/module2';
export module Server {
export class Server{
greating(){
let m2 = new Module2.Module2();
return "hello from server & loaded modules: " + m2.greating();
}
}
}
exports.Server = Server;
// ./app.js
var Server = require('./server').Server.Server;
var server = new Server();
console.log(server.greating());
And on the client side too:
// *./public/javscripts/index/index.ts*
import {Module2} from './../../../module2/module2';
document.body.onload = function(){
let m2 = new Module2.Module2();
alert(m2.greating());
}
// ./views/index.jade
extends layout
block content
h1= title
p Welcome to #{title}
script(src='main.js')
//
the main.js-file created by gulp-task 'browserify' below in the gulpfile.js
And, of course, a gulp-file for all of this:
// *./gulpfile.js*
var gulp = require('gulp'),
ts = require('gulp-typescript'),
runSequence = require('run-sequence'),
browserify = require('gulp-browserify'),
rename = require('gulp-rename');
gulp.task('default', function(callback) {
gulp.task('ts1', function() {
return gulp.src(['./module1/module1.ts'])
.pipe(ts())
.pipe(gulp.dest('./module1'))
});
gulp.task('ts2', function() {
return gulp.src(['./module2/module2.ts'])
.pipe(ts())
.pipe(gulp.dest('./module2'))
});
gulp.task('ts3', function() {
return gulp.src(['./public/javascripts/index/index.ts'])
.pipe(ts())
.pipe(gulp.dest('./public/javascripts/index'))
});
gulp.task('browserify', function() {
return gulp.src('./public/javascripts/index/index.js', { read: false })
.pipe(browserify({
insertGlobals: true
}))
.pipe(rename('main.js'))
.pipe(gulp.dest('./public/javascripts/'))
});
runSequence('ts1', 'ts2', 'ts3', 'browserify', callback);
})
Updated.
Of course, it's not neccessary to compile typescript files separatly.
runSequence(['ts1', 'ts2', 'ts3'], 'browserify', callback)
works perfect.
A lot of good solutions and valuable commentaries by known experts from JS community on the topic could be found here. It could be an indicator that it's not that trivial problem as it may seem. I think this is why it could be the source of doubts and uncertainty on the issue.
Fundamental problem here is that in React you're only allowed to mount component to its parent, which is not always the desired behavior. But how to address this issue?
I propose the solution, addressed to fix this issue. More detailed problem definition, src and examples can be found here: https://github.com/fckt/react-layer-stack#rationale
Rationale
react
/react-dom
comes comes with 2 basic assumptions/ideas:
- every UI is hierarchical naturally. This why we have the idea of
components
which wrap each otherreact-dom
mounts (physically) child component to its parent DOM node by defaultThe problem is that sometimes the second property isn't what you want in your case. Sometimes you want to mount your component into different physical DOM node and hold logical connection between parent and child at the same time.
Canonical example is Tooltip-like component: at some point of development process you could find that you need to add some description for your
UI element
: it'll render in fixed layer and should know its coordinates (which are thatUI element
coord or mouse coords) and at the same time it needs information whether it needs to be shown right now or not, its content and some context from parent components. This example shows that sometimes logical hierarchy isn't match with the physical DOM hierarchy.
Take a look at https://github.com/fckt/react-layer-stack/blob/master/README.md#real-world-usage-example to see the concrete example which is answer to your question:
import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
return (
<Cell {...props}>
// the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
<Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
hideMe, // alias for `hide(modalId)`
index } // useful to know to set zIndex, for example
, e) => // access to the arguments (click event data in this example)
<Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
<ConfirmationDialog
title={ 'Delete' }
message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
confirmButton={ <Button type="primary">DELETE</Button> }
onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
close={ hideMe } />
</Modal> }
</Layer>
// this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
<LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
<div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
<Icon type="trash" />
</div> }
</LayerContext>
</Cell>)
// ...
Sometime this error also occur when you change the order of Component Function while passing to connect.
Incorrect Order:
export default connect(mapDispatchToProps, mapStateToProps)(TodoList);
Correct Order:
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);
You can add the plugins as suggested by @Vikramaditya. Then to generate the production build. You have to run the the command
NODE_ENV=production webpack --config ./webpack.production.config.js
If using babel
, you will also need to prefix BABEL_ENV=node
to the above command.
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.
Here is what worked for me. First, let us understand the problem. You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time.
When I got the error, I thought it may be related to path issue as in absolute vs relative. So I passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. It was working fine. But in my case the value is a variable coming from props. I tried to pass a string literal variable as some suggested. It did not work. Also I tried to define a local method using switch case for all 10 values (I knew it was not best solution, but I just wanted it to work somehow). That too did not work. Then I came to know that we can NOT pass variable to the require.
As a workaround I have modified the data in the data.json file to confine it to just the name of my image. This image name which is coming from the props as a String literal. I concatenated it to the hard coded value, like so:
import React from "react";
function JobCard(props) {
const { logo } = props;
return (
<div className="jobCards">
<img src={require(`../assets/images/${logo}`)} alt="" />
</div>
)
}
The actual value contained in the logo would be coming from data.json file and would refer to some image name like photosnap.svg.
Try to create script with ADD
command and specification of working directory
Like this("script" is the name of script and /root/script.sh
is where you want it in the container, it can be different path:
ADD script.sh /root/script.sh
In this case ADD
has to come before CMD
, if you have one
BTW it's cool way to import scripts to any location in container from host machine
In CMD
place [./script]
It should automatically execute your script
You can also specify WORKDIR
as /root
, then you'l be automatically placed in root, upon starting a container
To export a single component in ES6, you can use export default
as follows:
class MyClass extends Component {
...
}
export default MyClass;
And now you use the following syntax to import that module:
import MyClass from './MyClass.react'
If you are looking to export multiple components from a single file the declaration would look something like this:
export class MyClass1 extends Component {
...
}
export class MyClass2 extends Component {
...
}
And now you can use the following syntax to import those files:
import {MyClass1, MyClass2} from './MyClass.react'
I've solved this problem by deleting the google-services.json file and downloading it again from Firebase console.
The -o option didn't work for me because the artifact is still in development and not yet uploaded and maven (3.5.x) still tries to download it from the remote repository because it's the first time, according to the error I get.
However this fixed it for me: https://maven.apache.org/general.html#importing-jars
After this manual install there's no need to use the offline option either.
UPDATE
I've just rebuilt the dependency and I had to re-import it: the regular mvn clean install
was not sufficient for me
I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:
sudo python -m pip install wheel
and
sudo python -m pip install pandas
Else if you see python version 3.x then run these two commands to install pandas:
sudo python3 -m pip install wheel
and
sudo python3 -m pip install pandas
Good Luck!
Use these settings and it will work fine.
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.pm.motivator"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
}
}
Always for Ubuntu/Debian, chjortlund's answer it's very good but not perfect, since this way you get an unoptimized BLAS library. You have simply to do:
sudo apt install libatlas-base-dev
and voila'!
I was getting this error
Error:Execution failed for task ':app:preDebugAndroidTestBuild'. Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.
I was having following dependencies in my build.gradle file under Gradle Scripts
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
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'
}
So, I resolved it by commenting the following dependencies
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'
So my dependencies look like this
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
//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'
}
Hope it helps!
try this below solution:
exclude:path.resolve(__dirname, "node_modules")
I was having the same issue and tried all of the solutions on this page but none of them did the trick.
What finally worked was adding the universe
repo to my repo list. To do that run the following command
sudo add-apt-repository universe
After running the above command I was able to run
sudo apt install openjdk-8-jre
without an issue and the package was installed.
Hope this helps someone.
I have tried to remove all the Java services but still it is failing while executing the gradlew clean build command from IntelliJ terminal. I even verified the other applications I have opened somewhere the same path which I am trying the delete. But could not find any of such. So, finally restarted the IntelliJ IDE and able to proceed build smoothly.
It occurred on my side when building an app in the command line via xcodebuild and xcrun PackageApplication, signing the app with an enterprise profile. On our CI build servers, the certificate was set to "Always Trust" in the keychain (select certificate -> Get Info -> Trust -> "Use System Default" can be changed to "Always Trust"). I had to set it back to "Use System Default" in order to make this work. Initially we set this to "Always Trust" to work-around the keychain dialogs that appear after software updates and certificate updates.
Download the android SDK http://developer.android.com/sdk/installing/index.html
You only export the path of SDK folder.
export ANDROID_HOME="YOUR_PATH/sdk/"
AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.
As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.
So AArch64 and ARM64 refer to the same thing.
I install with npm install --save-dev webpack-dev-server
then I set package.json and webpack.config.js like this:
setting.
Then I run webpack-dev-server and get this error error.
If I don't use npm install -g webpack-dev-server
to install, then how to fix it?
I fixed the error configuration has an unknown property 'colors'
by removing colors:true
. It worked!
SpringBoot developers recommend to locate your main application class in a root package above other classes. Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute. Detailed info But be sure that the custom root package exists.
This works for me! be careful with the new java versions because they cause error, check that you have everything installed and in your specific directory,
I did not use openJDK
export JAVA_HOME="/usr/lib/jvm/java-8-jdk" \
&& export PATH=$JAVA_HOME/bin:$PATH \
&& export ANDROID_HOME=$HOME/Android/Sdk \
&& export PATH=${PATH}:${ANDROID_HOME}/tools \
&& export PATH=${PATH}:${ANDROID_HOME}/platform-tools \
&& export GRADLE_HOME=/usr/share/java/gradle/bin/gradle \
export PATH=$PATH:$GRADLE_HOME/bin
Linux 4.14.39-1-MANJARO #1 SMP PREEMPT Wed May 2 19:03:39 UTC 2018 x86_64 GNU/Linux
I'm using Visual Studio 2015, and I've found that the first thing to do is look in the build output.
I found this error reported there:
Reading build config file: \build.json... SyntaxError: Unexpected token
The solution for that was to remove the bom from the build.json file
Then I hit a second problem - with this message in the build output:
FAILURE: Build failed with an exception. * What went wrong: A problem was found with the configuration of task ':packageRelease'.
File 'C:\Users\Colin\etc' specified for property 'signingConfig.storeFile' is not a file.
Easily solved by putting the correct filename into the keystore property
You can use python3 -m pip
as a synonym for pip3
. That has saved me a couple of times.
As the React Native Documentation says, all your images sources needs to be loaded before compiling your bundle
So another way you can use dynamic images it's using a switch statement. Let's say you want to display a different avatar for a different character, you can do something like this:
class App extends Component {
state = { avatar: "" }
get avatarImage() {
switch (this.state.avatar) {
case "spiderman":
return require('./spiderman.png');
case "batman":
return require('./batman.png');
case "hulk":
return require('./hulk.png');
default:
return require('./no-image.png');
}
}
render() {
return <Image source={this.avatarImage} />
}
}
Check the snack: https://snack.expo.io/@abranhe/dynamic-images
Also, remember if your image it's online you don't have any problems, you can do:
let superhero = "spiderman";
<Image source={{ uri: `https://some-website.online/${superhero}.png` }} />
I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format
<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here
I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o
file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!
Recommendations:
Tweaks:
Disable VCS by File > Settings > Plugins
and disable the following things :
CVS Integration
; Git Integration
; GitHub
; Google Cloud ...
things; Subversion Integration
; hg4idea
;
Editor is a resource eating too (especially on Large Monitors) and slow. Make it much much faster: click Help > Edit custom VM options
and add these lines :
-Dsun.java2d.d3d=false
-Dsun.java2d.opengl=true
save it and Restart Android Studio.
File > Settings > Appearance & Behavior > System settings > HTTP Proxy
.Another Useful quote (from article):
Modules are expensive… On my current project I had to build some libraries from scratch and had to fork some that almost fitted my needs but not quite! If that modules are not constantly modified, it’s important to have this into consideration: the time needed to compile them from scratch, or even to check if the previous individual module build is up-to-date, can be up to almost 4x greater than to simply load that dependency as a binary
.jar/.aar
.Hint: run the
gradle build -profile
for an HTML report showing where the time goes regarding the build process.Note: keep that “unnecessary” modules in your version control system for the eventuallity of a quickfix/improvement in that dependency.
In your Gradle build script, use only
specific Google Service, like: compile 'com.google.android.gms:play-services-maps:...'
Instead of full Google Library: compile 'com.google.android.gms:play-services:...'
(Compile time goes from 2 minutes to around 25 seconds).
Gradle configures every project before executing tasks, regardless of whether the project is actually needed for the particular build. In global gradle.properties
adding this will help much: org.gradle.configureondemand=true
Surprisingly, some people say , they solved problem by reducing: 1) heapsizes to -Xmx256m
(instead of higher values); 2) Emulator Ram-size (from Edit AVD > Advanced Settings
);
Build > Clean Project
(or Rebuild
), you can use keyboard shortcut.Include import androidx.appcompat.app.AppCompatActivity; in your MainActivity.java with other import statements. This would look like:
this resolved my issue
The problem is that /var/www
doesn't exist either, and mkdir
isn't recursive by default -- it expects the immediate parent directory to exist.
Use:
mkdir -p /var/www/app
...or install a package that creates a /var/www
prior to reaching this point in your Dockerfile.
Use r.URL.Query()
when you appending to existing query, if you are building new set of params use the url.Values
struct like so
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
// if you appending to existing query this works fine
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
// or you can create new url.Values struct and encode that like so
q := url.Values{}
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB
Your debug output indicates that Clean is the first thing that it's trying to run, so I'm guessing it's failing to download any plugins from central.
First off, see if you can download the plugin jar directly in a web browser: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5.jar
If that works then your web browser has connectivity to central but maven doesn't. That suggests to me that your web browser is using a proxy that maven isn't configured to use.
Maven proxy settings are described in depth here. To simplify that a little fill this out (replace the protocol/host/port with the values from your internet settings) and put it in the <settings>
tag of your maven settings.xml
file:
<proxies>
<proxy>
<id>proxy</id>
<active>true</active>
<protocol>http</protocol>
<host>proxy.example.com</host>
<port>8080</port>
</proxy>
</proxies>
I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.
Error :
Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessImpl.create(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at hudson.Proc$LocalProc.<init>(Proc.java:250)
at hudson.Proc$LocalProc.<init>(Proc.java:219)
at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
at hudson.Launcher$ProcStarter.start(Launcher.java:455)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
at hudson.model.Build$BuildExecution.build(Build.java:206)
at hudson.model.Build$BuildExecution.doRun(Build.java:163)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
at hudson.model.Run.execute(Run.java:1853)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE
Solution :
1 - Install Cygwin and note the directory where it gets installed.
It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.
2 - Tell Jenkins where sh.exe is located.
Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.
That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.
I tried this really interesting solution today, which worked for me on an Ubuntu server. Some DNS or another issue in the apt
was making it adamant to not installing some packages from a custom PPA. What I did was install the apt-fast package and use it to install my packages instead of apt
.
apt-fast
is an alternative to apt
which works on top of apt
but uses aria2c
to download packages. It is used to increase the download speed. In my case, it also solved whatever network problem was making apt
to fail.
Using it is exactly the same as apt
:
sudo apt-fast install package-name
The build tasks are project specific. To create a new project, open a directory in Visual Studio Code.
Following the instructions here, press Ctrl + Shift + P, type Configure Tasks
, select it and press Enter.
The tasks.json file will be opened. Paste the following build script into the file, and save it:
{
"version": "0.1.0",
"command": "make",
"isShellCommand": true,
"tasks": [
{
"taskName": "Makefile",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "always",
// Pass 'all' as the build target
"args": ["all"],
// Use the standard less compilation problem matcher.
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
Now go to menu File ? Preferences ? Keyboard Shortcuts, and add the following key binding for the build task:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "f8", "command": "workbench.action.tasks.build" }
]
Now when you press F8 the Makefile will be executed, and errors will be underlined in the editor.
What worked for me was to import "github.com/gorilla/handlers" and then use it this way:
router := mux.NewRouter()
router.HandleFunc("/config", getConfig).Methods("GET")
router.HandleFunc("/config/emcServer", createEmcServers).Methods("POST")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
log.Fatal(http.ListenAndServe(":" + webServicePort, handlers.CORS(originsOk, headersOk, methodsOk)(router)))
As soon as I executed an Ajax POST request and attaching JSON data to it, Chrome would always add the Content-Type header which was not in my previous AllowedHeaders config.
I had the same pronlem but the folder "%TEMP%\VisualStudioTestExplorerExtensions" did not exist on my machine so as i read the posts i had the idea to create it and it works. The test explorer is now able to show all my tests. Thanks.
You can still use map
if you can afford to create a makeshift array:
{
new Array(this.props.level).fill(0).map((_, index) => (
<span className='indent' key={index}></span>
))
}
This works because new Array(n).fill(x)
creates an array of size n
filled with x
, which can then aid map
.
Use the following command
docker build -t mytag .
Note that mytag and dot has a space between them . This dot represents the present working directory .
For those who use Ubuntu 18.04
can run this command:
Create the /etc/apt/sources.list.d/mongodb-org-4.2.list
file for Ubuntu 18.04 (Bionic):
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);
Please refer to List and Keys - React
The right way to add further configurations to the Spring Boot peconfigured ObjectMapper is to define a Jackson2ObjectMapperBuilderCustomizer. Else you are overwriting Springs configuration, which you do not want to lose.
@Configuration
public class MyJacksonConfigurer implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.deserializerByType(LocalDate.class, new MyOwnJsonLocalDateTimeDeserializer());
}
}
Not a direct answer to the question, but this may help those who are having trouble creating style
information using Typescript.
I was getting an error telling me that the following was incorrect:
let iconStyle = {
position: 'relative',
maxHeight: '90px',
top: '25%',
}
The error told me that "types of property 'position' are incompatible". I have no idea why.
I fixed this by adding a strict Typescript declaration, like so:
let iconStyle: CSSProperties = {
position: 'relative',
maxHeight: '90px',
top: '25%',
}
This works.
I was using a virtual environment on Ubuntu 18.04, and since I only wanted to install it as a client, I only had to do:
sudo apt install libpq-dev
pip install psycopg2
And installed without problems. Of course, you can use the binary as other answers said, but I preferred this solution since it was stated in a requirements.txt file.
If you have something like
Uncaught SyntaxError: embedded: Unexpected token
You probably missed a comma in a place like this:
var CommentForm = React.createClass({
getInitialState: function() {
return {author: '', text: ''};
}, // <---- DON'T FORGET THE COMMA
render: function() {
return (
<form className="commentForm">
<input type="text" placeholder="Nombre" />
<input type="text" placeholder="Qué opina" />
<input type="submit" value="Publicar" />
</form>
)
}
});
You suggested "Catching any unexpected errors and return some error code signaling "unexpected situation" " but couldn't find an appropriate error code.
Guess what: That's what 5xx is there for.
Below are the steps to do revoke your JWT access token:
Please let me know if you need more details, I can share the code (Java + Spring boot) as well.
For your questions:
Q1: It's another JWT with fewer claims put in with long expiry time.
Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.
Q3: Yes, Correct
I have tried all suggestions and found my own simple solution.
The problem is that codes written in external environment like C
need compiler. Look for its own VS environment, i.e. VS 2008.
Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat
.
I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS
as variable name and gave the value of VS120COMNTOOLS
.
You can find my step by step solution below:
Now open a new session and pip install your-package
I found that mounting a local volume over /tmp can cause permission issues when the "apt-get update" runs, which prevents the package cache from being populated. Hopefully, this isn't something most people do, but it's something else to look for if you see this issue.
I faced at the same problem, and here i leave the reason of this behavior for everyone else with the same issue.
View LifeCycle
In order to improve performance, we've improved Ionic's ability to cache view elements and scope data. Once a controller is initialized, it may persist throughout the app’s life; it’s just hidden and removed from the watch cycle. Since we aren’t rebuilding scope, we’ve added events for which we should listen when entering the watch cycle again.
To see full description and $ionicView events go to: http://ionicframework.com/blog/navigating-the-changes/
To do this job in storyboard (Interface Builder Inspector)
With help of IBDesignable
, we can add more options to Interface Builder Inspector for UIButton
and tweak them on storyboard. First, add the following code to your project.
@IBDesignable extension UIButton {
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
@IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
Then simply set the attributes for buttons on storyboard.
I am researching the same thing and stumbled upon identityserver which implements OAuth and OpenID on top of ASP.NET. It integrates with ASP.NET identity and Membership Reboot with persistence support for Entity Framework.
So, to answer your question, check out their detailed document on how to setup an OAuth and OpenID server.
The compileSdkVersion
should be newest stable version.
The targetSdkVersion
should be fully tested and less or equal to compileSdkVersion
.
I tried lots of method but below work like charm....
After this command run these :-
curl -sL https://deb.nodesource.com/setup_14.x 565 | sudo -E bash -
sudo apt-get install -y nodejs
Now check…
node -v
npm -v
Get the latest version of MVC3 via NuGet. Open your project in Dev Studio. Open the Package Manager Console tab at the bottom of Dev Studio. Then use this command:
PM> Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1
If you click the tab key after "-Version" you will get a list of all of the available versions.
If you have an old version of NuGet you may get an error indicating you have to upgrade it. If so, open Tools->Extension Manager to install the latest version of NuGet. Note, you will need to run Dev Studio as Administrator before you can install NuGet.
Installing MVC3 should update Web.config in your project.
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.1" newVersion="3.0.0.1" />
</dependentAssembly>
</assemblyBinding>
I had a very simple solution for this, after struggling with all the methods of fixing this.
i had the problem on my mobile IOS devices.
css (desktop)
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}
.widget-wrap {
background-attachment: scroll;
}
Then i overwrite it with media query removing "fixed" as background attachment.
css (mobile)
@media (max-width: 767px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-attachment: initial;
}
}
initial - Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.
This worked for me on every device. Hope it helps someone else as well.
What worked for me is to add include tag in order to specify exactly what I want to filter.
It seems the resource plugin has problems going through the whole src/main/resource folder, probably due to some specific files inside.
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application.yml</include>
</includes>
</resource>
</resources>
Debugging build step failures is indeed very annoying.
The best solution I have found is to make sure that each step that does real work succeeds, and adding a check after those that fails. That way you get a committed layer that contains the outputs of the failed step that you can inspect.
A Dockerfile, with an example after the # Run DB2 silent installer
line:
#
# DB2 10.5 Client Dockerfile (Part 1)
#
# Requires
# - DB2 10.5 Client for 64bit Linux ibm_data_server_runtime_client_linuxx64_v10.5.tar.gz
# - Response file for DB2 10.5 Client for 64bit Linux db2rtcl_nr.rsp
#
#
# Using Ubuntu 14.04 base image as the starting point.
FROM ubuntu:14.04
MAINTAINER David Carew <[email protected]>
# DB2 prereqs (also installing sharutils package as we use the utility uuencode to generate password - all others are required for the DB2 Client)
RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y sharutils binutils libstdc++6:i386 libpam0g:i386 && ln -s /lib/i386-linux-gnu/libpam.so.0 /lib/libpam.so.0
RUN apt-get install -y libxml2
# Create user db2clnt
# Generate strong random password and allow sudo to root w/o password
#
RUN \
adduser --quiet --disabled-password -shell /bin/bash -home /home/db2clnt --gecos "DB2 Client" db2clnt && \
echo db2clnt:`dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode -| head -n 2 | grep -v begin | cut -b 2-10` | chgpasswd && \
adduser db2clnt sudo && \
echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
# Install DB2
RUN mkdir /install
# Copy DB2 tarball - ADD command will expand it automatically
ADD v10.5fp9_linuxx64_rtcl.tar.gz /install/
# Copy response file
COPY db2rtcl_nr.rsp /install/
# Run DB2 silent installer
RUN mkdir /logs
RUN (/install/rtcl/db2setup -t /logs/trace -l /logs/log -u /install/db2rtcl_nr.rsp && touch /install/done) || /bin/true
RUN test -f /install/done || (echo ERROR-------; echo install failed, see files in container /logs directory of the last container layer; echo run docker run '<last image id>' /bin/cat /logs/trace; echo ----------)
RUN test -f /install/done
# Clean up unwanted files
RUN rm -fr /install/rtcl
# Login as db2clnt user
CMD su - db2clnt
Ensure that you have following JARS in place: 1) jackson-core-asl-1.9.13 2) jackson-jaxrs-1.9.13 3) jackson-mapper-asl-1.9.13 4) jackson-xc-1.9.13
A list of HTTP Status Codes
The good-practice regarding status response is to, predictably, send the proper HTTP status code depending on the error (4xx for client errors, 5xx for server errors), regarding the actual JSON response there's no "bible" but a good idea could be to send (again) the status and data as 2 different properties of the root object in a successful response (this way you are giving the client the chance to capture the status from the HTTP headers and the payload itself) and a 3rd property explaining the error in a human-understandable way in the case of an error.
Stripe's API behaves similarly in the real world.
i.e.
OK
200, {status: 200, data: [...]}
Error
400, {status: 400, data: null, message: "You must send foo and bar to baz..."}
As many have already answered, mounting host volumes during the build is not possible. I just would like to add docker-compose
way, I think it'll be nice to have, mostly for development/testing usage
Dockerfile
FROM node:10
WORKDIR /app
COPY . .
RUN npm ci
CMD sleep 999999999
docker-compose.yml
version: '3'
services:
test-service:
image: test/image
build:
context: .
dockerfile: Dockerfile
container_name: test
volumes:
- ./export:/app/export
- ./build:/app/build
And run your container by docker-compose up -d --build
To add on to the Enterprise distribution cert solution: you can open Keychain and inspect the cert. If there is any red text saying the trust chain can't be verified or it being revoked, it WILL NOT WORK! On my computer, our distribution cert was showing as revoked even though the web portal showed it as still valid. We got a new distribution cert, which was green (valid) in Keychain, and this solved the issue.
{{html_entity_decode ($post->content())}} saved the issue for me with Laravel 4.0. Now My HTML content is interpreted as it should.
Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.
Installation
npm install --save-dev unminified-webpack-plugin
Usage
var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'library.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new UnminifiedWebpackPlugin()
]
};
By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^
A quick solution is add this code in your pom.xml:
<repositories>
<repository>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>http://repo1.maven.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
</repository>
</repositories>
Where never is for avoid the search a certified.
It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied
.
One thing you can try is doing a user install of the package with pip install lxml --user
. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)
You can also run pip install
as a superuser with sudo pip install lxml
but it is not generally a good idea because it can cause issues with your system-level packages.
Running the following commands solved this for me 1. python manage.py migrate 2. python manage.py makemigrations 3. python manage.py makemigrations appName
That's one of the few legitimate jobs for cat
:
openssl verify -verbose -CAfile <(cat Intermediate.pem RootCert.pem) UserCert.pem
Update:
As Greg Smethells points out in the comments, this command implicitly trusts Intermediate.pem. I recommend reading the first part of the post Greg references (the second part is specifically about pyOpenSSL and not relevant to this question).
In case the post goes away I'll quote the important paragraphs:
Unfortunately, an "intermediate" cert that is actually a root / self-signed will be treated as a trusted CA when using the recommended command given above:
$ openssl verify -CAfile <(cat geotrust_global_ca.pem rogue_ca.pem) fake_sometechcompany_from_rogue_ca.com.pem fake_sometechcompany_from_rogue_ca.com.pem: OK
It seems openssl will stop verifying the chain as soon as a root certificate is encountered, which may also be Intermediate.pem if it is self-signed. In that case RootCert.pem is not considered. So make sure that Intermediate.pem is coming from a trusted source before relying on the command above.
It happened the same to me after updating Xcode. I tried everything I can do such as reinstalling cocoapods and cleaning the project, but it didn't work. Now it's been solved after restart the system.
The easiest way I found to fix this was to set the height of the body and html elements to 100.1% for any request where the user agent was an iphone. This only works in Landscape mode, but thats all I needed.
html.iphone,
html.iphone body { height: 100.1%; }
Check it out at https://www.360jungle.com/virtual-tour/25
I had the same error. I tried and rechecked everything. I was so focused in the Stack trace that I didn't read the last lines of the build before the Reactor summary and the stack trace:
[DEBUG] Using connector AetherRepositoryConnector with priority 3.4028235E38 for http://www:8081/nexus/content/repositories/snapshots/
[INFO] Downloading: http://www:8081/nexus/content/repositories/snapshots/com/wdsuite/com.wdsuite.server.product/1.0.0-SNAPSHOT/maven-metadata.xml
[DEBUG] Could not find metadata com.group:artifact.product:version-SNAPSHOT/maven-metadata.xml in nexus (http://www:8081/nexus/content/repositories/snapshots/)
[DEBUG] Writing tracking file /home/me/.m2/repository/com/group/project/version-SNAPSHOT/resolver-status.properties
[INFO] Uploading: http://www:8081/nexus/content/repositories/snapshots/com/...-1.0.0-20141118.124526-1.zip
[INFO] Uploading: http://www:8081/nexus/content/repositories/snapshots/com/...-1.0.0-20141118.124526-1.pom
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
This was the key : "Could not find metadata". Although it said that it was an authentication error actually it got fixed doing a "rebuild metadata" in the nexus repository.
Hope it helps.
My problem was that I spelt one of the libraries wrongly when installing with pip3, which ended up all the other downloaded libaries in the same command not being installed. Just run pip3 install on them again and they should be installed from their cache.
Try adding the script element just before the /body tag like that
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>
<div id="divid">Next</div>
<script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>
@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.
On your controller
$dogs = Dog::lists('name', 'id');
On customer create view you can use.
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
Update For Laravel 5.1
The lists method now returns a Collection. Upgrading To 5.1.0
{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
Delete
/.idea/libraries
Then sync gradle to build project.
I would like to mention a PRETTY COOL feature that has been included since iOS 10, which is:
For now, UIRefreshControl is directly supported in each of UICollectionView
, UITableView
and UIScrollView
!
Each one of these views have refreshControl instance property, which means that there is no longer a need to add it as a subview in your scroll view, all you have to do is:
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)
// this is the replacement of implementing: "collectionView.addSubview(refreshControl)"
collectionView.refreshControl = refreshControl
}
func doSomething(refreshControl: UIRefreshControl) {
print("Hello World!")
// somewhere in your code you might need to call:
refreshControl.endRefreshing()
}
Personally, I find it more natural to treat it as a property for scroll view more than add it as a subview, especially because the only appropriate view to be as a superview for a UIRefreshControl is a scrollview, i.e the functionality of using UIRefreshControl is only useful when working with a scroll view; That's why this approach should be more obvious to setup the refresh control view.
However, you still have the option of using the addSubview
based on the iOS version:
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
collectionView.addSubview(refreshControl)
}
Short answer but did you have Skype open? This interferes specifically with ASP.NET by default (and localhosts in general) using port:80.
In Windows: Go to Tools -> Options -> Advanced -> Connection and uncheck the box "use port 80 and 443 as alternatives for incoming connections".
You have successfully removed the row names. The print.data.frame
method just shows the row numbers if no row names are present.
df1 <- data.frame(values = rnorm(3), group = letters[1:3],
row.names = paste0("RowName", 1:3))
print(df1)
# values group
#RowName1 -1.469809 a
#RowName2 -1.164943 b
#RowName3 0.899430 c
rownames(df1) <- NULL
print(df1)
# values group
#1 -1.469809 a
#2 -1.164943 b
#3 0.899430 c
You can suppress printing the row names and numbers in print.data.frame
with the argument row.names
as FALSE
.
print(df1, row.names = FALSE)
# values group
# -1.4345829 d
# 0.2182768 e
# -0.2855440 f
Edit: As written in the comments, you want to convert this to HTML. From the xtable
and print.xtable
documentation, you can see that the argument include.rownames
will do the trick.
library("xtable")
print(xtable(df1), type="html", include.rownames = FALSE)
#<!-- html table generated in R 3.1.0 by xtable 1.7-3 package -->
#<!-- Thu Jun 26 12:50:17 2014 -->
#<TABLE border=1>
#<TR> <TH> values </TH> <TH> group </TH> </TR>
#<TR> <TD align="right"> -0.34 </TD> <TD> a </TD> </TR>
#<TR> <TD align="right"> -1.04 </TD> <TD> b </TD> </TR>
#<TR> <TD align="right"> -0.48 </TD> <TD> c </TD> </TR>
#</TABLE>
One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.
@SpringBootApplication
public class ChildApplication extends ParentApplication{
public static void main(String[] args) {
SpringApplication.run(ChildApplication.class, args);
}
}
Just include #import "myProject-Swift.h" in .m or .h file
P.S You will not find "myProject-Swift.h" in file inspector it's hidden. But it is generated by app automatically.
We can Supply parameter in different way after some search I found some useful
<plugin>
<artifactId>${release.artifactId}</artifactId>
<version>${release.version}-${release.svm.version}</version>...
...
Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .
While Running build we need supply value for those parameter as follows.
RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74
Here I am supplying
release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74
It worked for me. Thanks
Quite a few good answers, but I just wanted to share my personal favourite Swift random number generation function for positive integers:
func randomNumber(range: Range<Int> = 1...6) -> Int {
let min = range.startIndex
let max = range.endIndex
return Int(arc4random_uniform(UInt32(max - min))) + min
}
Here's a quick update for Swift 3 and, as a bonus, it now works for any value type that conforms to the SignedInteger protocol - much more convenient for core data applications that need to specify Int16, Int32 etc. As a quick note, if you really need it to work on unsigned integers as well, just copy the entire function then replace SignedInteger
with UnsignedInteger
and toIntMax()
with toUIntMax()
.
func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
let length = (range.upperBound - range.lowerBound + 1).toIntMax()
let value = arc4random().toIntMax() % length + range.lowerBound.toIntMax()
return T(value)
}
Thanks to the removal of toIntMax() in Swift 4, we now have to use a different means of converting to a common integer type. In this example I'm using Int64 which is large enough for my purposes, but if you're using unsigned integers or have an Int128 or Int256 custom type you should use those.
public func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
let length = Int64(range.upperBound - range.lowerBound + 1)
let value = Int64(arc4random()) % length + Int64(range.lowerBound)
return T(value)
}
One more, for the total random-phile, here's an extension that returns a random element from any Collection
type object. Note this uses the above function to generate its index so you will need both.
extension Collection {
func randomItem() -> Self.Iterator.Element {
let count = distance(from: startIndex, to: endIndex)
let roll = randomNumber(inRange: 0...count-1)
return self[index(startIndex, offsetBy: roll)]
}
}
randomNumber()
returns a random number between 1 and 6.
randomNumber(50...100)
returns a number between 50 and 100 inclusive. Naturally you can replace the values of 50 and 100 with whatever you like.
Alas, my best StackOverflow answer has been rendered obsolete at last. You can now use simply Int.random(in: 1 ... 6)
to generate a random number in a given range. Also works for other forms of integer and floating point number. Collection types also now provide shuffle()
and randomElement()
functions. There is therefore no longer any need for fancy randomisation functions unless you want to use a specific randomiser type.
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
Solutions above didn't work. It simply displayed the last key/value pairs, but this did:
http://localhost/?key[]=1&key[]=2
Returns:
Array
(
[key] => Array
(
[0] => 1
[1] => 2
)
This worked for me.
Swift 3:
let time1 = 8.23
let time2 = 3.42
// Delay 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
print("Sum of times: \(time1 + time2)")
}
Objective-C:
CGFloat time1 = 3.49;
CGFloat time2 = 8.13;
// Delay 2 seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
CGFloat newTime = time1 + time2;
NSLog(@"New time: %f", newTime);
});
I wrote a simple Xcode 6 project that shows how to mix C++, Objective-C and Swift code:
https://github.com/romitagl/shared/tree/master/C-ObjC-Swift/Performance_Console
In particular, the example calls an Objective-C and a C++ function from the Swift.
The key is to create a shared header, Project-Bridging-Header.h, and put the Objective-C headers there.
Please download the project as a complete example.
Try Fragment, if you don't want any of above.
In your case, we can write
import React, {useState, Fragment} from 'react'
const thisIsMyCopy = Fragment('<p>copy copy copy <strong>strong copy</strong></p>')
render: function() {
return (
<div className="content">{thisIsMyCopy}</div>
);
}
If you using hook want to set it in a state somewhere with any condition
const [thisIsMyCopy, setThisIsMyCopy] = useState(<Fragment><p>copy copy copy <strong>strong copy</strong></p></Fragment>);
Disabling certificate checking is the wrong solution, and radically insecure.
The correct solution is to import the self-signed certificate into your truststore. An even more correct solution is to get the certificate signed by a CA.
If this is 'only for testing' it is still necessary to test the production configuration. Testing something else isn't a test at all, it's just a waste of time.
Both classes Rectangle and Ellipse need to override both of the abstract methods.
To work around this, you have 3 options:
Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:
abstract class Shape {
// ...
void draw(Graphics g);
}
And
class Rectangle extends Shape {
void draw(Graphics g) {
// ...
}
}
Finally
class Ellipse extends Shape {
void draw(Graphics g) {
// ...
}
}
And you can switch in between them, like so:
Shape shape = new Ellipse();
shape.draw(/* ... */);
shape = new Rectangle();
shape.draw(/* ... */);
Again, just an example.
If you have a script with the same name as your module in another directory, it will use that instead. For example:
module.py
module
|
|--module
| |
| |--__init__.py
| |--module.py
This will make it so that the first module.py is being used, not the second one.
restrict is for defining the directive type, and it can be A
(Attribute), C
(Class), E
(Element), and M
(coMment) , let's assume that the name of the directive is Doc
:
Type : Usage
A =
<div Doc></div>
C =
<div class="Doc"></div>
E =
<Doc data="book_data"></Doc>
M =
<!--directive:Doc -->
Overide the dismiss()
method like this:
@Override
public void dismiss() {
Window window = getWindow();
if (window == null) {
return;
}
View decor = window.getDecorView();
if (decor != null && decor.getParent() != null) {
super.dismiss();
}
}
To reproduce the issue, just finish activity before dismiss dialog.
Been beating my head on this for the last couple of days on a repackaged base box. (Mac OS X, El Capitan)
Following @Radek 's procedure I did 'vagrant ssh-config' on the source box and got:
...
/Users/Shared/dev/<source-box-name>/.vagrant/machines/default/virtualbox/private_key
...
On the new copy, that command gave me:
...
IdentityFile /Users/<username>/.vagrant.d/insecure_private_key
...
So, I just added this line in the new copy:
...
config.ssh.private_key_path = "/Users/Shared/dev/<source-box-name>/.vagrant/machines/default/virtualbox/private_key"
...
Not perfect, but I can get on with my life.
I had the same issue when i reference the Class library into my MVC web application,
the issue was the nuget package version number mismatch between two projects.
ex: my class library had log4net of 1.2.3 but my webapp had 1.2.6
fix: just make sure both the project have the same version number referenced.
I found this issue addressed here vagrant issues. Two ways to do it:
Run this on guest (i.e. after you ssh into vbox via vagrant ssh
)
sudo ln -s /opt/VBoxGuestAdditions-4.3.10/lib/VBoxGuestAdditions /usr/lib/VBoxGuestAdditions
Then run vagrant reload
to correctly mount the folders.
As @klang pointed out, update the VBoxGuestAdditions.iso file on your mac:
wget https://www.virtualbox.org/download/testcase/VBoxGuestAdditions_4.3.11-93070.iso??
sudo cp VBoxGuestAdditions_4.3.11-93070.iso /Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso
Since the iso is no longer available, you can use the 4.3.12 one (http://dlc.sun.com.edgesuite.net/virtualbox/4.3.12/VBoxGuestAdditions_4.3.12.iso)
note : the binary vbox4.3.12 for os X is not available at this time
You can solve the issue by adding below lines in web.config file.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
There is a new docker command for "secrets" management. But that only works for swarm clusters.
docker service create
--name my-iis
--publish target=8000,port=8000
--secret src=homepage,target="\inetpub\wwwroot\index.html"
microsoft/iis:nanoserver
in case some one still get this kind of message. Its happen because you add JVM argument when running maven project. Because it is related with maven you can check your pom.xml
file on your project.
find this line <argLine>...</argLine>
, on my project I also have argument below
<argLine>-Xmx1024m -XX:MaxPermSize=512m -XX:+TieredCompilation -XX:TieredStopAtLevel=1</argLine>
you should replace MaxPermSize
argument as -Xms123m -Xmx123m
, since MaxPermSize
is already deprecated and wont take any effect on your JVM config :
<argLine>-Xms512m -Xmx512m -XX:+TieredCompilation -XX:TieredStopAtLevel=1</argLine>
Since you mention you have a proxy connection I will tell you what worked for me: I went to properties (as friedrich mentioned) ensuring the Offline Work was unchecked. I opened up the gradle.properties file in the IDE and added my proxy settings. Here's a generic version:
systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
Then at the top of the properties file in the IDE there was a "Try Again" link which I clicked. That did it.
It works for me
try to make an independent <div>
then put the button
into that.
just like this :
<div id="contactBtn">
<button type="submit" class="btn btn-primary ">Send</button>
</div>
Then Go to to your CSS
Style page and do the Text-align:center
like this :
#contactBtn{text-align: center;}
the error can be due to one of several missing package. Below command will install several packages like g++, gcc, etc.
sudo apt-get install build-essential
A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.
<div class="container">
<div class="row">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--×-->
<h4 class="modal-title text-center" id="addContact">Add Contact</h4>
</div>
<div class="modal-body">
<div class="row">
<ul class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
</li>
<li>
<a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
</li>
</ul>
<div class="tab-content">
<div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
<div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-info" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
</div>
Here is how we got out of the infinite routing loop and still used $state.go
instead of $location.path
if('401' !== toState.name) {
if (principal.isIdentityResolved()) authorization.authorize();
}
Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:
<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
<label class="col-sm-2 control-label" for="username">Username*</label>
<div class="col-sm-10 col-md-9">
<input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
</div>
</div>
It is also important, that your form has the ng-submit="" attribute:
<form name="myForm" ng-submit="checkSubmit()" novalidate>
<!-- input fields here -->
....
<button type="submit">Submit</button>
</form>
You can also add an optional function for validation to the form:
//within your controller (some extras...)
$scope.checkSubmit = function () {
if ($scope.myForm.$valid) {
alert('All good...'); //next step!
}
else {
alert('Not all fields valid! Do something...');
}
}
Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched.
Instead of:
!myForm.username.$pristine
You could also use:
myForm.username.$dirty
You have to play with JSFiddle loading option :
set it to "No wrap - in body
" instead of "onload"
Working fiddle : http://jsfiddle.net/zQv9n/1/
Note that if you are using TeamCity as a build server, you get a "NuGet Installer" step that you can use to restore all the packages before the build step.
You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.
Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.
Tools
Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.
You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.
Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.
Language
PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.
A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.
Javascript-heavy sites
In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.
There are two approaches to this problem:
The low level approach:
You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.
The embedded browser approach:
Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.
If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.
You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.
Which approach is best?
That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.
The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.
Rate Limiting/Bot behaviour
You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.
Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.
You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.
Testing
Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.
There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.
The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.
You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.
Legal Issues
The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.
The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.
It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.
Who am I to write this giant wall of text anyway?
I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.
I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)
I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.
I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.
I know this is too late for sure, but, this could help someone as well.
In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).
Make sure that you can copy from the command prompt,
The sort-stream may also be used to ensure specific order of files with gulp.src
. Sample code that puts the backbone.js
always as the last file to process:
var gulp = require('gulp');
var sort = require('sort-stream');
gulp.task('scripts', function() {
gulp.src(['./source/js/*.js', './source/js/**/*.js'])
.pipe(sort(function(a, b){
aScore = a.path.match(/backbone.js$/) ? 1 : 0;
bScore = b.path.match(/backbone.js$/) ? 1 : 0;
return aScore - bScore;
}))
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./build/js/'));
});
This issue has already been resolved here : What is the best way to detect a mobile device in jQuery?.
On the accepted answer, they basically test if it's an iPhone, an iPod, an Android device or whatever to return true. Just keep the ones you want for instance if( /Android/i.test(navigator.userAgent) ) { // some code.. }
will return true only for Android user-agents.
However, user-agents are not really reliable since they can be changed. The best thing is still to develop something universal for all mobile platforms.
On the Mac
version of Android Studio Beta 1.2
, it's under
Android Studio->preferences->Build, Execution, Deployment->Compiler
Create file version.properties
MAJOR=1
MINOR=3
PATCH=6
VERSION_CODE=1
Change build.gradle
:
android {
def _versionCode=0
def _major=0
def _minor=0
def _patch=0
def _applicationId = "com.example.test"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
_patch = versionProps['PATCH'].toInteger() + 1
_major = versionProps['MAJOR'].toInteger()
_minor = versionProps['MINOR'].toInteger()
_versionCode= versionProps['VERSION_CODE'].toInteger()+1
if(_patch==99)
{
_patch=0
_minor=_minor+1
}
if(_major==99){
_major=0
_major=_major+1
}
versionProps['MAJOR']=_major.toString()
versionProps['MINOR']=_minor.toString()
versionProps['PATCH']=_patch.toString()
versionProps['VERSION_CODE']=_versionCode.toString()
versionProps.store(versionPropsFile.newWriter(), null)
}
else {
throw new GradleException("Could not read version.properties!")
}
def _versionName = "${_major}.${_versionCode}.${_minor}.${_patch}"
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId _applicationId
minSdkVersion 11
targetSdkVersion 23
versionCode _versionCode
versionName _versionName
}
}
Output : 1.1.3.6
There's the Managed Script Plugin which provides an easy way of managing user scripts. It also adds a build step action which allows you to select which user script to execute.
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
For Fedora (can be useful for someone)
sudo dnf install zlib-1.2.8-10.fc24.i686 libgcc-6.1.1-2.fc24.i686
This is done simply by doing this variable.
var base_url = '<?php echo base_url();?>'
This will have base url now. And now make a javascript function that will use this variable
function base_url(string){
return base_url + string;
}
And now this will always use the correct path.
var path = "assets/css/themes/" + color_ + ".css"
$('#style_color').attr("href", base_url(path) );
Update for mid 2016:
The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!
Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!
Google "npm as build tool" result: https://medium.com/@dabit3/introduction-to-using-npm-as-a-build-tool-b41076f488b0#.c33e74tsa
Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!
Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot
Your questions:
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
Everything belongs in package.json now
Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev
(--save-dev updates your package.json by adding an entry to devDependencies)
npm install lodash --save
(--save updates your package.json by adding an entry to dependencies)If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?
Always. Just because of comfort. When you add a flag (--save-dev
or --save
) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name
is npm i -D package-name
and shortcut for npm install --save package-name
is npm i -S package-name
It's all about display: block
:)
Updated:
Ok so you have the table, tr and td tags:
<table>
<tr>
<td>
<!-- your image goes here -->
</td>
</tr>
</table>
Lets say your table
or td
(whatever define your width) has property width: 360px;
. Now, when you try to replace the html comment with the actual image and set that image property for example width: 100%;
which should fully fill out the td
cell you will face the problem.
The problem is that your table cell (td
) isn't properly filled with the image. You'll notice the space at the bottom of the cell which your image doesn't cover (it's like 5px of padding).
How to solve this in a simpliest way?
You are working with the tables, right? You just need to add the display property to your image so that it has the following:
img {
width: 100%;
display: block;
}
You can override setMenuVisibility like this:
@Override
public void setMenuVisibility(final boolean visible) {
if (visible) {
//Do your stuff here
}
super.setMenuVisibility(visible);
}
Another approach depending on how you are changing the div. If you are using JQuery to change a div's contents with its html() method, you can extend that method and call a registration function each time you put html into a div.
(function( $, oldHtmlMethod ){
// Override the core html method in the jQuery object.
$.fn.html = function(){
// Execute the original HTML method using the
// augmented arguments collection.
var results = oldHtmlMethod.apply( this, arguments );
com.invisibility.elements.findAndRegisterElements(this);
return results;
};
})( jQuery, jQuery.fn.html );
We just intercept the calls to html(), call a registration function with this, which in the context refers to the target element getting new content, then we pass on the call to the original jquery.html() function. Remember to return the results of the original html() method, because JQuery expects it for method chaining.
For more info on method overriding and extension, check out http://www.bennadel.com/blog/2009-Using-Self-Executing-Function-Arguments-To-Override-Core-jQuery-Methods.htm, which is where I cribbed the closure function. Also check out the plugins tutorial at JQuery's site.
Looking forward to Web Animations in 2020.
async function moveToPosition(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
transform: `translateY(${el.getBoundingClientRect().top}px)`
},
], {
duration: durationInMs,
easing: 'ease-in',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeIn(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
opacity: '0.5',
offset: 0.5
},
{
opacity: '1',
offset: 1
}
], {
duration: durationInMs,
easing: 'linear',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeInSections() {
for (const section of document.getElementsByTagName('section')) {
await fadeIn(section, 200);
}
}
window.addEventListener('load', async() => {
await moveToPosition(document.getElementById('headerContent'), 500);
await fadeInSections();
await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
height: 100vh;
}
header {
height: 20%;
}
.text-center {
text-align: center;
}
.leading-none {
line-height: 1;
}
.leading-3 {
line-height: .75rem;
}
.leading-2 {
line-height: .25rem;
}
.bg-black {
background-color: rgba(0, 0, 0, 1);
}
.bg-gray-50 {
background-color: rgba(249, 250, 251, 1);
}
.pt-12 {
padding-top: 3rem;
}
.pt-2 {
padding-top: 0.5rem;
}
.text-lightGray {
color: lightGray;
}
.container {
display: flex;
/* or inline-flex */
justify-content: space-between;
}
.container section {
padding: 0.5rem;
}
.opacity-0 {
opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Web site created using create-snowpack-app" />
<link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>
<body>
<header class="bg-gray-50">
<div id="headerContent">
<h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
<p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
</div>
</header>
<div class="container">
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 1</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 2</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 3</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
</div>
<footer class="opacity-0">
<h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
<p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
</footer>
</body>
</html>
_x000D_
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
I believe you can just assign the empty set ({}
) to your variable.
struct x instance;
for(i = 0; i < n; i++) {
instance = {};
/* Do Calculations */
}
For footer change from position: relative;
to position:fixed;
footer {
background-color: #333;
width: 100%;
bottom: 0;
position: fixed;
}
Example: http://jsfiddle.net/a6RBm/
background-clip
and box-shadow
properties.1) Set background-clip: content-box
- this restricts the background only to the content itself (instead of covering both the padding and border)
2) Add an inner box-shadow
with the spread radius set to the same value as the padding.
So say the padding is 10px - set box-shadow: inset 0 0 0 10px lightGreen
- which will make only the padding area light green.
nav {_x000D_
width: 80%;_x000D_
height: 50px;_x000D_
background-color: gray;_x000D_
float: left;_x000D_
padding: 10px; /* 10px padding */_x000D_
border: 2px solid red;_x000D_
background-clip: content-box; /* <---- */_x000D_
box-shadow: inset 0 0 0 10px lightGreen; /* <-- 10px spread radius */_x000D_
}_x000D_
ul {_x000D_
list-style: none;_x000D_
}_x000D_
li {_x000D_
display: inline-block;_x000D_
}
_x000D_
<h2>The light green background color shows the padding of the element</h2>_x000D_
<nav>_x000D_
<ul>_x000D_
<li><a href="index.html">Home</a>_x000D_
</li>_x000D_
<li><a href="/about/">About</a>_x000D_
</li>_x000D_
<li><a href="/blog/">Blog</a>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
For a thorough tutorial covering this technique see this great css-tricks post
If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS
Here is the connectionString in the web config file which you can add:
<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>
Place is just above the system.web tag.
Then you can call it by:
connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;
Good news everyone, there's an isBetween
function!
Update your library ;)
You can listen to the dragend
event, and if the map is dragged outside the allowed bounds, move it back inside. You can define your allowed bounds in a LatLngBounds
object and then use the contains()
method to check if the new lat/lng center is within the bounds.
You can also limit the zoom level very easily.
Consider the following example: Fiddle Demo
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Limit Panning and Zoom</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
// This is the minimum zoom level that we'll allow
var minZoomLevel = 5;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(28.70, -127.50),
new google.maps.LatLng(48.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function() {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
</script>
</body>
</html>
Screenshot from the above example. The user will not be able to drag further south or far east in this case:
I have found the try: ... else:
construct useful in the situation where you are running database queries and logging the results of those queries to a separate database of the same flavour/type. Let's say I have lots of worker threads all handling database queries submitted to a queue
#in a long running loop
try:
query = queue.get()
conn = connect_to_db(<main db>)
curs = conn.cursor()
try:
curs.execute("<some query on user input that may fail even if sanitized">)
except DBError:
logconn = connect_to_db(<logging db>)
logcurs = logconn.cursor()
logcurs.execute("<update in DB log with record of failed query")
logcurs.close()
logconn.close()
else:
#we can't put this in main try block because an error connecting
#to the logging DB would be indistinguishable from an error in
#the mainquery
#We can't put this after the whole try: except: finally: block
#because then we don't know if the query was successful or not
logconn = connect_to_db(<logging db>)
logcurs = logconn.cursor()
logcurs.execute("<update in DB log with record of successful query")
logcurs.close()
logconn.close()
#do something in response to successful query
except DBError:
#This DBError is because of a problem with the logging database, but
#we can't let that crash the whole thread over what might be a
#temporary network glitch
finally:
curs.close()
conn.close()
#other cleanup if necessary like telling the queue the task is finished
Of course if you can distinguish between the possible exceptions that might be thrown, you don't have to use this, but if code reacting to a successful piece of code might throw the same exception as the successful piece, and you can't just let the second possible exception go, or return immediately on success (which would kill the thread in my case), then this does come in handy.
The correlation matrix is the standard way to express correlations between an arbitrary finite number of variables. The correlation matrix of N data vectors is a symmetric N × N matrix with unity diagonal. Only in the case N = 2 does this matrix have one free parameter.
If an application is designed to start when Windows starts (as opposed to when a user logs in), your only option is to involve a Windows Service. Either write the application as a service, or write a simple service that exists only to launch the application.
Writing services can be tricky, and can impose restrictions that may be unacceptable for your particular case. One common design pattern is a front-end/back-end pair, with a service that does the work and an application front-end that communicates with the service to display information to the user.
On the other hand, if you just want your application to start on user login, you can use methods 1 or 2 that Joel Coehoorn listed.
the best way (for me) to make it it's the next infrastructure:
<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>
with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.
jQuery 3
As of jQuery 3, removeAttr
does not set the corresponding property to false
anymore:
Prior to jQuery 3.0, using
.removeAttr()
on a boolean attribute such aschecked
,selected
, orreadonly
would also set the corresponding named property tofalse
. This behavior was required for ancient versions of Internet Explorer but is not correct for modern browsers because the attribute represents the initial value and the property represents the current (dynamic) value.It is almost always a mistake to use
.removeAttr( "checked" )
on a DOM element. The only time it might be useful is if the DOM is later going to be serialized back to an HTML string. In all other cases,.prop( "checked", false )
should be used instead.
Hence only .prop('checked',false)
is correct way when using this version.
Original answer (from 2011):
For attributes which have underlying boolean properties (of which checked
is one), removeAttr
automatically sets the underlying property to false
. (Note that this is among the backwards-compatibility "fixes" added in jQuery 1.6.1).
So, either will work... but the second example you gave (using prop
) is the more correct of the two. If your goal is to uncheck the checkbox, you really do want to affect the property, not the attribute, and there's no need to go through removeAttr
to do that.
ALTER TABLE {TABLE NAME}
ALTER COLUMN {COLUMN NAME} SET DEFAULT '{DEFAULT VALUES}'
example :
ALTER TABLE RESULT
ALTER COLUMN STATUS SET DEFAULT 'FAIL'
If your trying to read file form HDFS. trying setting path in SparkConf
val conf = new SparkConf().setMaster("local[*]").setAppName("HDFSFileReader")
conf.set("fs.defaultFS", "hdfs://hostname:9000")
Go to your Arduino documents directory; inside you will find a directory named "Libraries". The imported library directory will be there. Just delete it and restart the Arduino app.
Your Arduino library folder should look like this (on Windows):
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h
My Documents\Arduino\libraries\ArduinoParty\examples
....
or like this (on Mac and Linux):
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h
Documents/Arduino/libraries/ArduinoParty/examples
The only issue with unused libraries is the trivial amount of disk space they use. They aren't loaded automatically so don't take up any application memory of the Arduino IDE.
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
I came up with this:
My scenario included more popovers on the same page, and hiding them just made them invisible and because of that, clicking on items behind the popover was not possible. The idea is to mark the specific popover-link as 'active' and then you can simply 'toggle' the active popover. Doing so will close the popover completely.
$('.popover-link').popover({ html : true, container: 'body' })
$('.popover-link').popover().on 'shown.bs.popover', ->
$(this).addClass('toggled')
$('.popover-link').popover().on 'hidden.bs.popover', ->
$(this).removeClass('toggled')
$("body").on "click", (e) ->
$openedPopoverLink = $(".popover-link.toggled")
if $openedPopoverLink.has(e.target).length == 0
$openedPopoverLink.popover "toggle"
$openedPopoverLink.removeClass "toggled"
There are two major purposes of hashing functions:
It's impossible to recommend a hash without knowing what you're using it for.
If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a variation of FNV. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.
If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. The Hash Function Lounge is a good place to start.
In my case the issue was caused by using a file path starting at the directory where the script was executing rather than at the root of the project.
My directory stucture was like this: projectfolder/ +-- package.json +-- scriptFolder/ ¦ +-- myScript.js
And I was calling fs.createReadStream('users.csv')
instead of the correct fs.createReadStream('scriptFolder/users.csv')
As mentionned in comments, this is the updated solution in favor of Icon object with documentation.
Use Icon object
var icon = {
url: "../res/sit_marron.png", // url
scaledSize: new google.maps.Size(50, 50), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
posicion = new google.maps.LatLng(latitud,longitud)
marker = new google.maps.Marker({
position: posicion,
map: map,
icon: icon
});
Simplest way:
>>> from datetime import datetime
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> dt.strftime("%s")
'1199163600'
Edit: @Daniel is correct, this would convert it to the machine's timezone. Here is a revised answer:
>>> from datetime import datetime, timezone
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> int((dt-epoch).total_seconds())
'1199145600'
In fact, its not even necessary to specify timezone.utc
, because the time difference is the same so long as both datetime
have the same timezone (or no timezone).
>>> from datetime import datetime
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> int((dt-epoch).total_seconds())
1199145600
This is for others (like me :) ). Don't forget to add the spring tx jar/maven dependency. Also correct configuration in appctx is:
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
, by mistake wrong configuration which others may have
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
i.e., extra "/spring-tx-3.1.xsd"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
in other words what is there in xmlns(namespace) should have proper mapping in
schemaLocation (namespace vs schema).
namespace here is : http://www.springframework.org/schema/tx
schema Doc Of namespace is : http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
this schema of namespace later is mapped in jar to locate the path of actual xsd located in org.springframework.transaction.config
Try this:
"0x" + BitConverter.ToString(arraytoinsert).Replace("-", "")
Although you should really be using a parameterised query rather than string concatenation of course...
I also like to build locators from up to bottom like:
//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']
It's pretty simple, as we just search btn-group
with button[contains(.,'Arcade Reader')]
and get it's button[@name='settings']
That's just another option to build xPath locators
What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:
getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");
or even simplify more
getGroupButton("Arcade Reader", "delete").click();
I think you are getting confused about what the a:active
CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected
into your CSS and when you select a link, update the selected menu item with new class e.g.
<div class="menuBar">
<ul>
<li class="selected"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
....
</ul>
</div>
// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; }
// more general CSS
li.selected a { color: #FF0000; }
You will need to update your template page to take in a selectedPage
parameter.
As Apple DOC
targetForAction:withSender:
Returns the target object that responds to an action.
You can't use that method to set target for UIButton
.
Try
addTarget(_:action:forControlEvents:) method
There are a lot of good answers on this thread. My solution for this issue was to write a script.
Name this 'git-scriptname' (and make it executable and put it in your PATH, like any script), and you can invoke it like a normal git command by running
$ git scriptname
The actual functionality is just the last line. Here's the source:
#!/usr/bin/env zsh
#
# Show a side-by-side diff of a particular file how it currently exists between:
# * the file system
# * in HEAD (latest committed changes)
function usage() {
cat <<-HERE
USAGE
$(basename $1) <file>
Show a side-by-side diff of a particular file between the current versions:
* on the file system (latest edited changes)
* in HEAD (latest committed changes)
HERE
}
if [[ $# = 0 ]]; then
usage $0
exit
fi
file=$1
diff -y =(git show HEAD:$file) $file | pygmentize -g | less -R
Those who are using Java 7.0 or below version can refer the code which I used here and it works.
public class WaitTest {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void waitHere(long waitTime) {
System.out.println("wait started...");
lock.lock();
try {
condition.await(waitTime, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
System.out.println("wait ends here...");
}
public static void main(String[] args) {
//Your Code
new WaitTest().waitHere(10);
//Your Code
}
}
Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017
-- Creating a table using NEWID for uniqueidentifier data type.
CREATE TABLE cust
(
CustomerID uniqueidentifier NOT NULL
DEFAULT newid(),
Company varchar(30) NOT NULL,
ContactName varchar(60) NOT NULL,
Address varchar(30) NOT NULL,
City varchar(30) NOT NULL,
StateProvince varchar(10) NULL,
PostalCode varchar(10) NOT NULL,
CountryRegion varchar(20) NOT NULL,
Telephone varchar(15) NOT NULL,
Fax varchar(15) NULL
);
GO
-- Inserting 5 rows into cust table.
INSERT cust
(CustomerID, Company, ContactName, Address, City, StateProvince,
PostalCode, CountryRegion, Telephone, Fax)
VALUES
(NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,
'90110', 'Finland', '981-443655', '981-443655')
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',
'08737-363', 'Brasil', '(14) 555-8122', '')
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,
'1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,
'8010', 'Austria', '7675-3425', '7675-3426')
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,
'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');
GO
Assuming that files with those names exist in multiple places in the directory tree and you want to preserve all of them:
find . -type f ! -regex ".*/\(textfile.txt\|backup.tar.gz\|script.php\|database.sql\|info.txt\)" -delete
You created the UIButton
is added the ViewController
, The following instance method to change UIFont
, tintColor
and TextColor
of the UIButton
Objective-C
buttonName.titleLabel.font = [UIFont fontWithName:@"LuzSans-Book" size:15];
buttonName.tintColor = [UIColor purpleColor];
[buttonName setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
Swift
buttonName.titleLabel.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purpleColor()
buttonName.setTitleColor(UIColor.purpleColor(), forState: .Normal)
Swift3
buttonName.titleLabel?.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purple
buttonName.setTitleColor(UIColor.purple, for: .normal)
command_1 && command_2
: execute command_2 only when command_1 is executed successfully.
command_1 || command_2
: execute command_2 only when command_1 is not successful executed.
Feels similar as how an 'if' condition is executed in a mainstream programming language, like, in if (condition_1 && condition_2){...}
condition_2 will be omitted if condition_1 is false
and in if (condition_1 || condition_2){...}
condition_2 will be omitted if condition_1 is true
.
See, it's the same trick you use for coding :)
Here is a version using filter
in dplyr
that applies the same technique as the accepted answer by negating the logical with !:
D2 <- D1 %>% dplyr::filter(!V1 %in% c('B','N','T'))
This fixed my problem but it crashed unless I changed
action:@selector(switchToNewsDetails:event:)
to
action:@selector(switchToNewsDetails: forEvent:)
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\"");
echo readfile($url);
is correct
or better one for exe type of files
header("Location: $url");
Try this:
result <- df %>%
group_by(A, B) %>%
filter(value == max(value)) %>%
arrange(A,B,C)
Seems to work:
identical(
as.data.frame(result),
ddply(df, .(A, B), function(x) x[which.max(x$value),])
)
#[1] TRUE
As pointed out in the comments, slice
may be preferred here as per @RoyalITS' answer below if you strictly only want 1 row per group. This answer will return multiple rows if there are multiple with an identical maximum value.
To make this you need to navigate to the Eclipse.app directory and use the following command:
open -n Eclipse.app
Instead of using -f or --force developers should use
--force-with-lease
Why? Because it checks the remote branch for changes which is absolutely a good idea. Let's imagine that James and Lisa are working on the same feature branch and Lisa has pushed a commit. James now rebases his local branch and is rejected when trying to push. Of course James thinks this is due to rebase and uses --force and would rewrite all Lisa's changes. If James had used --force-with-lease he would have received a warning that there are commits done by someone else. I don't see why anyone would use --force instead of --force-with-lease when pushing after a rebase.
I think the best solution I have come across is on this stackoverflow.
This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.
$('body').on('touchstart', function() {});
Hope this helps.
In case you can't for some reason use the same Random
again and again, try initializing it with something that changes all the time, like the time itself.
new Random(new System.DateTime().Millisecond).Next();
Remember this is bad practice though.
EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN:
Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.
The code below is probably your best option:
new Random().Next();
We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.
On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:
### log just the SQL
log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug
However, the JDBC bind parameters are not being logged.
I had the same error and solve it this way:
1 . Delete the orphaned volumes in Docker, you can use the built-in docker volume command. The built-in command also deletes any directory in /var/lib/docker/volumes that is not a volume so make sure you didn't put anything in there you want to save.
Warning be very careful with this if you have some data you want to keep
Cleanup:
$ docker volume rm $(docker volume ls -qf dangling=true)
Additional commands:
List dangling volumes:
$ docker volume ls -qf dangling=true
List all volumes:
$ docker volume ls
2 . Also consider removing all the unused Images.
First get rid of the <none>
images (those are sometimes generated while building an image and if for any reason the image building was interrupted, they stay there).
here's a nice script I use to remove them
docker rmi $(docker images | grep '^<none>' | awk '{print $3}')
Then if you are using Docker Compose to build Images locally for every project. You will end up with a lot of images usually named like your folder (example if your project folder named Hello, you will find images name Hello_blablabla
). so also consider removing all these images
you can edit the above script to remove them or remove them manually with
docker rmi {image-name}
View-Page
<h:selectOneMenu id="selectOneCB" value="#{page.selectedName}">
<f:selectItems value="#{page.names}"/>
</h:selectOneMenu>
Backing-Bean
List<SelectItem> names = new ArrayList<SelectItem>();
//-- Populate list from database
names.add(new SelectItem(valueObject,"label"));
//-- setter/getter accessor methods for list
To display particular selected record, it must be one of the values in the list.
I had the same issue using the request module to proxy POST request from somewhere else and it was because I left the host property in the header (I was copying the header from the original request).
If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst
:
Optional<List> o = id1.entrySet()
.stream()
.filter( e -> e.getKey() == 1)
.map(Map.Entry::getValue)
.findFirst();
In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :
List<List> list = id1.entrySet()
.stream()
.filter(.. some predicate...)
.map(Map.Entry::getValue)
.collect(Collectors.toList());
In eclipse Galileo :
From there you can Add External Jars
An easier way to do this is using crop from ImageOps. You can feed the number of pixels you want to crop from each side.
from PIL import ImageOps
border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)
I don't know what is the value/usefulness of renaming a function and call it with the new name. But using a string as function name, e.g. obtained from the command line, has some value/usefulness:
import sys
fun = eval(sys.argv[1])
fun()
In the present case, fun = x.
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
If you really just have lock-step iteration over a range, you can do it one of several ways:
for i in range(x):
j = i
…
# or
for i, j in enumerate(range(x)):
…
# or
for i, j in ((i,i) for i in range(x)):
…
All of the above are equivalent to for i, j in zip(range(x), range(y))
if x <= y
.
If you want a nested loop and you only have two iterables, just use a nested loop:
for i in range(x):
for i in range(y):
…
If you have more than two iterables, use itertools.product
.
Finally, if you want lock-step iteration up to x
and then to continue to y
, you have to decide what the rest of the x
values should be.
for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
…
# or
for i in range(min(x,y)):
j = i
…
for i in range(min(x,y), max(x,y)):
j = float('nan')
…
I use this one:
select max(table_catalog) as x from information_schema.tables
to check connection and ability to run queries (with 1 row as result) for postgreSQL, MySQL and MSSQL.
As per the documentation:
@dynamic tells the compiler that the accessor methods are provided at runtime.
With a little bit of investigation I found out that providing accessor methods override the @dynamic directive.
@synthesize tells the compiler to create those accessors for you (getter and setter)
@property tells the compiler that the accessors will be created, and that can be accessed with the dot notation or [object message]
edit the init.py file in your project origin directory
import pymysql
pymysql.install_as_MySQLdb()
I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.
UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.
UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.
In case anyone in the future is interested, here's what I came up with:
1. Create a custom directive for the <head>
element:
app.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
link: function(scope, elem){
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
elem.append($compile(html)(scope));
scope.routeStyles = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.css){
if(!angular.isArray(current.$$route.css)){
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, function(sheet){
delete scope.routeStyles[sheet];
});
}
if(next && next.$$route && next.$$route.css){
if(!angular.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function(sheet){
scope.routeStyles[sheet] = sheet;
});
}
});
}
};
}
]);
This directive does the following things:
$compile
) an html string that creates a set of <link />
tags for every item in the scope.routeStyles
object using ng-repeat
and ng-href
.<link />
elements to the <head>
tag.$rootScope
to listen for '$routeChangeStart'
events. For every '$routeChangeStart'
event, it grabs the "current" $$route
object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head>
tag. It also grabs the "next" $$route
object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head>
tag.ng-repeat
part of the compiled <link />
tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles
object.Note: this requires that your ng-app
attribute is on the <html>
element, not on <body>
or anything inside of <html>
.
2. Specify which stylesheets belong to which routes using the $routeProvider
:
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/some/route/1', {
templateUrl: 'partials/partial1.html',
controller: 'Partial1Ctrl',
css: 'css/partial1.css'
})
.when('/some/route/2', {
templateUrl: 'partials/partial2.html',
controller: 'Partial2Ctrl'
})
.when('/some/route/3', {
templateUrl: 'partials/partial3.html',
controller: 'Partial3Ctrl',
css: ['css/partial3_1.css','css/partial3_2.css']
})
}]);
This config adds a custom css
property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart'
event as .$$route
. So when listening to the '$routeChangeStart'
event, we can grab the css
property that we specified and append/remove those <link />
tags as needed. Note that specifying a css
property on the route is completely optional, as it was omitted from the '/some/route/2'
example. If the route doesn't have a css
property, the <head>
directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3'
example above, where the css
property is an array of relative paths to the stylesheets needed for that route.
3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.
Hope that helps someone else who might be struggling with this issue as much as I was.
When I asked this question, my real question was, "is there a difference between the two? Doesn't the runtime have to keep information about the array size, and so will it not be able to tell which one we mean?" This question does not appear in "related questions", so just to help out those like me, here is the answer to that: "why do we even need the delete[] operator?"
This is an old question but Oracle's latest installers are no improvement, so I recently found myself back in this swamp, thrashing around for several days ...
My scenario was SQL Server 2016 RTM. 32-bit Oracle 12c Open Client + ODAC was eventually working fine for Visual Studio Report Designer and Integration Services designer, and also SSIS packages run through SQL Server Agent (with 32-bit option). 64-bit was working fine for Report Portal when defining and Testing an Data Source, but running the reports always gave the dreaded "ORA-12154" error.
My final solution was to switch to an EZCONNECT connection string - this avoids the TNSNAMES mess altogether. Here's a link to a detailed description, but it's basically just: host:port/sid
In case it helps anyone in the future (or I get stuck on this again), here are my Oracle install steps (the full horror):
Install Oracle drivers: Oracle Client 12c (32-bit) plus ODAC.
a. Download and unzip the following files from http://www.oracle.com/technetwork/database/enterprise-edition/downloads/database12c-win64-download-2297732.html and http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html ):
i. winnt_12102_client32.zip
ii. ODAC112040Xcopy_32bit.zip
b. Run winnt_12102_client32\client32\setup.exe. For the Installation Type, choose Admin. For the installation location enter C:\Oracle\Oracle12. Accept other defaults.
c. Start a Command Prompt “As Administrator” and change directory (cd) to your ODAC112040Xcopy_32bit folder.
d. Enter the command: install.bat all C:\Oracle\Oracle12 odac
e. Copy the tnsnames.ora file from another machine to these folders: *
i. C:\Oracle\Oracle12\network\admin *
ii. C:\Oracle\Oracle12\product\12.1.0\client_1\network\admin *
Install Oracle Client 12c (x64) plus ODAC
a. Download and unzip the following files from http://www.oracle.com/technetwork/database/enterprise-edition/downloads/database12c-win64-download-2297732.html and http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html ):
i. winx64_12102_client.zip
ii. ODAC121024Xcopy_x64.zip
b. Run winx64_12102_client\client\setup.exe. For the Installation Type, choose Admin. For the installation location enter C:\Oracle\Oracle12_x64. Accept other defaults.
c. Start a Command Prompt “As Administrator” and change directory (cd) to the C:\Software\Oracle Client\ODAC121024Xcopy_x64 folder.
d. Enter the command: install.bat all C:\Oracle\Oracle12_x64 odac
e. Copy the tnsnames.ora file from another machine to these folders: *
i. C:\Oracle\Oracle12_x64\network\admin *
ii. C:\Oracle\Oracle12_x64\product\12.1.0\client_1\network\admin *
* If you are going with the EZCONNECT method, then these steps are not required.
The ODAC installs are tricky and obscure - thanks to Dan English who gave me the method (detailed above) for that.
In windows first check under services if world wide web publishing services is running. If not start it.
If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.
I had the same problem and it works you just have to declare the i
outside of the loop:
int i;
for(i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Note- position really matters add google() before jcenter()
And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
check these links below for more details-
Path.GetDirectoryName()
... but you need to know that the path you are passing to it does contain a file name; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).
You could validate first by testing File.Exists()
and/or Directory.Exists()
on your path first to see if you need to call Path.GetDirectoryName
It should be $cmd
instead of $($cmd)
. Works fine with that on my box.
Edit: Your script works only for one-word commands, like ls. It will not work for "ls cpp". For this to work, replace cmd="$1"; $cmd
with "$@"
. And, do not run your script as command="some cmd"; safeRun command
, run it as safeRun some cmd
.
Also, when you have to debug your bash scripts, execute with '-x' flag. [bash -x s.sh].
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
You can see this error in VS 2008 if you have a project in your solution that references an assembly that cannot be found. This could happen if the assembly comes from another project that is not part of your solution but should be. In this case simply adding the correct project to the solution will solve it.
Check the References section of each project in your solution. If any of them has a reference with an red x next to it, then it you have found your problem. That assembly reference cannot be found by the solution.
The error message is a bit confusing but I've seen this many times.
I realize I am biased as an old C programmer, but there are times when the various Python conventions make things hard to follow. I find the indent convention a bit of an annoyance at times.
Sometimes, clarity of when a statement or block ends is very useful. Standard C code will often read something like this:
for(i=0; i<100; i++) {
do something here;
do another thing here;
}
continue doing things;
where you use the whitespace for a lot of clarity - and it is easy to see where the loop ends.
Python does let you terminate with an (optional) semicolon. As noted above, that does NOT mean that there is a statement to execute followed by a 'null' statement. SO, for example,
print(x);
print(y);
Is the same as
print(x)
print(y)
If you believe that the first one has a null statement at the end of each line, try - as suggested - doing this:
print(x);;
It will throw a syntax error.
Personally, I find the semicolon to make code more readable when you have lots of nesting and functions with many arguments and/or long-named args. So, to my eye, this is a lot clearer than other choices:
if some_boolean_is_true:
call_function(
long_named_arg_1,
long_named_arg_2,
long_named_arg_3,
long_named_arg_4
);
since, to me, it lets you know that last ')' ends some 'block' that ran over many lines.
I personally think there is much to much made of PEP style guidelines, IDEs that enforce them, and the belief there is 'only one Pythonic way to do things'. If you believe the latter, go look at how to format numbers: as of now, Python supports four different ways to do it.
I am sure I will be flamed by some diehards, but the compiler/interpreter doesn't care if the arguments have long or short names, and - but for the indentation convention in Python - doesn't care about whitespace. The biggest problem with code is giving clarity to another human (and even yourself after months of work) to understand what is going on, where things start and end, etc.
There is a more efficient and less cumbersome solution for integers than a Collections.shuffle.
The problem is the same as successively picking items from only the un-picked items in a set and setting them in order somewhere else. This is exactly like randomly dealing cards or drawing winning raffle tickets from a hat or bin.
This algorithm works for loading any array and achieving a random order at the end of the load. It also works for adding into a List collection (or any other indexed collection) and achieving a random sequence in the collection at the end of the adds.
It can be done with a single array, created once, or a numerically ordered collectio, such as a List, in place. For an array, the initial array size needs to be the exact size to contain all the intended values. If you don't know how many values might occur in advance, using a numerically orderred collection, such as an ArrayList or List, where the size is not immutable, will also work. It will work universally for an array of any size up to Integer.MAX_VALUE which is just over 2,000,000,000. List objects will have the same index limits. Your machine may run out of memory before you get to an array of that size. It may be more efficient to load an array typed to the object types and convert it to some collection, after loading the array. This is especially true if the target collection is not numerically indexed.
This algorithm, exactly as written, will create a very even distribution where there are no duplicates. One aspect that is VERY IMPORTANT is that it has to be possible for the insertion of the next item to occur up to the current size + 1. Thus, for the second item, it could be possible to store it in location 0 or location 1. For the 20th item, it could be possible to store it in any location, 0 through 19. It is just as possible the first item to stay in location 0 as it is for it to end up in any other location. It is just as possible for the next new item to go anywhere, including the next new location.
The randomness of the sequence will be as random as the randomness of the random number generator.
This algorithm can also be used to load reference types into random locations in an array. Since this works with an array, it can also work with collections. That means you don't have to create the collection and then shuffle it or have it ordered on whatever orders the objects being inserted. The collection need only have the ability to insert an item anywhere in the collection or append it.
// RandomSequence.java
import java.util.Random;
public class RandomSequence {
public static void main(String[] args) {
// create an array of the size and type for which
// you want a random sequence
int[] randomSequence = new int[20];
Random randomNumbers = new Random();
for (int i = 0; i < randomSequence.length; i++ ) {
if (i == 0) { // seed first entry in array with item 0
randomSequence[i] = 0;
} else { // for all other items...
// choose a random pointer to the segment of the
// array already containing items
int pointer = randomNumbers.nextInt(i + 1);
randomSequence[i] = randomSequence[pointer];
randomSequence[pointer] = i;
// note that if pointer & i are equal
// the new value will just go into location i and possibly stay there
// this is VERY IMPORTANT to ensure the sequence is really random
// and not biased
} // end if...else
} // end for
for (int number: randomSequence) {
System.out.printf("%2d ", number);
} // end for
} // end main
} // end class RandomSequence
Change Column Name/Type/Position/Comment:
ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]
Example:
CREATE TABLE test_change (a int, b int, c int);
// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;
In my experience, first name/last name fields should be at least 48 characters -- there are names from some countries such as Malaysia or India that are very long in their full form.
Phone numbers and postcodes you should always treat as text, not numbers. The normal reason given is that there are postcodes that begin with 0, and in some countries, phone numbers can also begin with 0. But the real reason is that they aren't numbers -- they're identifiers that happen to be made up of numerical digits (and that's ignoring countries like Canada that have letters in their postcodes). So store them in a text field.
In MySQL you can use VARCHAR fields for this type of information. Whilst it sounds lazy, it means you don't have to be too concerned about the right minimum size.
URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".
RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).
In Java, the correct way to build a URL is with the URI
class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString()
method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI
object using the single-string constructor and then use the accessor methods (such as getPath()
) to retrieve the decoded components.
Don't use the URLEncoder
class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder
. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w
covers a-zA-Z and some other word characters. It all depends on what you need specifically.
Hi Guys you cant convert directly string to bigdecimal
you need to first convert it into long after that u will convert big decimal
String currency = "135.69";
Long rate1=Long.valueOf((currency ));
System.out.println(BigDecimal.valueOf(rate1));
I made the following changes in the /boot/config.txt
file, to support my 7" TFT LCD.
Uncomment "disable_overscan=1"
overscan_left=24
overscan_right=24
Overscan_top=10
Overscan_bottom=24
Framebuffer_width=480
Framebuffer_height=320
Sdtv_mode=2
Sdtv_aspect=2
I used this video as a guide.
You can use the createRef to change the state of the child component from the parent component. Here are all the steps.
Create a method to change the state in the child component.
2 - Create a reference for the child component in parent component using React.createRef().
3 - Attach reference with the child component using ref={}.
4 - Call the child component method using this.yor-reference.current.method.
Parent component
class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
render() {
return (
<div>
<button onClick={this.changeChild.current.toggleMenu()}>
Toggle Menu from Parent
</button>
<ChildComponent ref={this.changeChild} />
</div>
);
}
}
Child Component
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
open: false;
}
}
toggleMenu=() => {
this.setState({
open: !this.state.open
});
}
render() {
return (
<Drawer open={this.state.open}/>
);
}
}
If by "local" you mean on the same network segment, then you have to perform the following steps:
Or you can just let Python execute nmap externally and pipe the results back into your program.
In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:
void foo(char c)
{
puts("char");
}
void foo(int i)
{
puts("int");
}
int main()
{
foo('i');
return 0;
}
Output:
char
The internal representation of int
and unsigned int
is the same.
Therefore, when you pass the same format string to printf
it will be printed as the same.
However, there are differences when you compare them. Consider:
int x = 0x7FFFFFFF;
int y = 0xFFFFFFFF;
x < y // false
x > y // true
(unsigned int) x < (unsigned int y) // true
(unsigned int) x > (unsigned int y) // false
This can be also a caveat, because when comparing signed and unsigned integer one of them will be implicitly casted to match the types.
As a complement of the answers above, here is a sum up about Redirections:
EDIT: This graphic is not entirely correct.
The first example does not use stdin at all, it's passing "hello" as an argument to the echo command.
The graphic also says 2>&1 has the same effect as &> however
ls Documents ABC > dirlist 2>&1
#does not give the same output as
ls Documents ABC > dirlist &>
This is because &> requires a file to redirect to, and 2>&1 is simply sending stderr into stdout
I have a sample program for this:
public class BrowserBackForward {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//maximize the window
driver.manage().window().maximize();
driver.findElement(By.linkText("Documentation")).click();
System.out.println(driver.getCurrentUrl());
driver.navigate().back();
System.out.println(driver.getCurrentUrl());
Thread.sleep(30000);
driver.navigate().forward();
System.out.println("Forward");
Thread.sleep(30000);
driver.navigate().refresh();
}
}
I used some jquery to solve this
$('html').css({
'overflow-y': 'hidden'
});
$(document).ready(function(){
$(window).load(function() {
$('html').css({
'overflow-y': ''
});
});
});
On RHEL Linux just issue:
yum install tomcat-native.x86_64
/Note:depending on Your architecture 64bit or 32bit package may have different extension/
That is all. After that You will find in the log file next informational message:
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
All operations will be noticeably faster than before.
In my case, nginx was not able to open the log file which is located here /var/log/nginx/error.log
This was because I had deleted the log directory to free up space in root (which turned out to be stupid)
I then created a log folder in var and an nginx folder in log.
Then simply run sudo service nginx start
Yes, by capturing the output of sp_who2 into a table and then selecting from the table, but that would be a bad way of doing it. First, because sp_who2, despite its popularity, its an undocumented procedure and you shouldn't rely on undocumented procedures. Second because all sp_who2 can do, and much more, can be obtained from sys.dm_exec_requests and other DMVs, and show can be filtered, ordered, joined and all the other goodies that come with queriable rowsets.
Restarting explorer did this for me, but only for new cmd terminals.
The terminal I set the path could see the new Path variable already (in Windows 7).
taskkill /f /im explorer.exe && explorer.exe
Here is a proper explanation of "still reachable":
"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.
Local variables that are assigned allocations and not free'd are almost always leaks.
Here is an example
int foo(void)
{
static char *working_buf = NULL;
char *temp_buf;
if (!working_buf) {
working_buf = (char *) malloc(16 * 1024);
}
temp_buf = (char *) malloc(5 * 1024);
....
....
....
}
Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".
Taking a look at the source code of OpenPyXL (IterableWorksheet) I've figured out how to get the column and row count from an iterator worksheet:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]
row_count = sheet.get_highest_row() - 1
column_count = letter_to_index(sheet.get_highest_column()) + 1
IterableWorksheet.get_highest_column
returns a string with the column letter that you can see in Excel, e.g. "A", "B", "C" etc. Therefore I've also written a function to translate the column letter to a zero based index:
def letter_to_index(letter):
"""Converts a column letter, e.g. "A", "B", "AA", "BC" etc. to a zero based
column index.
A becomes 0, B becomes 1, Z becomes 25, AA becomes 26 etc.
Args:
letter (str): The column index letter.
Returns:
The column index as an integer.
"""
letter = letter.upper()
result = 0
for index, char in enumerate(reversed(letter)):
# Get the ASCII number of the letter and subtract 64 so that A
# corresponds to 1.
num = ord(char) - 64
# Multiply the number with 26 to the power of `index` to get the correct
# value of the letter based on it's index in the string.
final_num = (26 ** index) * num
result += final_num
# Subtract 1 from the result to make it zero-based before returning.
return result - 1
I still haven't figured out how to get the column sizes though, so I've decided to use a fixed-width font and automatically scaled columns in my application.
$('#link1').text("Replacement text");
The .text()
method drops the text you pass it into the element content. Unlike using .html()
, .text()
implicitly ignores any embedded HTML markup, so if you need to embed some inline <span>
, <i>
, or whatever other similar elements, use .html()
instead.
The . (dot) operator is usually used to get a field / call a method from an instance of class (or a static field / method of a class).
p.myField, p.myMethod() - p instance of a class
The -> (arrow) operator is used to get a field / call a method from the content pointed by the class.
p->myField, p->myMethod() - p points to a class
I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.
After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file
Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there
using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("[email protected]");
smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("[email protected]");
try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}
You may use the above code.
I've doing it with a function. In this case I will only transform character variables to factor:
for (i in 1:ncol(data)){
if(is.character(data[,i])){
data[,i]=factor(data[,i])
}
}
find . -name "*.pyc" -exec rm -f {} \;
From SQL Server you can set a Unique key index on the table for (Columns that needs to be unique)
Can a Python function be an argument of another function?
Yes.
def myfunc(anotherfunc, extraArgs):
anotherfunc(*extraArgs)
To be more specific ... with various arguments ...
>>> def x(a,b):
... print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
... z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>
I had a situation of git status
showing changes, but git diff
printing nothing, although there were changes in several lines. However:
$ git diff data.txt > myfile
$ cat myfile
<prints diff>
Git 2.20.1 on raspbian. Other commands like git checkout
, git pull
are printing to stdout without problems.
Using functions as spencer7593 mentioned is a correct approach for dynamic data. For static data, a more performant approach which is consistent with SQL data design (versus the anti-pattern of writting massive procedural code in sprocs) is to create a separate table with the static values and join to it. This is extremely beneficial from a performace perspective since the SQL Engine can build effective execution plans around a JOIN, and you have the potential to add indexes as well if needed.
The disadvantage of using functions (or any inline calculated values) is the callout happens for every potential row returned, which is costly. Why? Because SQL has to first create a full dataset with the calculated values and then apply the WHERE clause to that dataset.
Nine times out of ten you should not need dynamically calculated cell values in your queries. Its much better to figure out what you will need, then design a data model that supports it, and populate that data model with semi-dynamic data (via batch jobs for instance) and use the SQL Engine to do the heavy lifting via standard SQL.
If you really need the right way then you can use Google's recently open sourced libphonenumber
This bug is filed here. This is a bug of android devices having API level less than 12. You've to put correct versions of your layouts in drawable-v12 folder which will be used for API level 12 or higher. And an erroneous version(corners switched/reversed) of the same layout will be put in the default drawable folder which will be used by the devices having API level less than 12.
For example: I had to design a button with rounded corner at bottom-right.
In 'drawable' folder - button.xml: I had to make bottom-left corner rounded.
<shape>
<corners android:bottomLeftRadius="15dp"/>
</shape>
In 'drawable-v12' folder - button.xml: Correct version of the layout was placed here to be used for API level 12 or higher.
<shape>
<corners android:bottomLeftRadius="15dp"/>
</shape>
Every method needs to accept one argument: The instance itself (or the class if it is a static method).
a = range(1,10)
itemsToRemove = set([2, 3, 7])
b = filter(lambda x: x not in itemsToRemove, a)
or
b = [x for x in a if x not in itemsToRemove]
Don't create the set inside the lambda
or inside the comprehension. If you do, it'll be recreated on every iteration, defeating the point of using a set at all.
You can configure patterns to hide files and folders from the explorer and searches.
File > Preferences > Settings
). This will open the setting screen.files:exclude
in the search at the top.node_modules/
then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic. When you are done it should look something like this:
If you want to directly edit the settings file: For example to hide a top level node_modules folder in your workspace:
"files.exclude": {
"node_modules/": true
}
To hide all files that start with ._
such as ._.DS_Store
files found on OSX:
"files.exclude": {
"**/._*": true
}
You also have the ability to change Workspace Settings (Main menu: File > Preferences > Workspace Settings
). Workspace settings will create a .vscode/settings.json
file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing User and Workspace Settings.
I added the following VM Options and it worked for me:
-Dcom.sun.management.jmxremote=
-Dcom.sun.management.jmxremote.port=1099
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
Instead of YourCollection.FirstOrDefault()
, you could use YourCollection.DefaultIfEmpty(YourDefault).First()
for example.
Just use Analyze | Inspect Code
with appropriate inspection enabled (Unused declaration under Declaration redundancy group).
Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"
private String betweenComma(ArrayList<String> strings) {
String united = "";
for (String string : strings) {
united = united + "," + string;
}
return united.replaceFirst(",", "");
}
You should use the excellent OpenCSV for reading and writing CSV files. To adapt your example to use the library it would look like this:
public class ParseCSV {
public static void main(String[] args) {
try {
//csv file containing data
String strFile = "C:/Users/rsaluja/CMS_Evaluation/Drupal_12_08_27.csv";
CSVReader reader = new CSVReader(new FileReader(strFile));
String [] nextLine;
int lineNumber = 0;
while ((nextLine = reader.readNext()) != null) {
lineNumber++;
System.out.println("Line # " + lineNumber);
// nextLine[] is an array of values from the line
System.out.println(nextLine[4] + "etc...");
}
}
}
}
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
I solved my own problem when using google distance matrix API by setting my request header with Jquery ajax. take a look below.
var settings = {
'cache': false,
'dataType': "jsonp",
"async": true,
"crossDomain": true,
"url": "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=place_id:"+me.originPlaceId+"&destinations=place_id:"+me.destinationPlaceId+"®ion=ng&units=metric&key=mykey",
"method": "GET",
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Note what i added at the settings
**
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
**
I hope this helps.
This is explicitly throwing an error. It says whichever thread created a view, only that can touch its views. It is because the created view is inside that thread's space. The view creation (GUI) happens in the UI (main) thread. So, you always use the UI thread to access those methods.
In the above picture, the progress variable is inside the space of the UI thread. So, only the UI thread can access this variable. Here, you're accessing progress via new Thread(), and that's why you got an error.
@Anothen and @Number8 - The Vector class is not available in Silverlight, so to make it work we just need to keep a record of the last position sighted the last time the MouseMove event was called, and compare the two points to find the difference; then adjust the transform.
XAML:
<Border Name="viewboxBackground" Background="Black">
<Viewbox Name="viewboxMain">
<!--contents go here-->
</Viewbox>
</Border>
Code-behind:
public Point _mouseClickPos;
public bool bMoving;
public MainPage()
{
InitializeComponent();
viewboxMain.RenderTransform = new CompositeTransform();
}
void MouseMoveHandler(object sender, MouseEventArgs e)
{
if (bMoving)
{
//get current transform
CompositeTransform transform = viewboxMain.RenderTransform as CompositeTransform;
Point currentPos = e.GetPosition(viewboxBackground);
transform.TranslateX += (currentPos.X - _mouseClickPos.X) ;
transform.TranslateY += (currentPos.Y - _mouseClickPos.Y) ;
viewboxMain.RenderTransform = transform;
_mouseClickPos = currentPos;
}
}
void MouseClickHandler(object sender, MouseButtonEventArgs e)
{
_mouseClickPos = e.GetPosition(viewboxBackground);
bMoving = true;
}
void MouseReleaseHandler(object sender, MouseButtonEventArgs e)
{
bMoving = false;
}
Also note that you don't need a TransformGroup or collection to implement pan and zoom; instead, a CompositeTransform will do the trick with less hassle.
I'm pretty sure this is really inefficient in terms of resource usage, but at least it works :)
Basically we can create spring container object in two ways
both are the interfaces,
using implementation classes we can create object for spring container
coming to the differences
BeanFactory :
Does not support the Annotation based dependency Injection.
Doesn't Support I18N.
By default its support Lazy loading.
it doesn't allow configure to multiple configuration files.
ex: BeanFactory context=new XmlBeanFactory(new Resource("applicationContext.xml"));
ApplicationContext
Support Annotation based dependency Injection.-@Autowired, @PreDestroy
Support I18N
Its By default support Aggresive loading.
It allow to configure multiple configuration files.
ex:
ApplicationContext context=new ClasspathXmlApplicationContext("applicationContext.xml");
A simple method involves using the get and set functions on the variable
using System;
public string Name{
get{
return name;
}
set{
name= value;
OnVarChange?.Invoke();
}
}
private string name;
public event System.Action OnVarChange;
Install Java 7u21 from: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR
Set these variables:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
Run your app and have fun :)
You can use a pseudo-element to insert that character before each list item:
ul {_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
content: '?';_x000D_
}
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
Check whether you have given python PATH in environmental variables properly.
If not, then set python path. Then use:
$ python -m notebook
select id, group_concat(`Name` separator ',') as `ColumnName`
from
(
select
id,
concat(`Name`, ':', group_concat(`Value` separator ',')) as `Name`
from mytbl
group by
id,
`Name`
) tbl
group by id;
You can see it implemented here : Sql Fiddle Demo. Exactly what you need.
Update Splitting in two steps. First we get a table having all values(comma separated) against a unique[Name,id]. Then from obtained table we get all names and values as a single value against each unique id See this explained here SQL Fiddle Demo (scroll down as it has two result sets)
Edit There was a mistake in reading question, I had grouped only by id. But two group_contacts are needed if (Values are to be concatenated grouped by Name and id and then over all by id). Previous answer was
select
id,group_concat(concat(`name`,':',`value`) separator ',')
as Result from mytbl group by id
You can see it implemented here : SQL Fiddle Demo
Unfortunately @BrianFreud's answer doesn't fit my needs, I had a little different need, and I know that is not the answer for @BrianFreud's question, but I am leaving it here because a lot of persons got here with my same need. I needed something like 'How to get a file or blob from an URL?', and the current correct answer does not fit my needs because its not cross-domain.
I have a website that consumes images from an Amazon S3/Azure Storage, and there I store objects named with uniqueidentifiers:
sample: http://****.blob.core.windows.net/systemimages/bf142dc9-0185-4aee-a3f4-1e5e95a09bcf
Some of this images should be download from our system interface. To avoid passing this traffic through my HTTP server, since this objects does not require any security to be accessed (except by domain filtering), I decided to make a direct request on user's browser and use local processing to give the file a real name and extension.
To accomplish that I have used this great article from Henry Algus: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
1. First step: Add binary support to jquery
/**
*
* jquery.binarytransport.js
*
* @description. jQuery ajax transport for making binary data type requests.
* @version 1.0
* @author Henry Algus <[email protected]>
*
*/
// use this transport for "binary" data type
$.ajaxTransport("+binary", function (options, originalOptions, jqXHR) {
// check for conditions and support for blob / arraybuffer response type
if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
return {
// create new XMLHttpRequest
send: function (headers, callback) {
// setup all variables
var xhr = new XMLHttpRequest(),
url = options.url,
type = options.type,
async = options.async || true,
// blob or arraybuffer. Default is blob
dataType = options.responseType || "blob",
data = options.data || null,
username = options.username || null,
password = options.password || null;
xhr.addEventListener('load', function () {
var data = {};
data[options.dataType] = xhr.response;
// make callback and send data
callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
});
xhr.open(type, url, async, username, password);
// setup custom headers
for (var i in headers) {
xhr.setRequestHeader(i, headers[i]);
}
xhr.responseType = dataType;
xhr.send(data);
},
abort: function () {
jqXHR.abort();
}
};
}
});
2. Second step: Make a request using this transport type.
function downloadArt(url)
{
$.ajax(url, {
dataType: "binary",
processData: false
}).done(function (data) {
// just my logic to name/create files
var filename = url.substr(url.lastIndexOf('/') + 1) + '.png';
var blob = new Blob([data], { type: 'image/png' });
saveAs(blob, filename);
});
}
Now you can use the Blob created as you want to, in my case I want to save it to disk.
3. Optional: Save file on user's computer using FileSaver
I have used FileSaver.js to save to disk the downloaded file, if you need to accomplish that, please use this javascript library:
https://github.com/eligrey/FileSaver.js/
I expect this to help others with more specific needs.
Try something like:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
event.preventDefault();
$(this).next('div').slideToggle(200);
});
Here is the page about that in the jQuery documentation
In addition, you can build the binary package using the --binary option.
R CMD build --binary RJSONIO_0.2-3.tar.gz
I always do this,
f = open('filename.txt', 'a')
f.write("stuff")
f.close()
It's simple, but very useful.
You need to do a forceful push after rebasing against master
Don't forget that you can also use HTML to detect IE8.
<!--[if IE 8]>
<script type="text/javascript">
ie = 8;
</script>
<![endif]-->
Having that before all your scripts will let you just check the "ie" variable or whatever.
You're missing a GROUP BY clause:
SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.
You can add this method to your Status enum:
public static String getStringValueFromInt(int i) {
for (Status status : Status.values()) {
if (status.getValue() == i) {
return status.toString();
}
}
// throw an IllegalArgumentException or return null
throw new IllegalArgumentException("the given number doesn't match any Status.");
}
public static void main(String[] args) {
System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}
If you use "hg remove b"
against a file with "A" status, which means it has been added but not commited, Mercurial will respond:
not removing b: file has been marked for add (use forget to undo)
This response is a very clear explication of the difference between remove and forget.
My understanding is that "hg forget"
is for undoing an added but not committed file so that it is not tracked by version control; while "hg remove"
is for taking out a committed file from version control.
This thread has a example for using hg remove
against files of 7 different types of status.
My problem was a duplicate Product Module Name
for both the Action Extension I created and the main target. The solution was changing the Product module name (Under Build Settings) for the Extension.
(XCode 11)
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
Using command line, you can do this:
AT \\computername time "NET STOP servicename"
AT \\computername time "NET START servicename"
What about creating an additional wrapper class?
package com.naveen.research.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class PreparedStatementWrapper implements AutoCloseable {
protected PreparedStatement stat;
public PreparedStatementWrapper(Connection con, String query, Object ... params) throws SQLException {
this.stat = con.prepareStatement(query);
this.prepareStatement(params);
}
protected abstract void prepareStatement(Object ... params) throws SQLException;
public ResultSet executeQuery() throws SQLException {
return this.stat.executeQuery();
}
public int executeUpdate() throws SQLException {
return this.stat.executeUpdate();
}
@Override
public void close() {
try {
this.stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Then in the calling class you can implement prepareStatement method as:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatementWrapper stat = new PreparedStatementWrapper(con, query,
new Object[] { 123L, "TEST" }) {
@Override
protected void prepareStatement(Object... params) throws SQLException {
stat.setLong(1, Long.class.cast(params[0]));
stat.setString(2, String.valueOf(params[1]));
}
};
ResultSet rs = stat.executeQuery();) {
while (rs.next())
System.out.println(String.format("%s, %s", rs.getString(2), rs.getString(1)));
} catch (SQLException e) {
e.printStackTrace();
}
Maybe something like:
$(".subclass", this);
for example:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"
android:src="@drawable/icon"
/>
Add property android:scaleType="fitCenter"
and android:adjustViewBounds="true"
.
<div id="image">Example to have Background Image</div>
We need to Add the below content in Style tag:
.image {
background-image: url('C:\Users\ajai\Desktop\10.jpg');
}
Firefox 26 supports image-orientation: from-image
: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)
There is also a bug to implement this in Chrome.
Beware that this property is only supported by Firefox and is likely to be deprecated.
You need to recalculate width and height after first condition. Here is the code of entire script:
$(document).ready(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
}
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
});
Keep the h2 at the top, then pull-left on the p and pull-right on the login-box
<div class='container'>
<div class='hero-unit'>
<h2>Welcome</h2>
<div class="pull-left">
<p>Please log in</p>
</div>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<div class="clearfix"></div>
</div>
</div>
the default vertical-align on floated boxes is baseline, so the "Please log in" exactly lines up with the "Username" (check by changing the pull-right to pull-left).
I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
This solved the issue for me:
Uninstall the Visual Studio 2010 redistributable package if you have it installed already, and then install Microsoft Windows 7 SDK.
I changed loaders to rules in the webpack.config.js
file and updated the packages html-webpack-plugin
, webpack
, webpack-cli
, webpack-dev-server
to the latest version then it worked for me!
def touch(fname):
if os.path.exists(fname):
os.utime(fname, None)
else:
open(fname, 'a').close()
You must use a unique filename(s). Like this
<img src="cars.png?1287361287" alt="">
But this technique means high server usage and bandwidth wastage. Instead, you should use the version number or date. Example:
<img src="cars.png?2020-02-18" alt="">
But you want it to never serve image from cache. For this, if the page does not use page cache, it is possible with PHP or server side.
<img src="cars.png?<?php echo time();?>" alt="">
However, it is still not effective. Reason: Browser cache ... The last but most effective method is Native JAVASCRIPT. This simple code finds all images with a "NO-CACHE" class and makes the images almost unique. Put this between script tags.
var items = document.querySelectorAll("img.NO-CACHE");
for (var i = items.length; i--;) {
var img = items[i];
img.src = img.src + '?' + Date.now();
}
USAGE
<img class="NO-CACHE" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png" alt="">
RESULT(s) Like This
https://example.com/image.png?1582018163634
Had that issue on Ubuntu 14.04, In my case I had also libXtst.so missing:
Could not open library 'libXtst.so': libXtst.so: cannot open shared object
file: No such file or directory
Make sure your symbolic link is pointing to proper file, cd /usr/lib/x86_64-linux-gnu and list libXtst with:
ll |grep libXtst
lrwxrwxrwx 1 root root 16 Oct 7 2016 libXtst.so.6 -> libXtst.so.6.1.0
-rw-r--r-- 1 root root 22880 Aug 16 2013 libXtst.so.6.1.0
Then just create proper symbolic link using:
sudo ln -s libXtst.so.6 libXtst.so
List again:
ll | grep libXtst
lrwxrwxrwx 1 root root 12 Sep 20 10:23 libXtst -> libXtst.so.6
lrwxrwxrwx 1 root root 12 Sep 20 10:23 libXtst.so -> libXtst.so.6
lrwxrwxrwx 1 root root 16 Oct 7 2016 libXtst.so.6 -> libXtst.so.6.1.0
-rw-r--r-- 1 root root 22880 Aug 16 2013 libXtst.so.6.1.0
all set!
I was facing similar problem on Windows 7 x64 professional edition. Please note following steps to fix this problem.
tools.jar is missing from required path if you are using jdk1.7 x64 bit version.
Please install x86 version of jdk1.7
Set JDK_HOME="C:\Program Files (x86)\Java\jdk1.7.0_67" and update path environment variable as path="C:\Program Files (x86)\Java\jdk1.7.0_67\bin" Note: Linux put the proper path.
Launch 32 bit application from /android-studio\bin folder.
I tested and verified these steps on windows 7 with 32 bit jdk1.7
Mutations expect two arguments: state
and payload
, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.
The easiest way to pass a number of parameters is to destruct them:
mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token);
localStorage.setItem('expiration', expiration);
}
}
Then later on in your actions you can simply
store.commit('authenticate', {
token,
expiration,
});
This
Example:
objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";
Considering the String
you're asking about is
C:\Hello\AnotherFolder\The File Name.PDF
we need to extract everything after the last separator, ie. \
. That is what we are interested in.
You can do
String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);
This will retrieve the index of the last \
in your String
and extract everything that comes after it into fileName
.
If you have a String
with a different separator, adjust the lastIndexOf
to use that separator. (There's even an overload that accepts an entire String
as a separator.)
I've omitted it in the example above, but if you're unsure where the String
comes from or what it might contain, you'll want to validate that the lastIndexOf
returns a non-negative value because the Javadoc states it'll return
-1 if there is no such occurrence
MySQL's utf8
permits only the Unicode characters that can be represented with 3 bytes in UTF-8. Here you have a character that needs 4 bytes: \xF0\x90\x8D\x83 (U+10343 GOTHIC LETTER SAUIL).
If you have MySQL 5.5 or later you can change the column encoding from utf8
to utf8mb4
. This encoding allows storage of characters that occupy 4 bytes in UTF-8.
You may also have to set the server property character_set_server
to utf8mb4
in the MySQL configuration file. It seems that Connector/J defaults to 3-byte Unicode otherwise:
For example, to use 4-byte UTF-8 character sets with Connector/J, configure the MySQL server with
character_set_server=utf8mb4
, and leavecharacterEncoding
out of the Connector/J connection string. Connector/J will then autodetect the UTF-8 setting.
Update for macOS Sierra 10.12.6 - Android Studio for Mac 2.3.3
Locate the sdkmanager file usually under:
/Users/YOUR_MAC_USER/Library/Android/sdk/tools/bin
./sdkmanager --licenses
Warning: File /Users/mtro.josevaler**strong text**io/.android/repositories.cfg
could not be loaded.
6 of 6 SDK package licenses not accepted.
Review licenses that have not been accepted (y/N)? Y
To validate the problem has gone just repeat the operation involved in the license issue.
Here’s a more robust answer than the currently accepted one:
jQuery.expr[':'].focus = function(elem) {
return elem === document.activeElement && (elem.type || elem.href);
};
Note that the (elem.type || elem.href)
test was added to filter out false positives like body
. This way, we make sure to filter out all elements except form controls and hyperlinks.
This is so many worlds of bad, because your question implies that you probably have gaping SQL injection holes in your application.
You should be using parameterized statements. For Java, use PreparedStatement
with placeholders. You say you don't want to use parameterised statements, but you don't explain why, and frankly it has to be a very good reason not to use them because they're the simplest, safest way to fix the problem you are trying to solve.
See Preventing SQL Injection in Java. Don't be Bobby's next victim.
There is no public function in PgJDBC for string quoting and escaping. That's partly because it might make it seem like a good idea.
There are built-in quoting functions quote_literal
and quote_ident
in PostgreSQL, but they are for PL/PgSQL
functions that use EXECUTE
. These days quote_literal
is mostly obsoleted by EXECUTE ... USING
, which is the parameterised version, because it's safer and easier. You cannot use them for the purpose you explain here, because they're server-side functions.
Imagine what happens if you get the value ');DROP SCHEMA public;--
from a malicious user. You'd produce:
insert into test values (1,'');DROP SCHEMA public;--');
which breaks down to two statements and a comment that gets ignored:
insert into test values (1,'');
DROP SCHEMA public;
--');
Whoops, there goes your database.
As of Swift 3 / 4 / 5, this is done as follows.
To add a new element to the end of an Array.
anArray.append("This String")
To append a different Array to the end of your Array.
anArray += ["Moar", "Strings"]
anArray.append(contentsOf: ["Moar", "Strings"])
To insert a new element into your Array.
anArray.insert("This String", at: 0)
To insert the contents of a different Array into your Array.
anArray.insert(contentsOf: ["Moar", "Strings"], at: 0)
More information can be found in the "Collection Types" chapter of "The Swift Programming Language", starting on page 110.
The numbers generated by
=NORMINV(RAND(),10,7)
are uniformally distributed. If you want the numbers to be normally distributed, you will have to write a function I guess.
As Tariq Khan suggested, I did the same thing and it worked out..
FIX UBUNTU 14.10 UNICORN APT-GET UPDATE
Backup the repo first
$ sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup
$ sudo vi /etc/apt/sources.list
rename us.archive or archive in http://us.archive.ubuntu.com/ubuntu/ as http://old-release.ubuntu.com/ubuntu/
rename http://security.ubuntu.com/ubuntu/dists/saucy-security/universe/binary-i386/Packages as http://old-releases.ubuntu.com/ubuntu/dists/saucy-security/universe/binary-i386/Packages
$ sudo apt-get update
There are 3 ways to allow cross domain origin (excluding jsonp
):
1) Set the header in the page directly using a templating language like PHP. Keep in mind there can be no HTML before your header or it will fail.
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
2) Modify the server configuration file (apache.conf
) and add this line. Note that "*"
represents allow all. Some systems might also need the credential set. In general allow all access is a security risk and should be avoided:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true
3) To allow multiple domains on Apache web servers add the following to your config file
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(example.org|example.com)$" AccessControlAllowOrigin=$0$1
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true
</IfModule>
4) For development use only hack your browser and allow unlimited CORS using the Chrome Allow-Control-Allow-Origin extension
5) Disable CORS in Chrome: Quit Chrome completely. Open a terminal and execute the following. Just be cautious you are disabling web security:
open -a Google\ Chrome --args --disable-web-security --user-data-dir
An example would be nice - here's a trivial one
for %I in (*.*) do @echo %~xI
it lists only the EXTENSIONS of each file in current folder
for more useful variable combinations (also listed in previous response) from the CMD prompt execute: HELP FOR
which contains this snippet
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
environment variable for %I and expands to the
drive letter and path of the first one found.
%~ftzaI - expands %I to a DIR like output line
Asterisk symbol (*) is used to check values in the array, not the array itself.
$validator = Validator::make($request->all(), [
"names" => "required|array|min:3",
"names.*" => "required|string|distinct|min:3",
]);
In the example above:
EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:
$data = $request->validate([
"name" => "required|array|min:3",
"name.*" => "required|string|distinct|min:3",
]);
simple and easy
Locale locale = new Locale("en", "US");
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = locale;
res.updateConfiguration(conf, dm);
where "en" is language code and "US" is country code.
Beside the given approaches with a two pass approach, you could take a single loop approach by pushing the group if a new group is found.
var array = [{ group: "one", color: "red" }, { group: "two", color: "blue" }, { group: "one", color: "green" }, { group: "one", color: "black" }],_x000D_
groups = Object.create(null),_x000D_
grouped = [];_x000D_
_x000D_
array.forEach(function (o) {_x000D_
if (!groups[o.group]) {_x000D_
groups[o.group] = [];_x000D_
grouped.push({ group: o.group, color: groups[o.group] });_x000D_
}_x000D_
groups[o.group].push(o.color);_x000D_
});_x000D_
_x000D_
console.log(grouped);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
I thought I would draw your attention that in the specific context where a listener was defined within a jQuery plugin, then the only thing that successfully simulated the keypress event for me, eventually caught by that listener, was to use setTimeout(). e.g.
setTimeout(function() { $("#txtName").keypress() } , 1000);
Any use of $("#txtName").keypress()
was ignored, although placed at the end of the .ready() function
. No particular DOM supplement was being created asynchronously anyway.
I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL
my_value := regexp_replace(my_value, '[[:space:]]*','');
Quick fix for CGRectMake , CGPointMake, CGSizeMake in Swift3 & iOS10
Add these extensions :
extension CGRect{
init(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) {
self.init(x:x,y:y,width:width,height:height)
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
extension CGPoint{
init(_ x:CGFloat,_ y:CGFloat) {
self.init(x:x,y:y)
}
}
Then go to "Find and Replace in Workspace" Find CGRectMake , CGPointMake, CGSizeMake and Replace them with CGRect , CGPoint, CGSize
These steps might save all the time as Xcode right now doesn't give us quick conversion from Swift 2+ to Swift 3
SELECT DISTINCT MAX(salary) AS max
FROM STAFF
WHERE salary IN
(SELECT salary
FROM STAFF
WHERE salary<(SELECT MAX(salary) AS maxima
FROM STAFF
WHERE salary<
(SELECT MAX(salary) AS maxima
FROM STAFF))
GROUP BY salary);
I have tried other ways they are not right. This one works.
How about
List<object> collection = new List<object>((IEnumerable)myObject);
I've gotten this error when running a scalar function using a table value, but the Select statement in my scalar function RETURN clause was missing the "FROM table" portion. :facepalms:
I'd say this is an indicator of a flawed table structure. Perhaps the different location types should be separated in different tables, enabling you to do much richer querying and also avoid having superfluous columns around.
If you're unable to change the structure, something like the below might work:
SELECT
*
FROM
Test
WHERE
Account_Location = (
CASE LocationType
WHEN 'location' THEN @locationID
ELSE Account_Location
END
)
AND
Account_Location_Area = (
CASE LocationType
WHEN 'area' THEN @locationID
ELSE Account_Location_Area
END
)
And so forth... We can't change the structure of the query on the fly, but we can override it by making the predicates equal themselves out.
EDIT: The above suggestions are of course much better, just ignore mine.
(n,) and (n,1) are not the same shape. Try casting the vector to an array by using the [:, None]
notation:
n_lists = np.append(n_list_converted, n_last[:, None], axis=1)
Alternatively, when extracting n_last
you can use
n_last = n_list_converted[:, -1:]
to get a (20, 1)
array.
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}
Note: The cast to (Suit[])
is not strictly necessary, but it does make the code 0.5 ns faster.
Change permanent
conda install python={version}
Change Temporarily
View your environments
run conda info --envs
on your terminal window or an Anconda Prompt
If It doesn't show environment that you want to install
run conda create -n py36 python=3.6 anaconda
for python 3.6 change version as your prefer
Activating an environment (use Anaconda prompt)
run activate envnme
envnme you can find by this commandconda info --envs
as a example when you run conda info --envs
it show
base * C:\Users\DulangaHeshan\Anaconda3
py36 C:\Users\DulangaHeshan\Anaconda3\envs\py36
then run activate py36
to check run python --version
In Windows, it is good practice to deactivate one environment before activating another. https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html?highlight=deactivate%20environment
For the block element not occupy the whole line, set it's width to something small and the white-space:nowrap
label
{
width:10px;
display:block;
white-space:nowrap;
}
Whatever your separator is in your ls.dat, you can specify it to gnuplot:
set datafile separator "\t"
Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...
If one uses gcc (clang?) and have -Werror
and -Wbad-function-cast
defined,
int val = (int)pow(10,9);
will result:
error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]
(for a good reason, overflow and where values are rounded needs to be thought out)
EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).
After properly thought out (that parameters to pow() are good), int val = pow(10,9);
seems to work with gcc 9.2 x86-64 ...
but note:
printf("%d\n", pow(10,4));
may output e.g.
-1121380856
(did for me) where
int i = pow(10,4); printf("%d\n", i);
printed
10000
in one particular case I tried.
go to the url about:config
and paste each line:
network.http.keep-alive.timeout;10
network.http.connection-retry-timeout;10
network.http.pipelining.read-timeout;5
network.http.connection-timeout;10
I'm guessing that you don't need to re-increment the existing data so, why can't you just run a simple ALTER TABLE command to change the PK's attributes?
Something like:
ALTER TABLE `content` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT
I've tested this code on my own MySQL database and it works but I have not tried it with any meaningful number of records. Once you've altered the row then you need to reset the increment to a number guaranteed not to interfere with any other records.
ALTER TABLE `content` auto_increment = MAX(`id`) + 1
Again, untested but I believe it will work.
Stackoverflow uses such function to determine the age of a user.
The given answer is
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
So your helper method would look like
public static string Age(this HtmlHelper helper, DateTime birthday)
{
DateTime now = DateTime.Today;
int age = now.Year - birthday.Year;
if (now < birthday.AddYears(age)) age--;
return age.ToString();
}
Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.
public static int GetAge(DateTime reference, DateTime birthday)
{
int age = reference.Year - birthday.Year;
if (reference < birthday.AddYears(age)) age--;
return age;
}
The name
attribute is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different id
attributes, but the same name
. When submitted, there is just the one value in the response - the radio button you selected.
Of course, there's more to it than that, but it will definitely get you thinking in the right direction.
I think you are confusing objects and classes. A class inside a class looks like this:
class Foo(object):
class Bar(object):
pass
>>> foo = Foo()
>>> bar = Foo.Bar()
But it doesn't look to me like that's what you want. Perhaps you are after a simple containment hierarchy:
class Player(object):
def __init__(self, ... airplanes ...) # airplanes is a list of Airplane objects
...
self.airplanes = airplanes
...
class Airplane(object):
def __init__(self, ... flights ...) # flights is a list of Flight objects
...
self.flights = flights
...
class Flight(object):
def __init__(self, ... duration ...)
...
self.duration = duration
...
Then you can build and use the objects thus:
player = Player(...[
Airplane(... [
Flight(...duration=10...),
Flight(...duration=15...),
] ... ),
Airplane(...[
Flight(...duration=20...),
Flight(...duration=11...),
Flight(...duration=25...),
]...),
])
player.airplanes[5].flights[6].duration = 5
One way to control the locale settings is to set the java system properties user.language and user.region.
Here it is:
rfc2616#section-10.4.1 - 400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
rfc7231#section-6.5.1 - 6.5.1. 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
Refers to malformed (not wellformed) cases!
rfc4918 - 11.2. 422 Unprocessable Entity
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Conclusion
Rule of thumb: [_]00 covers the most general case and cases that are not covered by designated code.
422 fits best object validation error (precisely my recommendation:)
As for semantically erroneous - Think of something like "This username already exists" validation.
400 is incorrectly used for object validation
umount -f -t cifs -l /mnt &
Be careful of &
, let umount
run in background.
umount
will detach filesystem first, so you will find nothing abount /mnt
. If you run df
command, then it will umount /mnt
forcibly.
As noted in the official documentation, simply apply the class(es) btn btn-link
:
<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">Link</button>
For example, with the code you have provided:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<form action="..." method="post">_x000D_
<div class="row-fluid">_x000D_
<!-- Navigation for the form -->_x000D_
<div class="span3">_x000D_
<ul class="nav nav-tabs nav-stacked">_x000D_
<li>_x000D_
<button class="btn btn-link" role="link" type="submit" name="op" value="Link 1">Link 1</button>_x000D_
</li>_x000D_
<li>_x000D_
<button class="btn btn-link" role="link" type="submit" name="op" value="Link 2">Link 2</button>_x000D_
</li>_x000D_
<!-- ... -->_x000D_
</ul>_x000D_
</div>_x000D_
<!-- The actual form -->_x000D_
<div class="span9">_x000D_
<!-- ... -->_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
Apparently you can subtract the number of days you want from a datetime.
SELECT GETDATE() - 1
2016-12-25 15:24:50.403
the below codes helped me with the same problem. Let me know if it helped.
<!DOCTYPE html>
<html>
<body>
<audio controls>
<source src="YOUR AUDIO FILE" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
Also internationalization.
I fooled around with this some a while back. Did this in my model:
[Display(Name = "XXX", ResourceType = typeof(Labels))]
I had a separate class library for all the resources, so I had Labels.resx, Labels.culture.resx, etc.
In there I had key = XXX, value = "meaningful string in that culture."
You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.
$('#myForm').submit(function() {
$('select').removeAttr('disabled');
});
Note that if you rely on this method, you'll want to disable it programmatically as well, because if JS is disabled or not supported, you'll be stuck with the disabled select.
$(document).ready(function() {
$('select').attr('disabled', 'disabled');
});
Use value instanceof YourClass
Ambiguous date formats are interpreted according to the language of the login. This works
set dateformat mdy
select CAST('03/28/2011 18:03:40' AS DATETIME)
This doesn't
set dateformat dmy
select CAST('03/28/2011 18:03:40' AS DATETIME)
If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss
Simple and easy in javascipt
<script>
document.getElementById("selectsearch").addEventListener("change", function(){
var get_form = document.getElementById("search-form") // get form
get_form.action = '/search/' + this.value; // assign value
});
</script>
I just had to implement a method that automatically finds conflicts between a repository and its remote. This solution does the merge in memory so it won't touch the index, nor the working tree. I think this is the safest possible way you can solve this problem. Here's how it works:
git fetch origin master
git merge-base FETCH_HEAD master
git merge-tree mergebase master FETCH_HEAD
(mergebase is the hexadecimal id that merge-base printed in the previous step)Now suppose that you want to merge the remote master with your local master, but you can use any branches. git merge-tree
will execute the merge in memory and print the result to the standard output. Grep for the pattern <<
or >>
. Or you can print the output to a file and check that. If you find a line starting with 'changed in both' then most probably there will be a conflict.
You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:
Set<Integer> set = new TreeSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
//good way:
Iterator<Integer> iterator = set.iterator();
while(iterator.hasNext()) {
Integer setElement = iterator.next();
if(setElement==2) {
iterator.remove();
}
}
//bad way:
for(Integer setElement:set) {
if(setElement==2) {
//might work or might throw exception, Java calls it indefined behaviour:
set.remove(setElement);
}
}
As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :
Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:
https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html
stipulate, amongst others, that (emphasis mine):
"For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)
"Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."
To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).
This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.
Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.
We use the Url Rewrite extension for IIS for redirecting all HTTP requests to HTTPS. When trying to call a service not using transport security on an http://... address, this is the error that appeared.
So it might be worth checking if you can hit both the http and https addresses of the service via a browser and that it doesn't auto forward you with a 303 status code.
LAST EDIT: after 7 years I'm still getting upvotes for this answer, but I guess this one is now much more accurate.
Sure you can, but you'll need to render the page with something. If you really want to only use php, I suggest you HTMLTOPS, which renders the page and outputs it in a ps file (ghostscript), then, convert it in a .jpg, .png, .pdf.. can be little slower with complex pages (and don't support all the CSS).
Else, you can use wkhtmltopdf to output a html page in pdf, jpg, whatever.. Accept CSS2.0, use the webkit (safari's wrapper) to render the page.. so should be fine. You have to install it on your server, as well..
UPDATE Now, with new HTML5 and JS feature, is also possible to render the page into a canvas object using JavaScript. Here a nice library to do that: Html2Canvas and here is an implementation by the same author to get a feedback like G+. Once you have rendered the dom into the canvas, you can then send to the server via ajax and save it as a jpg.
EDIT: You can use the imagemagick tool for transforming pdf to png. My version of wkhtmltopdf does not support images. E.g. convert html.pdf -append html.png
.
EDIT: This small shell script gives a simple / but working usage example on linux with php5-cli and the tools mentioned above.
EDIT: i noticed now that the wkhtmltopdf team is working on another project: wkhtmltoimage, that gives you the jpg directly
private void PostForm()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dork.com/service");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postData ="home=Cosby&favorite+flavor=flies";
byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var result = reader.ReadToEnd();
stream.Dispose();
reader.Dispose();
}
Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)
then... v. SQL> connect /as sysdba
Connected. [SQL prompt response]
vi. SQL> alter user SYS identified by "newpassword";
User altered. [SQL prompt response]
Thank you. This minimized a headache
I can not use any of the answers here. No available jq, no shell arrays, no declare, no grep -P, no lookbehind and lookahead, no Python, no Perl, no Ruby, no - not even Bash... Remaining answers simply do not work well. JavaScript sounded familiar, but the tin says Nescaffe - so it is a no go, too :) Even if available, for my simple need - they would be overkill and slow.
Yet, it is extremely important for me to get many variables from the json formatted reply of my modem. I am doing it in a sh with very trimmed down BusyBox at my routers! No problems using awk alone: just set delimiters and read the data. For a single variable, that is all!
awk 'BEGIN { FS="\""; RS="," }; { if ($2 == "login") {print $4} }' test.json
Remember I have no arrays? I had to assign within the awk parsed data to the 11 variables which I need in a shell script. Wherever I looked, that was said to be an impossible mission. No problem with that, too.
My solution is simple. This code will: 1) parse .json file from the question (actually, I have borrowed a working data sample from the most upvoted answer) and pick out the quoted data, plus 2) create shell variables from within the awk assigning free named shell variable names.
eval $( curl -s 'https://api.github.com/users/lambda' |
awk ' BEGIN { FS="\""; RS="," };
{
if ($2 == "login") { print "Login=\""$4"\"" }
if ($2 == "name") { print "Name=\""$4"\"" }
if ($2 == "updated_at") { print "Updated=\""$4"\"" }
}' )
echo "$Login, $Name, $Updated"
No problems with blanks within. In my use, the same command parses a long single line output. As eval is used, this solution is suited for trusted data only. It is simple to adapt it to pickup unquoted data. For huge number of variables, marginal speed gain can be achieved using else if. Lack of array obviously means: no multiple records without extra fiddling. But where arrays are available, adapting this solution is a simple task.
@maikel sed answer almost works (but I can not comment on it). For my nicely formatted data - it works. Not so much with the example used here (missing quotes throw it off). It is complicated and difficult to modify. Plus, I do not like having to make 11 calls to extract 11 variables. Why? I timed 100 loops extracting 9 variables: the sed function took 48.99 sec and my solution took 0.91 sec! Not fair? Doing just a single extraction of 9 variables: 0.51 vs. 0.02 sec.
You certainly can. Others have pointed out correctly that you need to do i += 3
. You can't do what you have posted because all you are doing here is adding i + 3
but never assigning the result back to i
. i++
is just a shorthand for i = i + 1
, similarly i +=3
is a shorthand for i = i + 3
.
Faced the same issue. Changed the JRE to the correct 1.8 version and do a maven clean and build resolve the issue. You may need to change the Project Facet and verify the correct path.
You can see the history from ~/.mysql_history. However the content of the file is encoded by wctomb. To view the content:
shell> cat ~/.mysql_history | python2.7 -c "import sys; print(''.join([l.decode('unicode-escape') for l in sys.stdin]))"